diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..753e230 --- /dev/null +++ b/.htaccess @@ -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. + + php_flag magic_quotes_gpc off + php_flag magic_quotes_sybase off + php_flag register_globals off + + + +# Setting rewrite rules. + + RewriteEngine on + RewriteBase /%siteurlhere%/ + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule ^(.*)$ index.php [QSA,L] + \ No newline at end of file diff --git a/admin/index.php b/admin/index.php new file mode 100644 index 0000000..2a331dd --- /dev/null +++ b/admin/index.php @@ -0,0 +1,153 @@ +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 username or password', 'users'); + } + } + } else { + $login_error = __('Wrong username or password', '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(); \ No newline at end of file diff --git a/admin/themes/default/css/default.css b/admin/themes/default/css/default.css new file mode 100644 index 0000000..3f1d3db --- /dev/null +++ b/admin/themes/default/css/default.css @@ -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;} + diff --git a/admin/themes/default/img/header.png b/admin/themes/default/img/header.png new file mode 100644 index 0000000..6afc7b7 Binary files /dev/null and b/admin/themes/default/img/header.png differ diff --git a/admin/themes/default/img/overlay.png b/admin/themes/default/img/overlay.png new file mode 100644 index 0000000..56e0b8a Binary files /dev/null and b/admin/themes/default/img/overlay.png differ diff --git a/admin/themes/default/img/sidebar_bg.png b/admin/themes/default/img/sidebar_bg.png new file mode 100644 index 0000000..b6034f5 Binary files /dev/null and b/admin/themes/default/img/sidebar_bg.png differ diff --git a/admin/themes/default/index.template.php b/admin/themes/default/index.template.php new file mode 100644 index 0000000..71ec085 --- /dev/null +++ b/admin/themes/default/index.template.php @@ -0,0 +1,106 @@ + + + + + Monstra :: <?php echo __('Administration', 'system'); ?> + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +

+ +

+
+
+
+ + + +
+ +
+ + +
+

+
    + +
+
+ +

+
    + +
+
+ +

+
    + +
+
+ + + +
+ +
+
+
+ '.__('Plugin main admin function does not exist', 'system').'
'; + } + } else { + echo '
'.__('Plugin does not exist', 'system').'
'; + } + ?> +
+
+ +
+ + +
+ + + + + + + + + + \ No newline at end of file diff --git a/admin/themes/default/js/default.js b/admin/themes/default/js/default.js new file mode 100644 index 0000000..8d1d041 --- /dev/null +++ b/admin/themes/default/js/default.js @@ -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;} diff --git a/admin/themes/default/login.template.php b/admin/themes/default/login.template.php new file mode 100644 index 0000000..dc86771 --- /dev/null +++ b/admin/themes/default/login.template.php @@ -0,0 +1,120 @@ + + + + + Monstra :: <?php echo __('Administration', 'system'); ?> + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+
+


+
+ + + + + +
+
+ +
+
+
+ +
+
+
+


+
+ + + + +
+
+ +
+
+
+ - + ', 'system');?> + ', 'system');?> +
+
+
+
+ +
+ +
+ + + \ No newline at end of file diff --git a/backups/.empty b/backups/.empty new file mode 100644 index 0000000..e69de29 diff --git a/backups/.htaccess b/backups/.htaccess new file mode 100644 index 0000000..14249c5 --- /dev/null +++ b/backups/.htaccess @@ -0,0 +1 @@ +Deny from all \ No newline at end of file diff --git a/changelog.txt b/changelog.txt new file mode 100644 index 0000000..ce532de --- /dev/null +++ b/changelog.txt @@ -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 \ No newline at end of file diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..8fc932d Binary files /dev/null and b/favicon.ico differ diff --git a/index.php b/index.php new file mode 100644 index 0000000..36329b0 --- /dev/null +++ b/index.php @@ -0,0 +1,67 @@ + 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"); + } + } +?> + + + + + Monstra :: Install + + + + + + + + + + + + + +
+
+ en | + ru +
+
+
+
+
+
+
+
+ + + + + + + + + + + + + +
+ + +
+ + +
+ + +
+ + + + + +

+ +
+
+
+

+
+
    +
  • '.__('PHP 5.2 or greater is required', 'system').'
  • '; + } else { + echo '
  • '.__('PHP Version', 'system').' '.PHP_VERSION.'
  • '; + } + + if (in_array('SimpleXML', $php_modules)) { + echo '
  • '.__('Module SimpleXML is installed', 'system').'
  • '; + } else { + echo '
  • '.__('SimpleXML module is required', 'system').'
  • '; + } + + if (in_array('dom', $php_modules)) { + echo '
  • '.__('Module DOM is installed', 'system').'
  • '; + } else { + echo '
  • '.__('Module DOM is required', 'system').'
  • '; + } + + if (function_exists('apache_get_modules')) { + if ( ! in_array('mod_rewrite',apache_get_modules())) { + echo '
  • '.__('Apache Mod Rewrite is required', 'system').'
  • '; + } else { + echo '
  • '.__('Module Mod Rewrite is installed', 'system').'
  • '; + } + } else { + echo '
  • '.__('Module Mod Rewrite is installed', 'system').'
  • '; + } + + foreach ($dir_array as $dir) { + if (is_writable($dir.'/')) { + echo '
  • '.__('Directory: :dir writable', 'system', array(':dir' => $dir)).'
  • '; + } else { + echo '
  • '.__('Directory: :dir not writable', 'system', array(':dir' => $dir)).'
  • '; + } + } + + if (is_writable(__FILE__)){ + echo '
  • '.__('Install script writable', 'system').'
  • '; + } else { + echo '
  • '.__('Install script not writable', 'system').'
  • '; + } + + if (is_writable('sitemap.xml')){ + echo '
  • '.__('Sitemap file writable', 'system').'
  • '; + } else { + echo '
  • '.__('Sitemap file not writable', 'system').'
  • '; + } + + if (is_writable('.htaccess')){ + echo '
  • '.__('Main .htaccess file writable', 'system').'
  • '; + } else { + echo '
  • '.__('Main .htaccess not writable').'
  • '; + } + + if (isset($errors['sitename'])) echo '
  • '.$errors['sitename'].'
  • '; + if (isset($errors['siteurl'])) echo '
  • '.$errors['siteurl'].'
  • '; + if (isset($errors['login'])) echo '
  • '.$errors['login'].'
  • '; + if (isset($errors['password'])) echo '
  • '.$errors['password'].'
  • '; + if (isset($errors['email'])) echo '
  • '.$errors['email'].'
  • '; + if (isset($errors['email_valid'])) echo '
  • '.$errors['email_valid'].'
  • '; + ?> +
+ +
+ +
+
+ +
+ +
+ + + + diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..239ade4 --- /dev/null +++ b/license.txt @@ -0,0 +1,220 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +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. +This License refers to version 3 of the GNU General Public License. + +Copyright also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +The Program refers to any copyrightable work licensed under this License. Each licensee is addressed as you. Licensees and recipients may be individuals or organizations. + +To modify 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 modified version of the earlier work or a work based on the earlier work. + +A covered work means either the unmodified Program or a work based on the Program. + +To propagate 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 convey 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 Appropriate Legal Notices 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 source code for a work means the preferred form of the work for making modifications to it. Object code means any non-source form of a work. + +A Standard Interface 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 System Libraries 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 Major Component, 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 Corresponding Source 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 keep intact all notices. +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 aggregate 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 User Product is either (1) a consumer product, 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, normally used 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. + +Installation Information 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. +Additional permissions 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 further restrictions 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 entity transaction 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 contributor 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 contributor version. + +A contributor's essential patent claims 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, control 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 patent license 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 grant 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. Knowingly relying 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 discriminatory 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 or any later version 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 AS IS 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 copyright line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . +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: + + Copyright (C) + + 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 about box. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a copyright disclaimer for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +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 . \ No newline at end of file diff --git a/monstra/boot/defines.php b/monstra/boot/defines.php new file mode 100644 index 0000000..d415b03 --- /dev/null +++ b/monstra/boot/defines.php @@ -0,0 +1,148 @@ +'; } \ No newline at end of file diff --git a/monstra/bootstrap.php b/monstra/bootstrap.php new file mode 100644 index 0000000..3e5f560 --- /dev/null +++ b/monstra/bootstrap.php @@ -0,0 +1,81 @@ + 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 (" + + + + + Monstra + + + +
+

Monstra - ".$error_type."

+

".$exception->getMessage()."

+

Location

+

Exception thrown on line ".$exception->getLine()." in ".$exception->getFile()."

+ "); + + if ( ! empty($code)) { + echo '
'; + foreach ($code as $line) { + echo '
' . $line['number'] . '' . $line['code'] . '
'; + } + echo '
'; + } + + echo '
'; + + } else { + + // Production + echo (" + + + + + Monstra + + + +
+

Oops!

+

An unexpected error has occurred.

+
+ + + "); + } + + // 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", '', '', '<?php ', '#$@r4!/*'), + array('', '', '', '', '/*'), + highlight_string(' + * Option::add('pages_limit', 10); + * Option::add(array('pages_count' => 10, 'pages_default' => 'home')); + * + * + * @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 + * + * + * Option::update('pages_limit', 12); + * Option::update(array('pages_count' => 10, 'pages_default' => 'home')); + * + * + * @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 + * + * + * $pages_limit = Option::get('pages_limit'); + * if ($pages_limit == '10') { + * // do something... + * } + * + * + * @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 + * + * + * Option::delete('pages_limit'); + * + * + * @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.'"]'); + } + + } \ No newline at end of file diff --git a/monstra/engine/plugins.php b/monstra/engine/plugins.php new file mode 100644 index 0000000..3269bb2 --- /dev/null +++ b/monstra/engine/plugins.php @@ -0,0 +1,1206 @@ +select(null, 'all', null, array('location', 'frontend', 'backend', 'status', 'priority'), 'priority', 'ASC'); + + // Now include plugins from $records plugins array + // If plugin is active then load it to the system. + foreach ($records as $record) { + if ($record['status'] == 'active') { + include_once ROOT . DS . $record['location']; + } + } + } + + + /** + * Get plugin admin + * + * + * // Get admin for Blog plugin + * Plugin::admin('blog'); + * + * + * @param string $plug Plugin Name + * @param string $alt_folder Alternative plugin folder + */ + public static function admin($plug, $alt_folder = null) { + + // Redefine arguments + $plug = (string) $plug; + + // Plugin admin extension + $ext = '.admin.php'; + + // Plugin admin can be loaded only in backend + if (BACKEND) { + + // Plugin admin folder + if ( ! empty($alt_folder)) { + $folder = $alt_folder . DS . strtolower($plug); + } else { + $folder = strtolower($plug); + } + + // Path to plugin admin file + $path = PLUGINS . DS . $folder . DS . $plug . $ext; + + // Load plugin admin + if (File::exists($path)) { + include $path; + } + } + } + + + + /** + * Register new plugin in system + * + * + * // Register plugin + * Plugin::register( __FILE__, + * __('Blog'), + * __('Blog plugin'), + * '1.0.0', + * 'Awilum', + * 'http://example.org/', + * 'blog'); + * + * + * @param string $file Plugin file + * @param string $title Plugin title + * @param string $description Plugin description + * @param string $version Plugin version + * @param string $author Plugin author + * @param string $author_uri Plugin author uri + * @param string $component Plugin as component + * @param boolean $box Plugin as box + */ + public static function register($file, $title, $description = null, $version = null, $author = null, $author_uri = null, $component = null, $box = false) { + + // Redefine arguments + $file = (string) $file; + $title = (string) $title; + $description = ($description === null) ? null : (string) $description; + $version = ($version === null) ? null : (string) $version; + $author = ($author === null) ? null : (string) $author; + $author_uri = ($author_uri === null) ? null : (string) $author_uri; + $component = ($component === null) ? null : (string) $component; + $box = (bool) $box; + + + // Get plugin id from name.plugin.php + $id = strtolower(basename($file, '.plugin.php')); + + // Set plugin privilege 'box' if $box is true + if ($box) $privilege = 'box'; else $privilege = ''; + + // Register plugin in global plugins array. + Plugin::$plugins[$id] = array( + 'id' => $id, + 'title' => $title, + 'privilege' => $privilege, + 'version' => $version, + 'description' => $description, + 'author' => $author, + 'author_uri' => $author_uri, + ); + + // Add plugin as a component + // Plugin - component will be available at the link sitename/component_name + // Example: + // www.example.org/guestbook + // www.example.org/news + if ( ! empty($component)) { + Plugin::$components[] = $component; + } + } + + } + + + /** + * Frontend class + */ + class Frontend { + + public static function main() { } + public static function title() { return ''; } + public static function description() { return ''; } + public static function keywords() { return ''; } + public static function template() { return 'index'; } + public static function content() { return ''; } + + } + + + /** + * Backend class + */ + class Backend { + + public static function main() { } + + } + + + /** + * View class + */ + class View { + + + /** + * Path to view file. + * + * @var string + */ + protected $view_file; + + + /** + * View variables. + * + * @var array + */ + protected $vars = array(); + + + /** + * Global view variables. + * + * @var array + */ + protected static $global_vars = array(); + + + /** + * The output. + * + * @var string + */ + protected $output; + + + /** + * Create a new view object. + * + * + * // Create new view object + * $view = new View('blog/views/backend/index'); + * + * // Assign some new variables + * $view->assign('msg', 'Some message...'); + * + * // Get view + * $output = $view->render(); + * + * // Display view + * echo $output; + * + * + * @param string $view Name of the view file + * @param array $variables Array of view variables + */ + public function __construct($view, array $variables = array()) { + + // Set view file + $this->view_file = PLUGINS . DS . $view . '.view.php'; + + // Is view file exists ? + if (file_exists($this->view_file) === false) { + throw new RuntimeException(vsprintf("%s(): The '%s' view does not exist.", array(__METHOD__, $view))); + } + + // Set view variables + $this->vars = $variables; + } + + + /** + * View factory + * + * + * // Create new view object, assign some variables + * // and displays the rendered view in the browser. + * View::factory('blog/views/backend/index') + * ->assign('msg', 'Some message...') + * ->display(); + * + * + * @param string $view Name of the view file + * @param array $variables Array of view variables + * @return View + */ + public static function factory($view, array $variables = array()) { + return new View($view, $variables); + } + + + /** + * Assign a view variable. + * + * + * $view->assign('msg', 'Some message...'); + * + * + * @param string $key Variable name + * @param mixed $value Variable value + * @param boolean $global Set variable available in all views + * @return View + */ + public function assign($key, $value, $global = false) { + + // Assign a new view variable (global or locale) + if ($global === false) { + $this->vars[$key] = $value; + } else { + View::$global_vars[$key] = $value; + } + + return $this; + } + + + /** + * Include the view file and extracts the view variables before returning the generated output. + * + * + * // Get view + * $output = $view->render(); + * + * // Display output + * echo $output; + * + * + * @param string $filter Callback function used to filter output + * @return string + */ + public function render($filter = null) { + + // Is output empty ? + if (empty($this->output)) { + + // Extract variables as references + extract(array_merge($this->vars, View::$global_vars), EXTR_REFS); + + // Turn on output buffering + ob_start(); + + // Include view file + include($this->view_file); + + // Output... + $this->output = ob_get_clean(); + } + + // Filter output ? + if ($filter !== null) { + $this->output = call_user_func($filter, $this->output); + } + + // Return output + return $this->output; + } + + + /** + * Displays the rendered view in the browser. + * + * + * $view->display(); + * + * + */ + public function display() { + echo $this->render(); + } + + + /** + * Magic setter method that assigns a view variable. + * + * @param string $key Variable name + * @param mixed $value Variable value + */ + public function __set($key, $value) { + $this->vars[$key] = $value; + } + + + /** + * Magic getter method that returns a view variable. + * + * @param string $key Variable name + * @return mixed + */ + public function __get($key) { + + if (isset($this->vars[$key])) { + return $this->vars[$key]; + } + } + + + /** + * Magic isset method that checks if a view variable is set. + * + * @param string $key Variable name + * @return boolean + */ + public function __isset($key) { + return isset($this->vars[$key]); + } + + + /** + * Magic unset method that unsets a view variable. + * + * @param string $key Variable name + */ + public function __unset($key) { + unset($this->vars[$key]); + } + + + /** + * Method that magically converts the view object into a string. + * + * @return string + */ + public function __toString() { + return $this->render(); + } + } + + + /** + * I18n class + */ + class I18n { + + + /** + * Dictionary + * + * @var array + */ + public static $dictionary = array(); + + + /** + * An instance of the I18n class + * + * @var I18n + */ + protected static $instance = null; + + + /** + * Initializing I18n + * + * @param string $dir Plugins directory + */ + public static function init($locale) { + if ( ! isset(self::$instance)) self::$instance = new I18n($locale); + return self::$instance; + } + + + /** + * Protected clone method to enforce singleton behavior. + * + * @access protected + */ + protected function __clone() { + // Nothing here. + } + + + /** + * Construct + */ + protected function __construct($locale) { + + // Redefine arguments + $locale = (string) $locale; + + // Get lang table for current locale + $lang_table = Cache::get('i18n', $locale); + + // If lang_table is empty then create new + if ( ! $lang_table) { + + // Get plugins Table + $plugins = new Table('plugins'); + + // Get all plugins + $records = $plugins->select(null, 'all', null, array('location', 'priority'), 'priority', 'ASC'); + + // Init var + $lang_table = array(); + + // Loop through each installed plugin + foreach ($records as $record) { + + if (is_dir(ROOT . DS . dirname($record['location']) . DS . 'languages')) { + + // Init var + $t = array(); + + // Check lang file + if (file_exists(ROOT . DS . dirname($record['location']) . DS . 'languages' . DS . $locale . '.lang.php')) { + + // Merge the language strings into the sub table + $t = array_merge($t, include ROOT . DS . dirname($record['location']) . DS . 'languages' . DS . $locale . '.lang.php'); + + } + + // Append the sub table, preventing less specific language files from overloading more specific files + $lang_table += $t; + } + } + + // Save lang table for current locale + Cache::put('i18n', $locale, $lang_table); + + // Update dictionary + I18n::$dictionary = $lang_table; + } + + // Update dictionary + I18n::$dictionary = $lang_table; + } + + + /** + * Returns translation of a string. If no translation exists, the original + * string will be returned. No parameters are replaced. + * + * + * $hello = I18n::find('Hello friends, my name is :name', 'namespace'); + * + * + * @param string $string Text to translate + * @param string $namespace Namespace + * @return string + */ + public static function find($string, $namespace = null) { + + // Redefine arguments + $string = (string) $string; + + // Return string + if (isset(I18n::$dictionary[$namespace][$string])) return I18n::$dictionary[$namespace][$string]; else return $string; + } + + } + + + /** + * Global Translation/internationalization function. + * Accepts an English string and returns its translation + * to the active system language. If the given string is not available in the + * current dictionary the original English string will be returned. + * + * + * // Display a translated message + * echo __('Hello, world', 'namespace'); + * + * // With parameter replacement + * echo __('Hello, :user', 'namespace', array(':user' => $username)); + * + * + * @global array $dictionary Dictionary + * @param string $string String to translate + * @param array $values Values to replace in the translated text + * @param string $namespace Namespace + * @return string + */ + function __($string, $namespace = null, array $values = null) { + + // Redefine arguments + $string = (string) $string; + + // Find string in dictionary + $string = I18n::find($string, $namespace); + + // Return string + return empty($values) ? $string : strtr($string, $values); + } + + + /** + * Action class + */ + class Action { + + + /** + * Actions + * + * @var array + */ + public static $actions = array(); + + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() { + // Nothing here + } + + + /** + * Hooks a function on to a specific action. + * + * + * // Hooks a function "newLink" on to a "footer" action. + * Action::add('footer', 'newLink', 10); + * + * function newLink() { + * echo 'My link'; + * } + * + * + * @param string $action_name Action name + * @param string $added_function Added function + * @param integer $priority Priority. Default is 10 + * @param array $args Arguments + */ + public static function add($action_name, $added_function, $priority = 10, array $args = null) { + + // Hooks a function on to a specific action. + Action::$actions[] = array( + 'action_name' => (string)$action_name, + 'function' => (string)$added_function, + 'priority' => (int)$priority, + 'args' => $args + ); + } + + + /** + * Run functions hooked on a specific action hook. + * + * + * // Run functions hooked on a "footer" action hook. + * Action::run('footer'); + * + * + * @param string $action_name Action name + * @param array $args Arguments + * @param boolean $return Return data or not. Default is false + * @return mixed + */ + public static function run($action_name, $args = array(), $return = false) { + + // Redefine arguments + $action_name = (string) $action_name; + $return = (bool) $return; + + // Run action + if (count(Action::$actions) > 0) { + + // Sort actions by priority + $actions = Arr::subvalSort(Action::$actions, 'priority'); + + // Loop through $actions array + foreach ($actions as $action) { + + // Execute specific action + if ($action['action_name'] == $action_name) { + + // isset arguments ? + if (isset($args)) { + + // Return or Render specific action results ? + if ($return) { + return call_user_func_array($action['function'], $args); + } else { + call_user_func_array($action['function'], $args); + } + + } else { + + if ($return) { + return call_user_func_array($action['function'], $action['args']); + } else { + call_user_func_array($action['function'], $action['args']); + } + + } + + } + + } + + } + + } + + } + + + /** + * Filter class + */ + class Filter { + + + /** + * Filters + * + * @var array + */ + public static $filters = array(); + + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() { + // Nothing here + } + + + /** + * Apply filters + * + * + * Filter::apply('content', $content); + * + * + * @param string $filter_name The name of the filter hook. + * @param mixed $value The value on which the filters hooked. + * @return mixed + */ + public static function apply($filter_name, $value) { + + // Redefine arguments + $filter_name = (string) $filter_name; + + $args = array_slice(func_get_args(), 2); + + if ( ! isset(Filter::$filters[$filter_name])) { + return $value; + } + + foreach (Filter::$filters[$filter_name] as $priority => $functions) { + if ( ! is_null($functions)) { + foreach ($functions as $function) { + $all_args = array_merge(array($value), $args); + $function_name = $function['function']; + $accepted_args = $function['accepted_args']; + if ($accepted_args == 1) { + $the_args = array($value); + } elseif ($accepted_args > 1) { + $the_args = array_slice($all_args, 0, $accepted_args); + } elseif ($accepted_args == 0) { + $the_args = null; + } else { + $the_args = $all_args; + } + $value = call_user_func_array($function_name, $the_args); + } + } + } + return $value; + } + + + /** + * Add filter + * + * + * Filter::add('content', 'replacer'); + * + * function replacer($content) { + * return preg_replace(array('/\[b\](.*?)\[\/b\]/ms'), array('\1'), $content); + * } + * + * + * @param string $filter_name The name of the filter to hook the $function_to_add to. + * @param string $function_to_add The name of the function to be called when the filter is applied. + * @param integer $priority Function to add priority - default is 10. + * @param integer $accepted_args The number of arguments the function accept default is 1. + * @return boolean + */ + public static function add($filter_name, $function_to_add, $priority = 10, $accepted_args = 1) { + + // Redefine arguments + $filter_name = (string) $filter_name; + $function_to_add = (string) $function_to_add; + $priority = (int) $priority; + $accepted_args = (int) $accepted_args; + + // Check that we don't already have the same filter at the same priority. Thanks to WP :) + if (isset(Filter::$filters[$filter_name]["$priority"])) { + foreach (Filter::$filters[$filter_name]["$priority"] as $filter) { + if ($filter['function'] == $function_to_add) { + return true; + } + } + } + + Filter::$filters[$filter_name]["$priority"][] = array('function' => $function_to_add, 'accepted_args' => $accepted_args); + + // Sort + ksort(Filter::$filters[$filter_name]["$priority"]); + + return true; + } + + } + + + /** + * Stylesheet class + */ + class Stylesheet { + + + /** + * Stylesheets + * + * @var array + */ + public static $stylesheets = array(); + + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() { + // Nothing here + } + + + /** + * Add stylesheet + * + * + * Stylesheet::add('path/to/my/stylesheet1.css'); + * Stylesheet::add('path/to/my/stylesheet2.css', 'frontend', 11); + * Stylesheet::add('path/to/my/stylesheet3.css', 'backend',12); + * + * + * @param string $file File path + * @param string $load Load stylesheet on frontend, backend or both + * @param integer $priority Priority. Default is 10 + */ + public static function add($file, $load = 'frontend', $priority = 10) { + Stylesheet::$stylesheets[] = array( + 'file' => (string)$file, + 'load' => (string)$load, + 'priority' => (int)$priority, + ); + } + + + /** + * Minify, combine and load site stylesheet + */ + public static function load() { + + $backend_site_css_path = MINIFY . DS . 'backend_site.minify.css'; + $frontend_site_css_path = MINIFY . DS . 'frontend_site.minify.css'; + + // Load stylesheets + if (count(Stylesheet::$stylesheets) > 0) { + + $backend_buffer = ''; + $backend_regenerate = false; + + $frontend_buffer = ''; + $frontend_regenerate = false; + + + // Sort stylesheets by priority + $stylesheets = Arr::subvalSort(Stylesheet::$stylesheets, 'priority'); + + // Build backend site stylesheets + foreach ($stylesheets as $stylesheet) { + if ((file_exists(ROOT . DS . $stylesheet['file'])) and (($stylesheet['load'] == 'backend') or ($stylesheet['load'] == 'both')) ) { + if ( ! file_exists($backend_site_css_path) or filemtime(ROOT . DS . $stylesheet['file']) > filemtime($backend_site_css_path)) { + $backend_regenerate = true; + break; + } + } + } + + // Regenerate site stylesheet + if ($backend_regenerate) { + foreach ($stylesheets as $stylesheet) { + if ((file_exists(ROOT . DS . $stylesheet['file'])) and (($stylesheet['load'] == 'backend') or ($stylesheet['load'] == 'both')) ) { + $backend_buffer .= file_get_contents(ROOT . DS . $stylesheet['file']); + } + } + $backend_buffer = Stylesheet::parseVariables($backend_buffer); + file_put_contents($backend_site_css_path, Minify::css($backend_buffer)); + $backend_regenerate = false; + } + + + // Build frontend site stylesheets + foreach ($stylesheets as $stylesheet) { + if ((file_exists(ROOT . DS . $stylesheet['file'])) and (($stylesheet['load'] == 'frontend') or ($stylesheet['load'] == 'both')) ) { + if ( ! file_exists($frontend_site_css_path) or filemtime(ROOT . DS . $stylesheet['file']) > filemtime($frontend_site_css_path)) { + $frontend_regenerate = true; + break; + } + } + } + + // Regenerate site stylesheet + if ($frontend_regenerate) { + foreach ($stylesheets as $stylesheet) { + if ((file_exists(ROOT . DS . $stylesheet['file'])) and (($stylesheet['load'] == 'frontend') or ($stylesheet['load'] == 'both')) ) { + $frontend_buffer .= file_get_contents(ROOT . DS . $stylesheet['file']); + } + } + $frontend_buffer = Stylesheet::parseVariables($frontend_buffer); + file_put_contents($frontend_site_css_path, Minify::css($frontend_buffer)); + $frontend_regenerate = false; + } + + // Render + if (BACKEND) { + echo ''; + } else { + echo ''; + } + } + } + + + /** + * CSS Parser + */ + public static function parseVariables($frontend_buffer) { + return str_replace(array('@site_url', + '@theme_site_url', + '@theme_admin_url'), + array(Option::get('siteurl'), + Option::get('siteurl').'public/themes/'.Option::get('theme_site_name'), + Option::get('siteurl').'admin/themes/'.Option::get('theme_admin_name')), + $frontend_buffer); + } + + + } + + + /** + * Javascript class + */ + class Javascript { + + + /** + * Javascripts + * + * @var array + */ + public static $javascripts = array(); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() { + // Nothing here + } + + + /** + * Add javascript + * + * + * Javascript::add('path/to/my/script1.js'); + * Javascript::add('path/to/my/script2.js', 'frontend', 11); + * Javascript::add('path/to/my/script3.js', 'backend', 12); + * + * + * @param string $file File path + * @param string $load Load script on frontend, backend or both + * @param inteeer $priority Priority default is 10 + */ + public static function add($file, $load = 'frontend', $priority = 10) { + Javascript::$javascripts[] = array( + 'file' => (string)$file, + 'load' => (string)$load, + 'priority' => (int)$priority, + ); + } + + + /** + * Combine and load site javascript + */ + public static function load() { + + $backend_site_js_path = MINIFY . DS . 'backend_site.minify.js'; + $frontend_site_js_path = MINIFY . DS . 'frontend_site.minify.js'; + + // Load javascripts + if (count(Javascript::$javascripts) > 0) { + + $backend_buffer = ''; + $backend_regenerate = false; + + $frontend_buffer = ''; + $frontend_regenerate = false; + + + // Sort javascripts by priority + $javascripts = Arr::subvalSort(Javascript::$javascripts, 'priority'); + + // Build backend site javascript + foreach ($javascripts as $javascript) { + if ((file_exists(ROOT . DS . $javascript['file'])) and (($javascript['load'] == 'backend') or ($javascript['load'] == 'both')) ) { + if ( ! file_exists($backend_site_js_path) or filemtime(ROOT . DS . $javascript['file']) > filemtime($backend_site_js_path)) { + $backend_regenerate = true; + break; + } + } + } + + // Regenerate site javascript + if ($backend_regenerate) { + foreach ($javascripts as $javascript) { + if ((file_exists(ROOT . DS . $javascript['file'])) and (($javascript['load'] == 'backend') or ($javascript['load'] == 'both')) ) { + $backend_buffer .= file_get_contents(ROOT . DS . $javascript['file']); + } + } + file_put_contents($backend_site_js_path, $backend_buffer); + $backend_regenerate = false; + } + + + // Build frontend site javascript + foreach ($javascripts as $javascript) { + if ((file_exists(ROOT . DS . $javascript['file'])) and (($javascript['load'] == 'frontend') or ($javascript['load'] == 'both')) ) { + if ( ! file_exists($frontend_site_js_path) or filemtime(ROOT . DS . $javascript['file']) > filemtime($frontend_site_js_path)) { + $frontend_regenerate = true; + break; + } + } + } + + // Regenerate site javascript + if ($frontend_regenerate) { + foreach ($javascripts as $javascript) { + if ((file_exists(ROOT . DS . $javascript['file'])) and (($javascript['load'] == 'frontend') or ($javascript['load'] == 'both')) ) { + $frontend_buffer .= file_get_contents(ROOT . DS . $javascript['file']); + } + } + file_put_contents($frontend_site_js_path, $frontend_buffer); + $frontend_regenerate = false; + } + + // Render + if (BACKEND) { + echo ''; + } else { + echo ''; + } + } + } + + } + + + /** + * Navigation class + */ + class Navigation { + + + /** + * Items + * + * @var array + */ + public static $items = array(); + + + /** + * Navigation types + */ + const LEFT = 1; + const TOP = 2; + + + /** + * Add new item + * + * + * // Add link for left navigation + * Navigation::add(__('Blog'), 'content', 'blog', 11); + * + * // Add link for top navigation + * Navigation::add(__('View site'), 'top', 'http://site.com/', 11, Navigation::TOP, true); + * + * + * @param string $name Name + * @param string $category Category + * @param stirng $link Link + * @param integer $priority Priority. Default is 10 + * @param integer $type Type. Default is LEFT + * @param bool $external External or not. Default is false + */ + public static function add($name, $category, $id, $priority = 10, $type = Navigation::LEFT, $external = false) { + Navigation::$items[] = array( + 'name' => (string)$name, + 'category' => (string)$category, + 'id' => (string)$id, + 'priority' => (int)$priority, + 'type' => (int)$type, + 'external' => (bool)$external, + ); + } + + + /** + * Draw items + * + * + * Navigation::draw('content'); + * Navigation::draw('top', Navigation::TOP); + * + * + * @param string $category Category + * @param integer $type Type. Default is LEFT + */ + public static function draw($category, $type = Navigation::LEFT) { + + // Sort items by priority + $items = Arr::subvalSort(Navigation::$items, 'priority'); + + // Draw left navigation + if ($type == Navigation::LEFT) { + + // Loop trough the items + foreach ($items as $item) { + + // If current plugin id == selected item id then set class to current + if (Request::get('id') == $item['id'] && $item['external'] == false) $class = 'class = "current" '; else $class = ''; + + // If current category == item category and navigation type is left them draw this item + if ($item['category'] == $category && $item['type'] == Navigation::LEFT) { + + // Is external item id or not ? + if ($item['external'] == false) { + echo '
  • '.$item['name'].'
  • '; + } else { + echo '
  • '.$item['name'].'
  • '; + } + } + } + } elseif ($type == Navigation::TOP) { + // Draw top navigation + foreach ($items as $item) { + if ($item['category'] == $category && $item['type'] == Navigation::TOP) { + if ($item['external'] == false) { + echo ''.$item['name'].''.Html::nbsp(2); + } else { + echo ''.$item['name'].''.Html::nbsp(2); + } + } + } + } + } + + } \ No newline at end of file diff --git a/monstra/engine/shortcodes.php b/monstra/engine/shortcodes.php new file mode 100644 index 0000000..9222f28 --- /dev/null +++ b/monstra/engine/shortcodes.php @@ -0,0 +1,133 @@ + + * function returnSiteUrl() { + * return Option::get('siteurl'); + * } + * + * // Add shortcode {siteurl} + * Shortcode::add('siteurl', 'returnSiteUrl'); + *
    + * + * @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. + * + * + * $content = Shortcode::parse($content); + * + * + * @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; + } + +} \ No newline at end of file diff --git a/monstra/engine/site.php b/monstra/engine/site.php new file mode 100644 index 0000000..f46d901 --- /dev/null +++ b/monstra/engine/site.php @@ -0,0 +1,257 @@ + + * echo Site::name(); + *
    + * + * @return string + */ + public static function name() { + return Option::get('sitename'); + } + + + /** + * Get site theme + * + * + * echo Site::theme(); + * + * + * @return string + */ + public static function theme() { + return Option::get('theme_site_name'); + } + + + /** + * Get Page title + * + * + * echo Site::title(); + * + * + * @return string + */ + public static function title() { + + // Get title + $title = call_user_func(ucfirst(Uri::command()).'::title'); + + return $title; + } + + + /** + * Get page description + * + * + * echo Site::description(); + * + * + * @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 + * + * + * echo Site::keywords(); + * + * + * @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 + * + * + * echo Site::slogan(); + * + * + * @return string + */ + public static function slogan() { + return Option::get('slogan'); + } + + + /** + * Get page content + * + * + * echo Site::content(); + * + * + * @return string + */ + public static function content() { + + // Get content + $content = call_user_func(ucfirst(Uri::command()).'::content'); + + return Filter::apply('content', $content); + } + + + /** + * Get compressed template + * + * + * echo Site::template(); + * + * + * @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 + * + * + * echo Site::url(); + * + * + * @return string + */ + public static function url() { + return Option::get('siteurl'); + } + + + /** + * Get copyright information + * + * + * echo Site::powered(); + * + * + * @return string + */ + public static function powered() { + return __('Powered by', 'system').' Monstra ' . MONSTRA_VERSION; + } + + } + + + // Add new shortcode {siteurl} + Shortcode::add('siteurl', 'returnSiteUrl'); + function returnSiteUrl() { return Option::get('siteurl'); } \ No newline at end of file diff --git a/monstra/engine/xmldb.php b/monstra/engine/xmldb.php new file mode 100644 index 0000000..48c877a --- /dev/null +++ b/monstra/engine/xmldb.php @@ -0,0 +1,1008 @@ + + * $xml_safe = XML::safe($xml_unsafe); + *
    + * + * @param string $str String + * @param boolean $flag Flag + * @return string + */ + public static function safe($str, $flag = true) { + + // Redefine vars + $str = (string) $str; + $flag = (bool) $flag; + + // Remove invisible chars + $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); + + // htmlspecialchars + if ($flag) $str = htmlspecialchars($str, ENT_QUOTES, 'utf-8'); + + // Return safe string + return $str; + } + + + /** + * Get XML file + * + * + * $xml_file = XML::loadFile('path/to/file.xml'); + * + * + * @param string $file File name + * @param boolean $force Method + * @return array + */ + public static function loadFile($file, $force = false) { + + // Redefine vars + $file = (string) $file; + $force = (bool) $force; + + // For CMS API XML file force method + if ($force) { + $xml = file_get_contents($file); + $data = simplexml_load_string($xml); + return $data; + } else { + if (file_exists($file) && is_file($file)) { + $xml = file_get_contents($file); + $data = simplexml_load_string($xml); + return $data; + } else { + return false; + } + } + } + + } + + + /** + * DB Class + */ + class DB { + + + /** + * XMLDB directory + * + * @var string + */ + public static $db_dir = STORAGE; + + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() { + // Nothing here + } + + + /** + * Configure the settings of XMLDB + * + * @param mixed $setting Setting name + * @param mixed $value Setting value + */ + public static function configure($setting, $value){ + if (property_exists("db", $setting)) DB::$$setting = $value; + } + + + /** + * Create new database + * + * @param string $db_name Database name + * @param integer $mode Mode + * @return boolean + */ + public static function create($db_name, $chmod = 0775) { + + // Redefine vars + $db_name = (string) $db_name; + + // Create + if (is_dir(DB::$db_dir . '/' . $db_name)) return false; + return mkdir(DB::$db_dir . '/' . $db_name, $chmod); + } + + + /** + * Drop database + * + * @param string $db_name Database name + * @return boolean + */ + public static function drop($db_name) { + + // Redefine vars + $db_name = (string) $db_name; + + // Drop + if (is_dir(DB::$db_dir . '/' . $db_name)){$ob=scandir(DB::$db_dir . '/' . $db_name); foreach ($ob as $o){if($o!='.'&&$o!='..'){if(filetype(DB::$db_dir . '/' . $db_name.'/'.$o)=='dir')DB::drop(DB::$db_dir . '/' . $db_name.'/'.$o); else unlink(DB::$db_dir . '/' . $db_name.'/'.$o);}}} + reset($ob); rmdir(DB::$db_dir . '/' . $db_name); + } + + } + + + /** + * Table class + */ + class Table { + + + /** + * XMLDB Tables directory + * + * @var string + */ + public static $tables_dir = XMLDB; + + + /** + * Table + * + * @var object + */ + private $table; + + + /** + * Table name + * + * @var string + */ + private $name; + + + /** + * Configure the settings of XMLDB Tables + * + * @param mixed $setting Setting name + * @param mixed $value Setting value + */ + public static function configure($setting, $value){ + if (property_exists("table", $setting)) Table::$$setting = $value; + } + + + /** + * Table construct + * + * + * $users = new Table('table_name'); + * + * + * @param string $table_name Table name + */ + function __construct($table_name) { + + // Redefine vars + $table_name = (string) $table_name; + + $this->table = Table::get($table_name); + $this->name = $table_name; + } + + + /** + * Create new table + * + * XMLDB Table structure: + * + * + * + * 0 + * + * + * + * + * + * value + * value + * + * + * + * + * Table::create('table_name', array('field1', 'field2')); + * + * + * @param string $table_name Table name + * @param array $fields Fields + * @return boolean + */ + public static function create($table_name, $fields) { + + // Redefine vars + $table_name = (string) $table_name; + + if ( ! file_exists(Table::$tables_dir . '/' . $table_name . '.table.xml') && + is_dir(dirname(Table::$tables_dir)) && + is_writable(dirname(Table::$tables_dir)) && + isset($fields) && + is_array($fields)) { + + // Create table fields + $_fields = ''; + foreach ($fields as $field) $_fields .= "<$field/>"; + $_fields .= ''; + + // Create new table + return file_put_contents(Table::$tables_dir . '/' . $table_name . '.table.xml','0'.$_fields.'', LOCK_EX); + + } else { + + // Something wrong... return false + return false; + } + } + + + /** + * Delete table + * + * + * Table::drop('table_name'); + * + * + * @param string $table_name Table name + * @return boolean + */ + public static function drop($table_name) { + + // Redefine vars + $table_name = (string) $table_name; + + // Drop + if ( ! is_dir(Table::$tables_dir . '/' . $table_name . '.table.xml')) { + return unlink(Table::$tables_dir . '/' . $table_name . '.table.xml'); + } + + return false; + } + + + /** + * Get table + * + * + * $table = Table::get('table_name'); + * + * + * @param array $table_name Table name + * @return mixed + */ + public static function get($table_name) { + + // Redefine vars + $table_name = (string) $table_name; + + // Load table + if (file_exists(Table::$tables_dir . '/' . $table_name.'.table.xml') && is_file(Table::$tables_dir . '/' . $table_name.'.table.xml')) { + $data = array('xml_object' => XML::loadFile(Table::$tables_dir . '/' . $table_name.'.table.xml'), + 'xml_filename' => Table::$tables_dir . '/' . $table_name.'.table.xml'); + return $data; + } else { + return false; + } + } + + + /** + * Get information about table + * + * + * var_dump($users->info()); + * + * + * @return array + */ + public function info() { + return array( + 'table_name' => basename($this->table['xml_filename'], '.table.xml'), + 'table_size' => filesize($this->table['xml_filename']), + 'table_last_change' => filemtime($this->table['xml_filename']), + 'table_last_access' => fileatime($this->table['xml_filename']), + 'table_fields' => $this->fields(), + 'records_count' => $this->count(), + 'records_last_id' => $this->lastId() + ); + } + + + /** + * Get table fields + * + * + * var_dump($users->fields()); + * + * + * @return array + */ + public function fields() { + + // Select fields + $fields_obj = Table::_selectOne($this->table, "fields"); + + // Create fields array + foreach ($fields_obj as $key => $field) { + $fields[] = $key; + } + + // Return array of fields + return $fields; + } + + + /** + * Add new field + * + * + * $users->addField('test'); + * + * + * @param string $name Field name + * @return boolean + */ + public function addField($name) { + + // Redefine vars + $name = (string) $name; + + // Get table + $table = $this->table; + + // Select all fields + $fields = Table::_selectOne($this->table, "fields"); + + // Select current field + $field = Table::_selectOne($this->table, "fields/{$name}"); + + // If field dosnt exists than create new field + if ($field == null) { + + // Create new field + $fields->addChild($name, ''); + + // Save table + return Table::_save($table); + + } else { + + return false; + + } + + } + + + /** + * Delete field + * + * + * $users->deleteField('test'); + * + * + * @param string $name Field name + * @return boolean + */ + public function deleteField($name) { + + // Redefine vars + $name = (string) $name; + + // Get table + $table = $this->table; + + // Select field + $field = Table::_selectOne($this->table, "fields/{$name}"); + + // If field exist than delete it + if ($field != null) { + + // Delete field + unset($field[0]); + + // Save table + return Table::_save($table); + + } else { + + return false; + + } + } + + + /** + * Update field + * + * + * $users->updateField('login', 'username'); + * + * + * @param string $old_name Old field name + * @param string $new_name New field name + * @return boolean + */ + public function updateField($old_name, $new_name) { + if (file_exists(Table::$tables_dir . '/' . $this->name.'.table.xml') && is_file(Table::$tables_dir . '/' . $this->name.'.table.xml')) { + $table = strtr(file_get_contents(Table::$tables_dir . '/' . $this->name.'.table.xml'), array('<'.$old_name.'>' => '<'.$new_name.'>', + '' => '', + '<'.$old_name.'/>' => '<'.$new_name.'/>')); + if (file_put_contents(Table::$tables_dir . '/' . $this->name.'.table.xml', $table)) { + return true; + } else { + return false; + } + } + } + + + /** + * Add new record + * + * + * $users->insert(array('login'=>'admin', 'password'=>'pass')); + * + * + * @param array $fields Record fields to insert + * @return boolean + */ + public function insert(array $fields = null) { + + // Set save flag to true + $save = true; + + // Foreach fields check is current field alredy exists + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + if (Table::_selectOne($this->table, "fields/{$key}") == null) { + $save = false; + break; + } + } + } + + // Get table fields and create fields names array + $_fields = Table::_selectOne($this->table, "fields"); + foreach ($_fields as $key => $value) { + $field_names[(string)$key] = (string)$key; + } + + // Save record + if ($save) { + + // Find autoincrement option + $inc = Table::_selectOne($this->table, "options/autoincrement"); + + // Increment + $inc_upd = $inc + 1; + + // Add record + $node = $this->table['xml_object']->addChild(XML::safe($this->name)); + + // Update autoincrement + Table::_updateWhere($this->table, "options", array('autoincrement' => $inc_upd)); + + // Add common record fields: id and uid + $node->addChild('id', $inc_upd); + $node->addChild('uid', Table::_generateUID()); + + // If exists fields to insert then insert them + if (count($fields) !== 0) { + + $table_fields = array_diff_key($field_names, $fields); + + // Defined fields + foreach ($table_fields as $table_field) { + $node->addChild($table_field, ''); + } + + // User fields + foreach ($fields as $key => $value) { + $node->addChild($key, XML::safe($value)); + } + } + + // Save table + return Table::_save($this->table); + + } else { + + return false; + + } + } + + + /** + * Select record(s) in table + * + * + * $records = $users->select('[id=2]'); + * $records = $users->select(null, 'all'); + * $records = $users->select(null, 'all', null, array('login')); + * $records = $users->select(null, 2, 1); + * + * + * @param string $query XPath query + * @param integer $row_count Row count. To select all records write 'all' + * @param integer $offset Offset + * @param array $fields Fields + * @param string $order_by Order by + * @param string $order Order type + * @return array + */ + public function select($query = null, $row_count = 'all', $offset = null, array $fields = null, $order_by = 'id', $order = 'ASC') { + + // Redefine vars + $query = ($query === null) ? null : (string) $query; + $offset = ($offset === null) ? null : (int) $offset; + $order_by = (string) $order_by; + $order = (string) $order; + + // Execute query + if ($query !== null) { + $tmp = $this->table['xml_object']->xpath('//'.$this->name.$query); + } else { + $tmp = $this->table['xml_object']->xpath($this->name); + } + + // Init vars + $data = array(); + $records = array(); + $_records = array(); + + $one_record = false; + + // If row count is null then select only one record + // eg: $users->select('[login="admin"]', null); + if ($row_count == null) { + + if (isset($tmp[0])) { + $_records = $tmp[0]; + $one_record = true; + } + + } else { + + // If row count is 'all' then select all records + // eg: + // $users->select('[status="active"]', 'all'); + // or + // $users->select('[status="active"]'); + if ($row_count == 'all') { + + foreach ($tmp as $record) { + $data[] = $record; + } + + $_records = $data; + + } else { + + // Else select records like + // eg: $users->select(null, 2, 1); + + foreach($tmp as $record) { + $data[] = $record; + } + + // If offset is null slice array from end else from begin + if ($offset === null) { + $_records = array_slice($data, -$row_count, $row_count); + } else { + $_records = array_slice($data, $offset, $row_count); + } + + } + } + + // If array of fields is exits then get records with this fields only + if (count($fields) > 0) { + + if (count($_records) > 0) { + + $count = 0; + foreach ($_records as $key => $record) { + + foreach ($fields as $field) { + $record_array[$count][$field] = (string)$record->$field; + } + + //$record_array[$count]['id'] = (int)$record['id']; + $record_array[$count]['id'] = (int)$record->id; + + if ($order_by == 'id') { + $record_array[$count]['sort'] = (int)$record->$order_by; + } else { + $record_array[$count]['sort'] = (string)$record->$order_by; + } + + $count++; + + } + $records = Table::subvalSort($record_array, 'sort', $order); + } + + } else { + + // Convert from XML object to array + + if ( ! $one_record) { + $count = 0; + foreach ($_records as $xml_objects) { + $vars = get_object_vars($xml_objects); + foreach ($vars as $key => $value) { + $records[$count][$key] = (string)$value; + } + $count++; + } + } else { + $vars = get_object_vars($_records[0]); + foreach ($vars as $key => $value) { + $records[$key] = (string)$value; + } + } + + } + + // Return records + return $records; + + } + + + /** + * Delete current record in table + * + * + * $users->delete(2); + * + * + * @param integer $id Record ID + * @return boolean + */ + public function delete($id) { + + // Redefine vars + $id = (int) $id; + + // Find record to delete + $xml_arr = Table::_selectOne($this->table, "//".$this->name."[id='".$id."']"); + + // If its exists then delete it + if (count($xml_arr) !== 0) { + + // Delete + unset($xml_arr[0]); + + } + + // Save table + return Table::_save($this->table); + } + + + /** + * Delete with xPath query record in xml file + * + * + * $users->deleteWhere('[id=2]'); + * + * + * @param string $query xPath query + * @return boolean + */ + public function deleteWhere($query) { + + // Redefine vars + $query = (string) $query; + + // Find record to delete + $xml_arr = Table::_selectOne($this->table, '//'.$this->name.$query); + + // If its exists then delete it + if (count($xml_arr) !== 0) { + + // Delete + unset($xml_arr[0]); + + } + + // Save table + return Table::_save($this->table); + } + + + /** + * Update record with xPath query in XML file + * + * + * $users->updateWhere('[id=2]', array('login'=>'Admin', 'password'=>'new pass')); + * + * + * @param string $query XPath query + * @param array $fields Record fields to udpate + * @return boolean + */ + public function updateWhere($query, array $fields = null) { + + // Redefine vars + $query = (string) $query; + + // Set save flag to true + $save = true; + + // Foreach fields check is current field alredy exists + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + if (Table::_selectOne($this->table, "fields/{$key}") == null) { + $save = false; + break; + } + } + } + + // Get table fields and create fields names array + $_fields = Table::_selectOne($this->table, "fields"); + foreach ($_fields as $key => $value) { + $field_names[(string)$key] = (string)$key; + } + + // Save record + if ($save) { + + // Find record + $xml_arr = Table::_selectOne($this->table, '//'.$this->name.$query); + + // If its exists then delete it + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + // Else: Strict Mode Error + // Creating default object from empty value + @$xml_arr->$key = XML::safe($value, false); + } + } + + // Save table + return Table::_save($this->table); + + } else { + + return false; + + } + } + + + /** + * Update current record in table + * + * + * $users->update(1, array('login'=>'Admin','password'=>'new pass')); + * + * + * @param integer $id Record ID + * @param array $fields Record fields to udpate + * @return boolean + */ + public function update($id, array $fields = null) { + + // Redefine vars + $id = (int) $id; + + // Set save flag to true + $save = true; + + // Foreach fields check is current field alredy exists + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + if (Table::_selectOne($this->table, "fields/{$key}") == null) { + $save = false; + break; + } + } + } + + // Get table fields and create fields names array + $_fields = Table::_selectOne($this->table, "fields"); + foreach ($_fields as $key => $value) { + $field_names[(string)$key] = (string)$key; + } + + // Save record + if ($save) { + + // Find record to delete + $xml_arr = Table::_selectOne($this->table, "//".$this->name."[id='".(int)$id."']"); + + // If its exists then update it + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + + // Delete current + unset($xml_arr->$key); + + // And add new one + $xml_arr->addChild($key, XML::safe($value, false)); + + } + } + + // Save table + return Table::_save($this->table); + + } else { + + return false; + + } + } + + + /** + * Get last record id + * + * + * echo $users->lastId(); + * + * + * @return integer + */ + public function lastId() { + $data = $this->table['xml_object']->xpath("//root/node()[last()]"); + return (int)$data[0]->id; + } + + + /** + * Get count of records + * + * + * echo $users->count(); + * + * + * @return integer + */ + public function count() { + return count($this->table['xml_object'])-2; + } + + + + /** + * Subval sort + * + * @param array $a Array + * @param string $subkey Key + * @param string $order Order type DESC or ASC + * @return array + */ + protected 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; + } + } + + + /** + * _selectOne + */ + protected static function _selectOne($table, $query) { + $tmp = $table['xml_object']->xpath($query); + return isset($tmp[0])? $tmp[0]: null; + } + + + /** + * _updateWhere + */ + protected static function _updateWhere($table, $query, $fields = array()) { + + // Find record to delete + $xml_arr = Table::_selectOne($table, $query); + + // If its exists then delete it + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + $xml_arr->$key = XML::safe($value, false); + } + } + + // Save table + Table::_save($table); + } + + + /** + * _generateUID + */ + protected static function _generateUID() { + return substr(md5(uniqid(rand(), true)), 0, 10); + } + + + /** + * Format XML and save + * + * @param array $table Array of database name and XML object + */ + protected static function _save($table) { + $dom = new DOMDocument('1.0'); + $dom->preserveWhiteSpace = false; + + // Save new xml data to xml file only if loadXML successful. + // Preventing the destruction of the database by unsafe data. + // note: If loadXML !successful then _save() add&save empty record. + // This record cant be removed by delete[Where]() Problem solved by hand removing... + // Possible solution: modify delete[Where]() or prevent add&saving of such records. + // the result now: database cant be destroyed :) + if ($dom->loadXML($table['xml_object']->asXML())) { + $dom->save($table['xml_filename']); + return true; + } else { + return false; + // report about errors... + } + } + + } \ No newline at end of file diff --git a/monstra/helpers/agent.php b/monstra/helpers/agent.php new file mode 100644 index 0000000..f9ee9cc --- /dev/null +++ b/monstra/helpers/agent.php @@ -0,0 +1,171 @@ + + * if (Agent::isMobile()) { + * // Do something... + * } + *
    + * + * @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. + * + * + * if (Agent::isRobot()) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Agent::is('iphone')) { + * // Do something... + * } + * + * if (Agent::is(array('iphone', 'ipod'))) { + * // Do something... + * } + * + * + * @param mixed $device String or array of strings you're looking for + * @return boolean + */ + public static function is($device) { + return Agent::find((array) $device); + } + +} \ No newline at end of file diff --git a/monstra/helpers/alert.php b/monstra/helpers/alert.php new file mode 100644 index 0000000..316ad6d --- /dev/null +++ b/monstra/helpers/alert.php @@ -0,0 +1,97 @@ + + * Alert::success('Message here...'); + *
    + * + * @param string $message Message + * @param integer $time Time + */ + public static function success($message, $time = 3000) { + + // Redefine vars + $message = (string) $message; + $time = (int) $time; + + echo '
    '.$message.'
    + '; + } + + + /** + * Show warning message + * + * + * Alert::warning('Message here...'); + * + * + * @param string $message Message + * @param integer $time Time + */ + public static function warning($message, $time = 3000) { + + // Redefine vars + $message = (string) $message; + $time = (int) $time; + + echo '
    '.$message.'
    + '; + } + + + /** + * Show error message + * + * + * Alert::error('Message here...'); + * + * + * @param string $message Message + * @param integer $time Time + */ + public static function error($message, $time = 3000) { + + // Redefine vars + $message = (string) $message; + $time = (int) $time; + + echo '
    '.$message.'
    + '; + } + + } \ No newline at end of file diff --git a/monstra/helpers/arr.php b/monstra/helpers/arr.php new file mode 100644 index 0000000..456d000 --- /dev/null +++ b/monstra/helpers/arr.php @@ -0,0 +1,193 @@ + + * $new_array = Arr::subvalSort($old_array, 'sort'); + *
    + * + * @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. + * + * + * $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'); + * + * + * @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". + * + * + * Arr::delete($array, 'foo.bar'); + * + * + * @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. + * + * + * if (Arr::keyExists($array, 'foo.bar')) { + * // Do something... + * } + * + * + * @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. + * + * + * Arr::random(array('php', 'js', 'css', 'html')); + * + * + * @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. + * + * + * if (Arr::isAssoc($array)) { + * // Do something... + * } + * + * + * @param array $array Array to check + * @return boolean + */ + public static function isAssoc($array) { + return (bool) count(array_filter(array_keys($array), 'is_string')); + } + + } \ No newline at end of file diff --git a/monstra/helpers/cache.php b/monstra/helpers/cache.php new file mode 100644 index 0000000..34022e0 --- /dev/null +++ b/monstra/helpers/cache.php @@ -0,0 +1,225 @@ + + * Cache::configure('cache_dir', 'path/to/cache/dir'); + *
    + * + * @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 + * + * + * $profile = Cache::get('profiles', 'profile'); + * + * + * @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 + * + * + * $profile = array('login' => 'Awilum', + * 'email' => 'awilum@msn.com'); + * Cache::put('profiles', 'profile', $profile); + * + * + * @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 + * + * + * Cache::delete('profiles', 'profile'); + * + * + * @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. + * + * + * Cache::clean('profiles'); + * + * + * @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); + } + + + } \ No newline at end of file diff --git a/monstra/helpers/captcha.php b/monstra/helpers/captcha.php new file mode 100644 index 0000000..903cf5d --- /dev/null +++ b/monstra/helpers/captcha.php @@ -0,0 +1,84 @@ + + *
    + * + * + * + *
    + *
    + * + * @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. + * + * + * if (isset($_POST['submit'])) { + * if (Captcha::correctAnswer($_POST['answer'])) { + * // Do something... + * } + * } + * + * + * @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; + + } + + } diff --git a/monstra/helpers/cookie.php b/monstra/helpers/cookie.php new file mode 100644 index 0000000..29289f8 --- /dev/null +++ b/monstra/helpers/cookie.php @@ -0,0 +1,113 @@ + + * Cookie::set('limit', 10); + *
    + * + * @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 + * + * + * $limit = Cookie::get('limit'); + * + * + * @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 + * + * + * Cookie::delete('limit'); + * + * + * @param string $name The name of the cookie that should be deleted. + */ + public static function delete($key) { + unset($_COOKIE[$key]); + } + + } \ No newline at end of file diff --git a/monstra/helpers/curl.php b/monstra/helpers/curl.php new file mode 100644 index 0000000..015167d --- /dev/null +++ b/monstra/helpers/curl.php @@ -0,0 +1,153 @@ + '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. + * + * + * $res = Curl::get('http://site.com/'); + * + * + * @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. + * + * + * $res = Curl::post('http://site.com/login'); + * + * + * @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. + * + * + * $res = Curl::getInfo(); + * + * + * @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]; + } + + } \ No newline at end of file diff --git a/monstra/helpers/date.php b/monstra/helpers/date.php new file mode 100644 index 0000000..0adf332 --- /dev/null +++ b/monstra/helpers/date.php @@ -0,0 +1,432 @@ + + * echo Date::format($date, 'j.n.Y'); + *
    + * + * @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. + * + * + * $seconds = Date::seconds(); + * + * + * @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. + * + * + * $minutes = Date::minutes(); + * + * + * @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. + * + * + * $hours = Date::hours(); + * + * + * @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. + * + * + * $months = Date::months(); + * + * + * @return array + */ + public static function months() { + return Date::_range(1, 1, 12, true); + } + + + /** + * Get number of days. + * + * + * $months = Date::days(); + * + * + * @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 + * + * + * $days = Date::daysInMonth(1); + * + * + * @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. + * + * + * $years = Date::years(); + * + * + * @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 + * + * + * echo Date::season(); + * + * + * @return string + */ + public static function season() { + $seasons = array("Winter", "Spring", "Summer", "Autumn"); + return $seasons[(int)((date("n") %12)/3)]; + } + + + /** + * Get today date + * + * + * echo Date::today(); + * + * + * @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 + * + * + * echo Date::yesterday(); + * + * + * @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 + * + * + * echo Date::tomorrow(); + * + * + * @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. + * + * + * $dos = Date::unix2dos($unix); + * + * + * @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. + * + * + * $unix = Date::dos2unix($dos); + * + * + * @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 & Canada)', + 'America/Tijuana'=>'(GMT-08:00) Tijuana, Baja California', + 'America/Denver'=>'(GMT-07:00) Mountain Time (US & 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 & Canada)', + 'America/Mexico_City'=>'(GMT-06:00) Guadalajara, Mexico City, Monterrey', + 'America/New_York'=>'(GMT-05:00) Eastern Time (US & 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; + } + + } \ No newline at end of file diff --git a/monstra/helpers/debug.php b/monstra/helpers/debug.php new file mode 100644 index 0000000..71f886f --- /dev/null +++ b/monstra/helpers/debug.php @@ -0,0 +1,124 @@ + + * Debug::elapsedTimeSetPoint('point_name'); + * + * + * @param string $point_name Point name + */ + public static function elapsedTimeSetPoint($point_name) { + Debug::$time[$point_name] = microtime(true); + } + + + /** + * Get elapsed time for current point + * + * + * echo Debug::elapsedTime('point_name'); + * + * + * @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 + * + * + * Debug::memoryUsageSetPoint('point_name'); + * + * + * @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 + * + * + * echo Debug::memoryUsage('point_name'); + * + * + * @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 + * + * + * Debug::dump($data); + * + * + * @param mixed $data Data + * @param boolean $exit Exit + */ + public static function dump($data, $exit = false){ + echo "
    dump \n---------------------- \n\n" . print_r($data, true) . "\n----------------------
    "; + if ($exit) exit; + } + + } \ No newline at end of file diff --git a/monstra/helpers/dir.php b/monstra/helpers/dir.php new file mode 100644 index 0000000..a101102 --- /dev/null +++ b/monstra/helpers/dir.php @@ -0,0 +1,215 @@ + + * Dir::create('folder1'); + * + * + * @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. + * + * + * if (Dir::exists('folder1')) { + * // Do something... + * } + * + * + * @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 + * + * + * echo Dir::checkPerm('folder1'); + * + * + * @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 + * + * + * Dir::delete('folder1'); + * + * + * @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 + * + * + * $dirs = Dir::scan('folders'); + * + * + * @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. + * + * + * if (Dir::writable('folder1')) { + * // Do something... + * } + * + * + * @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. + * + * + * echo Dir::size('folder1'); + * + * + * @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; + } + + } diff --git a/monstra/helpers/file.php b/monstra/helpers/file.php new file mode 100644 index 0000000..eb23942 --- /dev/null +++ b/monstra/helpers/file.php @@ -0,0 +1,596 @@ + '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. + * + * + * if (File::exists('filename.txt')) { + * // Do something... + * } + * + * + * @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 + * + * + * File::delete('filename.txt'); + * + * + * @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 + * + * + * File::rename('filename1.txt', 'filename2.txt'); + * + * + * @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 + * + * + * File::copy('folder1/filename.txt', 'folder2/filename.txt'); + * + * + * @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. + * + * + * echo File::ext('filename.txt'); + * + * + * @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 + * + * + * echo File::name('filename.txt'); + * + * + * @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 + * + * + * $files = File::scan('folder'); + * $files = File::scan('folder', 'txt'); + * $files = File::scan('folder', array('txt', 'log')); + * + * + * @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. + * + * + * echo File::getContent('filename.txt'); + * + * + * @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 + * + * + * echo File::lastChange('filename.txt'); + * + * + * @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 + * + * + * echo File::lastAccess('filename.txt'); + * + * + * @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. + * + * + * echo File::mime('filename.txt'); + * + * + * @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. + * + * + * File::download('filename.txt'); + * + * + * @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. + * + * + * File::display('filename.txt'); + * + * + * @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. + * + * + * if (File::writable('filename.txt')) { + * // do something... + * } + * + * + * @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; + } + + } \ No newline at end of file diff --git a/monstra/helpers/form.php b/monstra/helpers/form.php new file mode 100644 index 0000000..1f473a5 --- /dev/null +++ b/monstra/helpers/form.php @@ -0,0 +1,363 @@ + + * // 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')); + * + * + * @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 ''; + } + + + /** + * Create a form input. + * Text is default input type. + * + * + * echo Form::input('username', $username); + * + * + * @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 ''; + } + + + /** + * Create a hidden form input. + * + * + * echo Form::hidden('user_id', $user_id); + * + * + * @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. + * + * + * echo Form::password('password'); + * + * + * @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. + * + * + * echo Form::file('image'); + * + * + * @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. + * + * + * echo Form::checkbox('i_am_not_a_robot'); + * + * + * @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. + * + * + * echo Form::radio('i_am_not_a_robot'); + * + * + * @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. + * + * + * echo Form::textarea('text', $text); + * + * + * @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 ''.$body.''; + } + + + /** + * Creates a select form input. + * + * + * echo Form::select('themes', array('default', 'classic', 'modern')); + * + * + * @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 .= ''; + } + + return ''.$options_output.''; + } + + + /** + * Creates a submit form input. + * + * + * echo Form::submit('save', 'Save'); + * + * + * @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. + * + * + * echo Form::button('save', 'Save Profile', array('type' => 'submit')); + * + * + * @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 ''.$body.''; + } + + + /** + * Creates a form label. + * + * + * echo Form::label('username', 'Username'); + * + * + * @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 ''.$text.''; + } + + + /** + * Create closing form tag. + * + * + * echo Form::close(); + * + * + * @return string + */ + public static function close() { + return ''; + } + + } \ No newline at end of file diff --git a/monstra/helpers/html.php b/monstra/helpers/html.php new file mode 100644 index 0000000..04c84d6 --- /dev/null +++ b/monstra/helpers/html.php @@ -0,0 +1,277 @@ + + * echo Html::chars($username); + * + * + * @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. + * + * + * echo ''.$content.''; + * + * + * @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 + * + * + * echo Html::br(2); + * + * + * @param integer $num Count of line break tag + * @return string + */ + public static function br($num = 1) { + return str_repeat("
    ",(int)$num); + } + + + /** + * Create   + * + * + * echo Html::nbsp(2); + * + * + * @param integer $num Count of   + * @return string + */ + public static function nbsp($num = 1) { + return str_repeat(" ", (int)$num); + } + + + /** + * Create an arrow + * + * + * echo Html::arrow('right'); + * + * + * @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 = ''; break; + case "down": $output = ''; break; + case "left": $output = ''; break; + case "right": $output = ''; break; + } + return $output; + } + + + /** + * Create HTML link anchor. + * + * + * echo Html::anchor('About', 'http://sitename.com/about'); + * + * + * @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 ''.$title.''; + } + + + /** + * Create HTML tag + * + * + * echo Html::heading('Title', 1); + * + * + * @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 = ''.$title.''; + + return $output; + } + + + /** + * Generate document type declarations + * + * + * echo Html::doctype('html5'); + * + * + * @param string $type Doctype to generated + * @return mixed + */ + public static function doctype($type = 'html5') { + + $doctypes = array('xhtml11' => '', + 'xhtml1-strict' => '', + 'xhtml1-trans' => '', + 'xhtml1-frame' => '', + 'html5' => '', + 'html4-strict' => '', + 'html4-trans' => '', + 'html4-frame' => ''); + + if (isset($doctypes[$type])) return $doctypes[$type]; else return false; + + } + + + /** + * Create image + * + * + * echo Html::image('data/files/pic1.jpg'); + * + * + * @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 ''; + } + + + /** + * Convert html to plain text + * + * + * echo Html::toText('test'); + * + * + * @param string $str String + * @return string + */ + public static function toText($str) { + return htmlspecialchars($str, ENT_QUOTES, 'utf-8'); + } + + } \ No newline at end of file diff --git a/monstra/helpers/image.php b/monstra/helpers/image.php new file mode 100644 index 0000000..619df77 --- /dev/null +++ b/monstra/helpers/image.php @@ -0,0 +1,673 @@ +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. + * + * + * $image = Image::factory('original.png'); + * + * + * @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. + * + * + * Image::factory('original.png')->resize(800, 600)->save('edited.png'); + * + * + * @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 + * + * + * Image::factory('original.png')->crop(800, 600, 0, 0)->save('edited.png'); + * + * + * @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 + * + * + * Image::factory('original.png')->grayscale()->save('edited.png'); + * + * + * @return Image + */ + public function grayscale() { + imagefilter($this->image, IMG_FILTER_GRAYSCALE); + return $this; + } + + + /** + * Convert image into sepia + * + * + * Image::factory('original.png')->sepia()->save('edited.png'); + * + * + * @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 + * + * + * Image::factory('original.png')->brightness(60)->save('edited.png'); + * + * + * @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 + * + * + * Image::factory('original.png')->colorize(60, 0, 0)->save('edited.png'); + * + * + * @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 + * + * + * Image::factory('original.png')->contrast(60)->save('edited.png'); + * + * + * @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. + * + * + * Image::factory('original.png')->rotate(90)->save('edited.png'); + * + * + * @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. + * + * + * Image::factory('original.png')->border('#000', 5)->save('edited.png'); + * + * + * @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 + * + * + * Image::factory('original.png')->save('edited.png'); + * + * + * @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); + } + + } \ No newline at end of file diff --git a/monstra/helpers/inflector.php b/monstra/helpers/inflector.php new file mode 100644 index 0000000..bb5cfc7 --- /dev/null +++ b/monstra/helpers/inflector.php @@ -0,0 +1,238 @@ + '\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. + * + * + * // "some_text_here" becomes "SomeTextHere" + * echo Inflector::camelize('some_text_here'); + * + * + * @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. + * + * + * // "SomeTextHere" becomes "some_text_here" + * echo Inflector::underscore('SomeTextHere'); + * + * + * @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. + * + * + * // "some_text_here" becomes "Some text here" + * echo Inflector::humanize('some_text_here'); + * + * + * @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. + * + * + * // 1 becomes 1st + * echo Inflector::ordinalize(1); + * + * + * @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 + * + * + * echo Inflector::pluralize('cat'); + * + * + * @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 + * + * + * echo Inflector::singularize('cats'); + * + * + * @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; + } + + } diff --git a/monstra/helpers/minify.php b/monstra/helpers/minify.php new file mode 100644 index 0000000..c90a292 --- /dev/null +++ b/monstra/helpers/minify.php @@ -0,0 +1,98 @@ + + * echo Minify::html($buffer); + * + * + * @param string $buffer html + * @return string + */ + public static function html($buffer) { + return preg_replace('/^\\s+|\\s+$/m', '', $buffer); + } + + + /** + * Minify css + * + * + * echo Minify::css($buffer); + * + * + * @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; + } + + } \ No newline at end of file diff --git a/monstra/helpers/notification.php b/monstra/helpers/notification.php new file mode 100644 index 0000000..34bc064 --- /dev/null +++ b/monstra/helpers/notification.php @@ -0,0 +1,150 @@ + + * echo Notification::get('success'); + * echo Notification::get('errors'); + * + * + * @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. + * + * + * Notification::set('success', 'Data has been saved with success!'); + * Notification::set('errors', 'Data not saved!'); + * + * + * @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. + * + * + * Notification::setNow('success', 'Success!'); + * + * + * @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. + * + * + * Notification::clean(); + * + * + * 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. + * + * + * Notification::init(); + * + * + * 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(); + + } + + } diff --git a/monstra/helpers/number.php b/monstra/helpers/number.php new file mode 100644 index 0000000..389a367 --- /dev/null +++ b/monstra/helpers/number.php @@ -0,0 +1,213 @@ + + * echo Number::byteFormat(10000); + * + * + * @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. + * + * + * echo Number::quantity(7000); // 7K + * echo Number::quantity(7500); // 8K + * echo Number::quantity(7500, 1); // 7.5K + * + * + * @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). + * + * + * if (Number::between(2, 10, 5)) { + * // do something... + * } + * + * + * @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. + * + * + * if (Number::even(2)) { + * // do something... + * } + * + * + * @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. + * + * + * if (Number::greaterThan(2, 10)) { + * // do something... + * } + * + * + * @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. + * + * + * if (Number::smallerThan(2, 10)) { + * // do something... + * } + * + * + * @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. + * + * + * if (Number::maximum(2, 10)) { + * // do something... + * } + * + * + * @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. + * + * + * if (Number::minimum(2, 10)) { + * // do something... + * } + * + * + * @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. + * + * + * if (Number::odd(2)) { + * // do something... + * } + * + * + * @param integer $value The value to validate. + * @return boolean + */ + public static function odd($value) { + return ! Number::even((int) $value); + } + + } + + diff --git a/monstra/helpers/orm.php b/monstra/helpers/orm.php new file mode 100644 index 0000000..005b790 --- /dev/null +++ b/monstra/helpers/orm.php @@ -0,0 +1,1141 @@ + 'sqlite::memory:', + 'id_column' => 'id', + 'id_column_overrides' => array(), + 'error_mode' => PDO::ERRMODE_EXCEPTION, + 'username' => null, + 'password' => null, + 'driver_options' => null, + 'identifier_quote_character' => null, // if this is null, will be autodetected + 'logging' => false, + 'caching' => false, + ); + + // Database connection, instance of the PDO class + protected static $_db; + + // Last query run, only populated if logging is enabled + protected static $_last_query; + + // Log of all queries run, only populated if logging is enabled + protected static $_query_log = array(); + + // Query cache, only used if query caching is enabled + protected static $_query_cache = array(); + + // --------------------------- // + // --- INSTANCE PROPERTIES --- // + // --------------------------- // + + // The name of the table the current ORM instance is associated with + protected $_table_name; + + // Alias for the table to be used in SELECT queries + protected $_table_alias = null; + + // Values to be bound to the query + protected $_values = array(); + + // Columns to select in the result + protected $_result_columns = array('*'); + + // Are we using the default result column or have these been manually changed? + protected $_using_default_result_columns = true; + + // Join sources + protected $_join_sources = array(); + + // Should the query include a DISTINCT keyword? + protected $_distinct = false; + + // Is this a raw query? + protected $_is_raw_query = false; + + // The raw query + protected $_raw_query = ''; + + // The raw query parameters + protected $_raw_parameters = array(); + + // Array of WHERE clauses + protected $_where_conditions = array(); + + // LIMIT + protected $_limit = null; + + // OFFSET + protected $_offset = null; + + // ORDER BY + protected $_order_by = array(); + + // GROUP BY + protected $_group_by = array(); + + // The data for a hydrated instance of the class + protected $_data = array(); + + // Fields that have been modified during the + // lifetime of the object + protected $_dirty_fields = array(); + + // Is this a new object (has create() been called)? + protected $_is_new = false; + + // Name of the column to use as the primary key for + // this instance only. Overrides the config settings. + protected $_instance_id_column = null; + + // ---------------------- // + // --- STATIC METHODS --- // + // ---------------------- // + + /** + * Pass configuration settings to the class in the form of + * key/value pairs. As a shortcut, if the second argument + * is omitted, the setting is assumed to be the DSN string + * used by PDO to connect to the database. Often, this + * will be the only configuration required to use Idiorm. + */ + public static function configure($key, $value=null) { + // Shortcut: If only one argument is passed, + // assume it's a connection string + if (is_null($value)) { + $value = $key; + $key = 'connection_string'; + } + self::$_config[$key] = $value; + } + + /** + * Despite its slightly odd name, this is actually the factory + * method used to acquire instances of the class. It is named + * this way for the sake of a readable interface, ie + * ORM::for_table('table_name')->find_one()-> etc. As such, + * this will normally be the first method called in a chain. + */ + public static function for_table($table_name) { + self::_setup_db(); + return new self($table_name); + } + + /** + * Set up the database connection used by the class. + */ + protected static function _setup_db() { + if (!is_object(self::$_db)) { + $connection_string = self::$_config['connection_string']; + $username = self::$_config['username']; + $password = self::$_config['password']; + $driver_options = self::$_config['driver_options']; + $db = new PDO($connection_string, $username, $password, $driver_options); + $db->setAttribute(PDO::ATTR_ERRMODE, self::$_config['error_mode']); + self::set_db($db); + } + } + + /** + * Set the PDO object used by Idiorm to communicate with the database. + * This is public in case the ORM should use a ready-instantiated + * PDO object as its database connection. + */ + public static function set_db($db) { + self::$_db = $db; + self::_setup_identifier_quote_character(); + } + + /** + * Detect and initialise the character used to quote identifiers + * (table names, column names etc). If this has been specified + * manually using ORM::configure('identifier_quote_character', 'some-char'), + * this will do nothing. + */ + public static function _setup_identifier_quote_character() { + if (is_null(self::$_config['identifier_quote_character'])) { + self::$_config['identifier_quote_character'] = self::_detect_identifier_quote_character(); + } + } + + /** + * Return the correct character used to quote identifiers (table + * names, column names etc) by looking at the driver being used by PDO. + */ + protected static function _detect_identifier_quote_character() { + switch(self::$_db->getAttribute(PDO::ATTR_DRIVER_NAME)) { + case 'pgsql': + case 'sqlsrv': + case 'dblib': + case 'mssql': + case 'sybase': + return '"'; + case 'mysql': + case 'sqlite': + case 'sqlite2': + default: + return '`'; + } + } + + /** + * Returns the PDO instance used by the the ORM to communicate with + * the database. This can be called if any low-level DB access is + * required outside the class. + */ + public static function get_db() { + self::_setup_db(); // required in case this is called before Idiorm is instantiated + return self::$_db; + } + + /** + * Add a query to the internal query log. Only works if the + * 'logging' config option is set to true. + * + * This works by manually binding the parameters to the query - the + * query isn't executed like this (PDO normally passes the query and + * parameters to the database which takes care of the binding) but + * doing it this way makes the logged queries more readable. + */ + protected static function _log_query($query, $parameters) { + // If logging is not enabled, do nothing + if (!self::$_config['logging']) { + return false; + } + + if (count($parameters) > 0) { + // Escape the parameters + $parameters = array_map(array(self::$_db, 'quote'), $parameters); + + // Replace placeholders in the query for vsprintf + $query = str_replace("?", "%s", $query); + + // Replace the question marks in the query with the parameters + $bound_query = vsprintf($query, $parameters); + } else { + $bound_query = $query; + } + + self::$_last_query = $bound_query; + self::$_query_log[] = $bound_query; + return true; + } + + /** + * Get the last query executed. Only works if the + * 'logging' config option is set to true. Otherwise + * this will return null. + */ + public static function get_last_query() { + return self::$_last_query; + } + + /** + * Get an array containing all the queries run up to + * now. Only works if the 'logging' config option is + * set to true. Otherwise returned array will be empty. + */ + public static function get_query_log() { + return self::$_query_log; + } + + // ------------------------ // + // --- INSTANCE METHODS --- // + // ------------------------ // + + /** + * "Private" constructor; shouldn't be called directly. + * Use the ORM::for_table factory method instead. + */ + protected function __construct($table_name, $data=array()) { + $this->_table_name = $table_name; + $this->_data = $data; + } + + /** + * Create a new, empty instance of the class. Used + * to add a new row to your database. May optionally + * be passed an associative array of data to populate + * the instance. If so, all fields will be flagged as + * dirty so all will be saved to the database when + * save() is called. + */ + public function create($data=null) { + $this->_is_new = true; + if (!is_null($data)) { + return $this->hydrate($data)->force_all_dirty(); + } + return $this; + } + + /** + * Specify the ID column to use for this instance or array of instances only. + * This overrides the id_column and id_column_overrides settings. + * + * This is mostly useful for libraries built on top of Idiorm, and will + * not normally be used in manually built queries. If you don't know why + * you would want to use this, you should probably just ignore it. + */ + public function use_id_column($id_column) { + $this->_instance_id_column = $id_column; + return $this; + } + + /** + * Create an ORM instance from the given row (an associative + * array of data fetched from the database) + */ + protected function _create_instance_from_row($row) { + $instance = self::for_table($this->_table_name); + $instance->use_id_column($this->_instance_id_column); + $instance->hydrate($row); + return $instance; + } + + /** + * Tell the ORM that you are expecting a single result + * back from your query, and execute it. Will return + * a single instance of the ORM class, or false if no + * rows were returned. + * As a shortcut, you may supply an ID as a parameter + * to this method. This will perform a primary key + * lookup on the table. + */ + public function find_one($id=null) { + if (!is_null($id)) { + $this->where_id_is($id); + } + $this->limit(1); + $rows = $this->_run(); + + if (empty($rows)) { + return false; + } + + return $this->_create_instance_from_row($rows[0]); + } + + /** + * Tell the ORM that you are expecting multiple results + * from your query, and execute it. Will return an array + * of instances of the ORM class, or an empty array if + * no rows were returned. + */ + public function find_many() { + $rows = $this->_run(); + return array_map(array($this, '_create_instance_from_row'), $rows); + } + + /** + * Tell the ORM that you wish to execute a COUNT query. + * Will return an integer representing the number of + * rows returned. + */ + public function count() { + $this->select_expr('COUNT(*)', 'count'); + $result = $this->find_one(); + return ($result !== false && isset($result->count)) ? (int) $result->count : 0; + } + + /** + * This method can be called to hydrate (populate) this + * instance of the class from an associative array of data. + * This will usually be called only from inside the class, + * but it's public in case you need to call it directly. + */ + public function hydrate($data=array()) { + $this->_data = $data; + return $this; + } + + /** + * Force the ORM to flag all the fields in the $data array + * as "dirty" and therefore update them when save() is called. + */ + public function force_all_dirty() { + $this->_dirty_fields = $this->_data; + return $this; + } + + /** + * Perform a raw query. The query should contain placeholders, + * in either named or question mark style, and the parameters + * should be an array of values which will be bound to the + * placeholders in the query. If this method is called, all + * other query building methods will be ignored. + */ + public function raw_query($query, $parameters) { + $this->_is_raw_query = true; + $this->_raw_query = $query; + $this->_raw_parameters = $parameters; + return $this; + } + + /** + * Add an alias for the main table to be used in SELECT queries + */ + public function table_alias($alias) { + $this->_table_alias = $alias; + return $this; + } + + /** + * Internal method to add an unquoted expression to the set + * of columns returned by the SELECT query. The second optional + * argument is the alias to return the expression as. + */ + protected function _add_result_column($expr, $alias=null) { + if (!is_null($alias)) { + $expr .= " AS " . $this->_quote_identifier($alias); + } + + if ($this->_using_default_result_columns) { + $this->_result_columns = array($expr); + $this->_using_default_result_columns = false; + } else { + $this->_result_columns[] = $expr; + } + return $this; + } + + /** + * Add a column to the list of columns returned by the SELECT + * query. This defaults to '*'. The second optional argument is + * the alias to return the column as. + */ + public function select($column, $alias=null) { + $column = $this->_quote_identifier($column); + return $this->_add_result_column($column, $alias); + } + + /** + * Add an unquoted expression to the list of columns returned + * by the SELECT query. The second optional argument is + * the alias to return the column as. + */ + public function select_expr($expr, $alias=null) { + return $this->_add_result_column($expr, $alias); + } + + /** + * Add a DISTINCT keyword before the list of columns in the SELECT query + */ + public function distinct() { + $this->_distinct = true; + return $this; + } + + /** + * Internal method to add a JOIN source to the query. + * + * The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this + * will be prepended to JOIN. + * + * The table should be the name of the table to join to. + * + * The constraint may be either a string or an array with three elements. If it + * is a string, it will be compiled into the query as-is, with no escaping. The + * recommended way to supply the constraint is as an array with three elements: + * + * first_column, operator, second_column + * + * Example: array('user.id', '=', 'profile.user_id') + * + * will compile to + * + * ON `user`.`id` = `profile`.`user_id` + * + * The final (optional) argument specifies an alias for the joined table. + */ + protected function _add_join_source($join_operator, $table, $constraint, $table_alias=null) { + + $join_operator = trim("{$join_operator} JOIN"); + + $table = $this->_quote_identifier($table); + + // Add table alias if present + if (!is_null($table_alias)) { + $table_alias = $this->_quote_identifier($table_alias); + $table .= " {$table_alias}"; + } + + // Build the constraint + if (is_array($constraint)) { + list($first_column, $operator, $second_column) = $constraint; + $first_column = $this->_quote_identifier($first_column); + $second_column = $this->_quote_identifier($second_column); + $constraint = "{$first_column} {$operator} {$second_column}"; + } + + $this->_join_sources[] = "{$join_operator} {$table} ON {$constraint}"; + return $this; + } + + /** + * Add a simple JOIN source to the query + */ + public function join($table, $constraint, $table_alias=null) { + return $this->_add_join_source("", $table, $constraint, $table_alias); + } + + /** + * Add an INNER JOIN souce to the query + */ + public function inner_join($table, $constraint, $table_alias=null) { + return $this->_add_join_source("INNER", $table, $constraint, $table_alias); + } + + /** + * Add a LEFT OUTER JOIN souce to the query + */ + public function left_outer_join($table, $constraint, $table_alias=null) { + return $this->_add_join_source("LEFT OUTER", $table, $constraint, $table_alias); + } + + /** + * Add an RIGHT OUTER JOIN souce to the query + */ + public function right_outer_join($table, $constraint, $table_alias=null) { + return $this->_add_join_source("RIGHT OUTER", $table, $constraint, $table_alias); + } + + /** + * Add an FULL OUTER JOIN souce to the query + */ + public function full_outer_join($table, $constraint, $table_alias=null) { + return $this->_add_join_source("FULL OUTER", $table, $constraint, $table_alias); + } + + /** + * Internal method to add a WHERE condition to the query + */ + protected function _add_where($fragment, $values=array()) { + if (!is_array($values)) { + $values = array($values); + } + $this->_where_conditions[] = array( + self::WHERE_FRAGMENT => $fragment, + self::WHERE_VALUES => $values, + ); + return $this; + } + + /** + * Helper method to compile a simple COLUMN SEPARATOR VALUE + * style WHERE condition into a string and value ready to + * be passed to the _add_where method. Avoids duplication + * of the call to _quote_identifier + */ + protected function _add_simple_where($column_name, $separator, $value) { + $column_name = $this->_quote_identifier($column_name); + return $this->_add_where("{$column_name} {$separator} ?", $value); + } + + /** + * Return a string containing the given number of question marks, + * separated by commas. Eg "?, ?, ?" + */ + protected function _create_placeholders($number_of_placeholders) { + return join(", ", array_fill(0, $number_of_placeholders, "?")); + } + + /** + * Add a WHERE column = value clause to your query. Each time + * this is called in the chain, an additional WHERE will be + * added, and these will be ANDed together when the final query + * is built. + */ + public function where($column_name, $value) { + return $this->where_equal($column_name, $value); + } + + /** + * More explicitly named version of for the where() method. + * Can be used if preferred. + */ + public function where_equal($column_name, $value) { + return $this->_add_simple_where($column_name, '=', $value); + } + + /** + * Add a WHERE column != value clause to your query. + */ + public function where_not_equal($column_name, $value) { + return $this->_add_simple_where($column_name, '!=', $value); + } + + /** + * Special method to query the table by its primary key + */ + public function where_id_is($id) { + return $this->where($this->_get_id_column_name(), $id); + } + + /** + * Add a WHERE ... LIKE clause to your query. + */ + public function where_like($column_name, $value) { + return $this->_add_simple_where($column_name, 'LIKE', $value); + } + + /** + * Add where WHERE ... NOT LIKE clause to your query. + */ + public function where_not_like($column_name, $value) { + return $this->_add_simple_where($column_name, 'NOT LIKE', $value); + } + + /** + * Add a WHERE ... > clause to your query + */ + public function where_gt($column_name, $value) { + return $this->_add_simple_where($column_name, '>', $value); + } + + /** + * Add a WHERE ... < clause to your query + */ + public function where_lt($column_name, $value) { + return $this->_add_simple_where($column_name, '<', $value); + } + + /** + * Add a WHERE ... >= clause to your query + */ + public function where_gte($column_name, $value) { + return $this->_add_simple_where($column_name, '>=', $value); + } + + /** + * Add a WHERE ... <= clause to your query + */ + public function where_lte($column_name, $value) { + return $this->_add_simple_where($column_name, '<=', $value); + } + + /** + * Add a WHERE ... IN clause to your query + */ + public function where_in($column_name, $values) { + $column_name = $this->_quote_identifier($column_name); + $placeholders = $this->_create_placeholders(count($values)); + return $this->_add_where("{$column_name} IN ({$placeholders})", $values); + } + + /** + * Add a WHERE ... NOT IN clause to your query + */ + public function where_not_in($column_name, $values) { + $column_name = $this->_quote_identifier($column_name); + $placeholders = $this->_create_placeholders(count($values)); + return $this->_add_where("{$column_name} NOT IN ({$placeholders})", $values); + } + + /** + * Add a WHERE column IS NULL clause to your query + */ + public function where_null($column_name) { + $column_name = $this->_quote_identifier($column_name); + return $this->_add_where("{$column_name} IS NULL"); + } + + /** + * Add a WHERE column IS NOT NULL clause to your query + */ + public function where_not_null($column_name) { + $column_name = $this->_quote_identifier($column_name); + return $this->_add_where("{$column_name} IS NOT NULL"); + } + + /** + * Add a raw WHERE clause to the query. The clause should + * contain question mark placeholders, which will be bound + * to the parameters supplied in the second argument. + */ + public function where_raw($clause, $parameters=array()) { + return $this->_add_where($clause, $parameters); + } + + /** + * Add a LIMIT to the query + */ + public function limit($limit) { + $this->_limit = $limit; + return $this; + } + + /** + * Add an OFFSET to the query + */ + public function offset($offset) { + $this->_offset = $offset; + return $this; + } + + /** + * Add an ORDER BY clause to the query + */ + protected function _add_order_by($column_name, $ordering) { + $column_name = $this->_quote_identifier($column_name); + $this->_order_by[] = "{$column_name} {$ordering}"; + return $this; + } + + /** + * Add an ORDER BY column DESC clause + */ + public function order_by_desc($column_name) { + return $this->_add_order_by($column_name, 'DESC'); + } + + /** + * Add an ORDER BY column ASC clause + */ + public function order_by_asc($column_name) { + return $this->_add_order_by($column_name, 'ASC'); + } + + /** + * Add a column to the list of columns to GROUP BY + */ + public function group_by($column_name) { + $column_name = $this->_quote_identifier($column_name); + $this->_group_by[] = $column_name; + return $this; + } + + /** + * Build a SELECT statement based on the clauses that have + * been passed to this instance by chaining method calls. + */ + protected function _build_select() { + // If the query is raw, just set the $this->_values to be + // the raw query parameters and return the raw query + if ($this->_is_raw_query) { + $this->_values = $this->_raw_parameters; + return $this->_raw_query; + } + + // Build and return the full SELECT statement by concatenating + // the results of calling each separate builder method. + return $this->_join_if_not_empty(" ", array( + $this->_build_select_start(), + $this->_build_join(), + $this->_build_where(), + $this->_build_group_by(), + $this->_build_order_by(), + $this->_build_limit(), + $this->_build_offset(), + )); + } + + /** + * Build the start of the SELECT statement + */ + protected function _build_select_start() { + $result_columns = join(', ', $this->_result_columns); + + if ($this->_distinct) { + $result_columns = 'DISTINCT ' . $result_columns; + } + + $fragment = "SELECT {$result_columns} FROM " . $this->_quote_identifier($this->_table_name); + + if (!is_null($this->_table_alias)) { + $fragment .= " " . $this->_quote_identifier($this->_table_alias); + } + return $fragment; + } + + /** + * Build the JOIN sources + */ + protected function _build_join() { + if (count($this->_join_sources) === 0) { + return ''; + } + + return join(" ", $this->_join_sources); + } + + /** + * Build the WHERE clause(s) + */ + protected function _build_where() { + // If there are no WHERE clauses, return empty string + if (count($this->_where_conditions) === 0) { + return ''; + } + + $where_conditions = array(); + foreach ($this->_where_conditions as $condition) { + $where_conditions[] = $condition[self::WHERE_FRAGMENT]; + $this->_values = array_merge($this->_values, $condition[self::WHERE_VALUES]); + } + + return "WHERE " . join(" AND ", $where_conditions); + } + + /** + * Build GROUP BY + */ + protected function _build_group_by() { + if (count($this->_group_by) === 0) { + return ''; + } + return "GROUP BY " . join(", ", $this->_group_by); + } + + /** + * Build ORDER BY + */ + protected function _build_order_by() { + if (count($this->_order_by) === 0) { + return ''; + } + return "ORDER BY " . join(", ", $this->_order_by); + } + + /** + * Build LIMIT + */ + protected function _build_limit() { + if (!is_null($this->_limit)) { + return "LIMIT " . $this->_limit; + } + return ''; + } + + /** + * Build OFFSET + */ + protected function _build_offset() { + if (!is_null($this->_offset)) { + return "OFFSET " . $this->_offset; + } + return ''; + } + + /** + * Wrapper around PHP's join function which + * only adds the pieces if they are not empty. + */ + protected function _join_if_not_empty($glue, $pieces) { + $filtered_pieces = array(); + foreach ($pieces as $piece) { + if (is_string($piece)) { + $piece = trim($piece); + } + if (!empty($piece)) { + $filtered_pieces[] = $piece; + } + } + return join($glue, $filtered_pieces); + } + + /** + * Quote a string that is used as an identifier + * (table names, column names etc). This method can + * also deal with dot-separated identifiers eg table.column + */ + protected function _quote_identifier($identifier) { + $parts = explode('.', $identifier); + $parts = array_map(array($this, '_quote_identifier_part'), $parts); + return join('.', $parts); + } + + /** + * This method performs the actual quoting of a single + * part of an identifier, using the identifier quote + * character specified in the config (or autodetected). + */ + protected function _quote_identifier_part($part) { + if ($part === '*') { + return $part; + } + $quote_character = self::$_config['identifier_quote_character']; + return $quote_character . $part . $quote_character; + } + + /** + * Create a cache key for the given query and parameters. + */ + protected static function _create_cache_key($query, $parameters) { + $parameter_string = join(',', $parameters); + $key = $query . ':' . $parameter_string; + return sha1($key); + } + + /** + * Check the query cache for the given cache key. If a value + * is cached for the key, return the value. Otherwise, return false. + */ + protected static function _check_query_cache($cache_key) { + if (isset(self::$_query_cache[$cache_key])) { + return self::$_query_cache[$cache_key]; + } + return false; + } + + /** + * Clear the query cache + */ + public static function clear_cache() { + self::$_query_cache = array(); + } + + /** + * Add the given value to the query cache. + */ + protected static function _cache_query_result($cache_key, $value) { + self::$_query_cache[$cache_key] = $value; + } + + /** + * Execute the SELECT query that has been built up by chaining methods + * on this class. Return an array of rows as associative arrays. + */ + protected function _run() { + $query = $this->_build_select(); + $caching_enabled = self::$_config['caching']; + + if ($caching_enabled) { + $cache_key = self::_create_cache_key($query, $this->_values); + $cached_result = self::_check_query_cache($cache_key); + + if ($cached_result !== false) { + return $cached_result; + } + } + + self::_log_query($query, $this->_values); + $statement = self::$_db->prepare($query); + $statement->execute($this->_values); + + $rows = array(); + while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { + $rows[] = $row; + } + + if ($caching_enabled) { + self::_cache_query_result($cache_key, $rows); + } + + return $rows; + } + + /** + * Return the raw data wrapped by this ORM + * instance as an associative array. Column + * names may optionally be supplied as arguments, + * if so, only those keys will be returned. + */ + public function as_array() { + if (func_num_args() === 0) { + return $this->_data; + } + $args = func_get_args(); + return array_intersect_key($this->_data, array_flip($args)); + } + + /** + * Return the value of a property of this object (database row) + * or null if not present. + */ + public function get($key) { + return isset($this->_data[$key]) ? $this->_data[$key] : null; + } + + /** + * Return the name of the column in the database table which contains + * the primary key ID of the row. + */ + protected function _get_id_column_name() { + if (!is_null($this->_instance_id_column)) { + return $this->_instance_id_column; + } + if (isset(self::$_config['id_column_overrides'][$this->_table_name])) { + return self::$_config['id_column_overrides'][$this->_table_name]; + } else { + return self::$_config['id_column']; + } + } + + /** + * Get the primary key ID of this object. + */ + public function id() { + return $this->get($this->_get_id_column_name()); + } + + /** + * Set a property to a particular value on this object. + * Flags that property as 'dirty' so it will be saved to the + * database when save() is called. + */ + public function set($key, $value) { + $this->_data[$key] = $value; + $this->_dirty_fields[$key] = $value; + } + + /** + * Check whether the given field has been changed since this + * object was saved. + */ + public function is_dirty($key) { + return isset($this->_dirty_fields[$key]); + } + + /** + * Save any fields which have been modified on this object + * to the database. + */ + public function save() { + $query = array(); + $values = array_values($this->_dirty_fields); + + if (!$this->_is_new) { // UPDATE + // If there are no dirty values, do nothing + if (count($values) == 0) { + return true; + } + $query = $this->_build_update(); + $values[] = $this->id(); + } else { // INSERT + $query = $this->_build_insert(); + } + + self::_log_query($query, $values); + $statement = self::$_db->prepare($query); + $success = $statement->execute($values); + + // If we've just inserted a new record, set the ID of this object + if ($this->_is_new) { + $this->_is_new = false; + if (is_null($this->id())) { + $this->_data[$this->_get_id_column_name()] = self::$_db->lastInsertId(); + } + } + + $this->_dirty_fields = array(); + return $success; + } + + /** + * Build an UPDATE query + */ + protected function _build_update() { + $query = array(); + $query[] = "UPDATE {$this->_quote_identifier($this->_table_name)} SET"; + + $field_list = array(); + foreach ($this->_dirty_fields as $key => $value) { + $field_list[] = "{$this->_quote_identifier($key)} = ?"; + } + $query[] = join(", ", $field_list); + $query[] = "WHERE"; + $query[] = $this->_quote_identifier($this->_get_id_column_name()); + $query[] = "= ?"; + return join(" ", $query); + } + + /** + * Build an INSERT query + */ + protected function _build_insert() { + $query[] = "INSERT INTO"; + $query[] = $this->_quote_identifier($this->_table_name); + $field_list = array_map(array($this, '_quote_identifier'), array_keys($this->_dirty_fields)); + $query[] = "(" . join(", ", $field_list) . ")"; + $query[] = "VALUES"; + + $placeholders = $this->_create_placeholders(count($this->_dirty_fields)); + $query[] = "({$placeholders})"; + return join(" ", $query); + } + + /** + * Delete this record from the database + */ + public function delete() { + $query = join(" ", array( + "DELETE FROM", + $this->_quote_identifier($this->_table_name), + "WHERE", + $this->_quote_identifier($this->_get_id_column_name()), + "= ?", + )); + $params = array($this->id()); + self::_log_query($query, $params); + $statement = self::$_db->prepare($query); + return $statement->execute($params); + } + + // --------------------- // + // --- MAGIC METHODS --- // + // --------------------- // + public function __get($key) { + return $this->get($key); + } + + public function __set($key, $value) { + $this->set($key, $value); + } + + public function __isset($key) { + return isset($this->_data[$key]); + } + } diff --git a/monstra/helpers/request.php b/monstra/helpers/request.php new file mode 100644 index 0000000..92d57da --- /dev/null +++ b/monstra/helpers/request.php @@ -0,0 +1,161 @@ + + * Request::redirect('test'); + * + * + * @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 "\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. + * + * + * Request::setHeaders('Location: http://site.com/'); + * + * + * @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 + * + * + * $action = Request::get('action'); + * + * + * @param string $key Key + * @param mixed + */ + public static function get($key) { + return Arr::get($_GET, $key); + } + + + /** + * Post + * + * + * $login = Request::post('login'); + * + * + * @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 + * + * + * if (Request::isAjax()) { + * // do something... + * } + * + * + * @return boolean + */ + public static function isAjax() { + return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'; + } + + + /** + * Terminate request + * + * + * Request::shutdown(); + * + * + */ + public static function shutdown() { + exit(0); + } + + } \ No newline at end of file diff --git a/monstra/helpers/response.php b/monstra/helpers/response.php new file mode 100644 index 0000000..a006deb --- /dev/null +++ b/monstra/helpers/response.php @@ -0,0 +1,109 @@ + '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 + * + * + * Response::status(404); + * + * + * @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]); + } + + + } \ No newline at end of file diff --git a/monstra/helpers/security.php b/monstra/helpers/security.php new file mode 100644 index 0000000..5446ede --- /dev/null +++ b/monstra/helpers/security.php @@ -0,0 +1,250 @@ + + * $token = Security::token(); + * + * + * You can insert this token into your forms as a hidden field: + * + * + * echo Form::hidden('csrf', Security::token()); + * + * + * 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. + * + * + * if (Security::check($token)) { + * // Pass + * } + * + * + * @param string $token token to check + * @return boolean + */ + public static function check($token) { + return Security::token() === $token; + } + + + + /** + * Encrypt password + * + * + * $encrypt_password = Security::encryptPassword('password'); + * + * + * @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. + * + * + * $safe_name = Security::safeName('hello world'); + * + * + * @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. + * + * + * $url = Security::sanitizeURL('http://test.com'); + * + * + * @param string $url Url to sanitize + * @return string + */ + public static function sanitizeURL($url) { + + $url = trim($url); + $url = rawurldecode($url); + $url = str_replace(array('--','"','!','@','#','$','%','^','*','(',')','+','{','}','|',':','"','<','>', + '[',']','\\',';',"'",',','*','+','~','`','laquo','raquo',']>','‘','’','“','”','–','—'), + 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; + } + + } diff --git a/monstra/helpers/session.php b/monstra/helpers/session.php new file mode 100644 index 0000000..ae88f82 --- /dev/null +++ b/monstra/helpers/session.php @@ -0,0 +1,198 @@ + + * Session::start(); + * + * + */ + 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. + * + * + * Session::delete('user'); + * + * + */ + 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. + * + * + * Session::destroy(); + * + * + */ + public static function destroy() { + + // Destroy + if (session_id()) { + session_unset(); + session_destroy(); + $_SESSION = array(); + } + + } + + + /** + * Checks if a session variable exists. + * + * + * if (Session::exists('user')) { + * // Do something... + * } + * + * + * @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. + * + * + * echo Session::get('user'); + * + * + * @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. + * + * + * echo Session::getSessionId(); + * + * + * @return string + */ + public static function getSessionId() { + if ( ! session_id()) Session::start(); + return session_id(); + } + + + /** + * Stores a variable in the session. + * + * + * Session::set('user', 'Awilum'); + * + * + * @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; + } + + + } diff --git a/monstra/helpers/text.php b/monstra/helpers/text.php new file mode 100644 index 0000000..67cfdb4 --- /dev/null +++ b/monstra/helpers/text.php @@ -0,0 +1,470 @@ + latin + * + * + * echo Text::translitIt('Привет'); + * + * + * @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 + * + * + * echo Text::trimSlashes('some text here/'); + * + * + * @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 + * + * + * echo Text::strpSlashes('some \ text \ here'); + * + * + * @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 + * + * + * echo Text::stripQuotes('some "text" here'); + * + * + * @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 + * + * + * echo Text::quotesToEntities('some "text" here'); + * + * + * @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("'", """, "'", """), $str); + } + + + /** + * Creates a random string of characters + * + * + * echo Text::random(); + * + * + * @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 + * + * + * echo Text::cut('Some text here', 5); + * + * + * @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 + * + * + * echo Text::lowercase('Some text here'); + * + * + * @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 + * + * + * echo Text::uppercase('some text here'); + * + * + * @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 + * + * + * echo Text::length('Some text here'); + * + * + * @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 + * + * + * echo Text::lorem(2); + * + * + * @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. + * + * + * echo Text::right('Some text here', 4); + * + * + * @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. + * + * + * echo Text::left('Some text here', 4); + * + * + * @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
    or
    . + * + * + * echo Text::nl2br("Some \n text \n here"); + * + * + * @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) ? '
    ' : '
    '), $str); + } + + + /** + * Replaces
    and
    with newline. + * + * + * echo Text::br2nl("Some
    text
    here"); + *
    + * + * @param string $str The input string + * @return string + */ + public static function br2nl($str) { + + // Redefine vars + $str = (string) $str; + + return str_replace(array('
    ', '
    ', '
    '), "\n", $str); + } + + + /** + * Converts & to &. + * + * + * echo Text::ampEncode("M&CMS"); + * + * + * @param string $str The input string + * @return string + */ + public static function ampEncode($str) { + + // Redefine vars + $str = (string) $str; + + return str_replace('&', '&', $str); + } + + + /** + * Converts & to &. + * + * + * echo Text::ampEncode("M&CMS"); + * + * + * @param string $str The input string + * @return string + */ + public static function ampDecode($str) { + + // Redefine vars + $str = (string) $str; + + return str_replace('&', '&', $str); + } + + + /** + * Convert plain text to html + * + * + * echo Text::toHtml('test'); + * + * + * @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'); + } + + } \ No newline at end of file diff --git a/monstra/helpers/uri.php b/monstra/helpers/uri.php new file mode 100644 index 0000000..cf551f9 --- /dev/null +++ b/monstra/helpers/uri.php @@ -0,0 +1,171 @@ + + * $segments = Uri::segments(); + * + * + * @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 + * + * + * $segment = Uri::segment(1); + * + * + * @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 + * + * + * $command = Uri::command(); + * + * + * @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 + * + * + * $params = Uri::params(); + * + * + * @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; + } + + } \ No newline at end of file diff --git a/monstra/helpers/url.php b/monstra/helpers/url.php new file mode 100644 index 0000000..66a3d71 --- /dev/null +++ b/monstra/helpers/url.php @@ -0,0 +1,115 @@ + + * echo Url::tiny('http:://sitename.com'); + * + * + * @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 + * + * + * if(Url::exists('http:://sitename.com')) { + * // Do something... + * } + * + * + * @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 + * + * + * // Outputs: http://sitename.com/home + * echo Url::find('home'); + * + * + * @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 + * + * + * echo Url::base(); + * + * + * @return string + */ + public static function base() { + return 'http://' . rtrim(rtrim($_SERVER['HTTP_HOST'], '\\/') . dirname($_SERVER['PHP_SELF']), '\\/'); + } + + } \ No newline at end of file diff --git a/monstra/helpers/valid.php b/monstra/helpers/valid.php new file mode 100644 index 0000000..c2db15f --- /dev/null +++ b/monstra/helpers/valid.php @@ -0,0 +1,208 @@ + + * if (Valid::email('test@test.com')) { + * // Do something... + * } + * + * + * @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.]+(? + * if (Valid::ip('127.0.0.1')) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Valid::creditCard(7711111111111111, 'Visa')) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Valid::phone(0661111117)) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Valid::url('http://site.com/')) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Valid::date('12/12/12')) { + * // Do something... + * } + * + * + * @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). + * + * + * if (Valid::digit('12')) { + * // Do something... + * } + * + * + * @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). + * + * + * if (Valid::numeric('3.14')) { + * // Do something... + * } + * + * + * 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); + + } + + } \ No newline at end of file diff --git a/monstra/helpers/zip.php b/monstra/helpers/zip.php new file mode 100644 index 0000000..89b78c6 --- /dev/null +++ b/monstra/helpers/zip.php @@ -0,0 +1,385 @@ +now = time(); + } + + + /** + * Zip factory + * + * + * Zip::factory(); + * + * + * @return Zip + */ + public static function factory() { + return new Zip(); + } + + + /** + * Add Directory + * + * + * Zip::factory()->addDir('test'); + * + * + * @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 + * + * + * Zip::factory()->addData('test.txt', 'Some test text here'); + * + * + * 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 + * + * + * Zip::factory()->readFile('test.txt'); + * + * + * @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. + * + * + * Zip::factory()->readDir('test/'); + * + * + * 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 + * + * + * Zip::factory()->getZip(); + * + * + * @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 + * + * + * Zip::factory()->readDir('test1/')->readDir('test2/')->archive('test.zip'); + * + * + * @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 + * + * + * Zip::factory()->clearData(); + * + * + * 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; + } + + } diff --git a/plugins/.htaccess b/plugins/.htaccess new file mode 100644 index 0000000..14249c5 --- /dev/null +++ b/plugins/.htaccess @@ -0,0 +1 @@ +Deny from all \ No newline at end of file diff --git a/plugins/box/backup/backup.admin.php b/plugins/box/backup/backup.admin.php new file mode 100644 index 0000000..6580be5 --- /dev/null +++ b/plugins/box/backup/backup.admin.php @@ -0,0 +1,60 @@ +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(); + } + } \ No newline at end of file diff --git a/plugins/box/backup/backup.plugin.php b/plugins/box/backup/backup.plugin.php new file mode 100644 index 0000000..8e03513 --- /dev/null +++ b/plugins/box/backup/backup.plugin.php @@ -0,0 +1,34 @@ + + + plugins/box/backup/backup.plugin.php + active + 8 + Backup + Backup plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/backup/languages/en.lang.php b/plugins/box/backup/languages/en.lang.php new file mode 100644 index 0000000..33f5da0 --- /dev/null +++ b/plugins/box/backup/languages/en.lang.php @@ -0,0 +1,17 @@ + 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...', + ) + ); \ No newline at end of file diff --git a/plugins/box/backup/languages/ru.lang.php b/plugins/box/backup/languages/ru.lang.php new file mode 100644 index 0000000..6c0162f --- /dev/null +++ b/plugins/box/backup/languages/ru.lang.php @@ -0,0 +1,17 @@ + array( + 'Backups' => 'Бекапы', + 'Backup date' => 'Бекап', + 'Create backup' => 'Сделать бекап', + 'Delete' => 'Удалить', + 'storage' => 'данные', + 'public' => 'публичная', + 'plugins' => 'плагины', + 'Size' => 'Размер', + 'Actions' => 'Действия', + 'Delete backup: :backup' => 'Удалить бекап: :backup', + 'Creating...' => 'Создание...', + ) + ); \ No newline at end of file diff --git a/plugins/box/backup/views/backend/index.view.php b/plugins/box/backup/views/backend/index.view.php new file mode 100644 index 0000000..99cbd53 --- /dev/null +++ b/plugins/box/backup/views/backend/index.view.php @@ -0,0 +1,48 @@ +

    +
    + + + + + + '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() + ); +?> + + + + + + + + + + + + 0) rsort($backups_list); foreach ($backups_list as $backup) { ?> + + + + + + + +
    + + + + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete backup: :backup', 'backup', array(':backup' => Date::format($name, 'F jS, Y - g:i A')))."')")); + ?> +
    + \ No newline at end of file diff --git a/plugins/box/blocks/blocks.admin.php b/plugins/box/blocks/blocks.admin.php new file mode 100644 index 0000000..cf40d89 --- /dev/null +++ b/plugins/box/blocks/blocks.admin.php @@ -0,0 +1,139 @@ +:name 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 :name 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 :name 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(); + + } + } + + } \ No newline at end of file diff --git a/plugins/box/blocks/blocks.plugin.php b/plugins/box/blocks/blocks.plugin.php new file mode 100644 index 0000000..46c1333 --- /dev/null +++ b/plugins/box/blocks/blocks.plugin.php @@ -0,0 +1,73 @@ + $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 __('Block :name is not found!', 'blocks', array(':name' => $name)); + } + } + } + } \ No newline at end of file diff --git a/plugins/box/blocks/install/blocks.manifest.xml b/plugins/box/blocks/install/blocks.manifest.xml new file mode 100644 index 0000000..a708260 --- /dev/null +++ b/plugins/box/blocks/install/blocks.manifest.xml @@ -0,0 +1,13 @@ + + + plugins/box/blocks/blocks.plugin.php + yes + yes + active + 6 + Blocks + Blocks manager plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/blocks/languages/en.lang.php b/plugins/box/blocks/languages/en.lang.php new file mode 100644 index 0000000..c7f8e54 --- /dev/null +++ b/plugins/box/blocks/languages/en.lang.php @@ -0,0 +1,25 @@ + 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 :name deleted' => 'Block :name deleted', + 'Your changes to the block :name have been saved.' => 'Your changes to the block :name have been saved.', + 'Delete block: :block' => 'Delete block: :block', + ) + ); \ No newline at end of file diff --git a/plugins/box/blocks/languages/ru.lang.php b/plugins/box/blocks/languages/ru.lang.php new file mode 100644 index 0000000..3930352 --- /dev/null +++ b/plugins/box/blocks/languages/ru.lang.php @@ -0,0 +1,25 @@ + 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 :name deleted' => 'Сниппет :name удален', + 'Your changes to the block :name have been saved.' => 'Ваши изменения к блоку :name были сохранены.', + 'Delete block: :block' => 'Удалить блок: :block', + ) + ); \ No newline at end of file diff --git a/plugins/box/blocks/views/backend/add.view.php b/plugins/box/blocks/views/backend/add.view.php new file mode 100644 index 0000000..89ab1fd --- /dev/null +++ b/plugins/box/blocks/views/backend/add.view.php @@ -0,0 +1,36 @@ +

    +
    + + + + + + + + + + + + + + 'span5'))); ?> + + '.$errors['blocks_empty_name'].'
    '; + if (isset($errors['blocks_exists'])) echo '   '.$errors['blocks_exists'].''; + ?> + +

    + 'btn')).Html::nbsp(2). + Form::submit('add_blocks', __('Save', 'blocks'), array('class' => 'btn')). + Form::close() + ); + +?> + diff --git a/plugins/box/blocks/views/backend/edit.view.php b/plugins/box/blocks/views/backend/edit.view.php new file mode 100644 index 0000000..e93c055 --- /dev/null +++ b/plugins/box/blocks/views/backend/edit.view.php @@ -0,0 +1,44 @@ +

    +
    + + + + + + + + + 'span5'))); ?> + + '.$errors['blocks_empty_name'].'
    '; + if (isset($errors['blocks_exists'])) echo '   '.$errors['blocks_exists'].''; + ?> + +

    + 'btn default')).Html::nbsp(2). + Form::submit('edit_blocks', __('Save', 'blocks'), array('class' => 'btn default')). Html::nbsp(). + Form::close() + ); + + } else { + echo '
    '.__('This block does not exist', 'blocks').'
    '; + } +?> \ No newline at end of file diff --git a/plugins/box/blocks/views/backend/index.view.php b/plugins/box/blocks/views/backend/index.view.php new file mode 100644 index 0000000..d91fece --- /dev/null +++ b/plugins/box/blocks/views/backend/index.view.php @@ -0,0 +1,34 @@ +

    +
    + + + + __('Create new block', 'blocks'), 'class' => 'btn default btn-small')). Html::nbsp(3) + ); +?> + +

    + + + + + + + + + + + + + + +
    + 'btn btn-actions')); ?> + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete block: :block', 'blocks', array(':block' => basename($block, '.block.html')))."')")); + ?> +
    + \ No newline at end of file diff --git a/plugins/box/editor/editor.plugin.php b/plugins/box/editor/editor.plugin.php new file mode 100644 index 0000000..d44805c --- /dev/null +++ b/plugins/box/editor/editor.plugin.php @@ -0,0 +1,43 @@ +
    '); + } + + } \ No newline at end of file diff --git a/plugins/box/editor/install/editor.manifest.xml b/plugins/box/editor/install/editor.manifest.xml new file mode 100644 index 0000000..f131b06 --- /dev/null +++ b/plugins/box/editor/install/editor.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/editor/editor.plugin.php + active + 1 + Editor + Editor plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/editor/languages/en.lang.php b/plugins/box/editor/languages/en.lang.php new file mode 100644 index 0000000..d6501d6 --- /dev/null +++ b/plugins/box/editor/languages/en.lang.php @@ -0,0 +1,8 @@ + array( + 'Editor' => 'Editor', + 'Editor plugin' => 'Editor plugin', + ) + ); \ No newline at end of file diff --git a/plugins/box/editor/languages/ru.lang.php b/plugins/box/editor/languages/ru.lang.php new file mode 100644 index 0000000..03781e7 --- /dev/null +++ b/plugins/box/editor/languages/ru.lang.php @@ -0,0 +1,8 @@ + array( + 'Editor' => 'Редактор', + 'Editor plugin' => 'Редактор плагин', + ) + ); \ No newline at end of file diff --git a/plugins/box/filesmanager/filesmanager.admin.php b/plugins/box/filesmanager/filesmanager.admin.php new file mode 100644 index 0000000..d9b994d --- /dev/null +++ b/plugins/box/filesmanager/filesmanager.admin.php @@ -0,0 +1,146 @@ +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; + } + } + + } diff --git a/plugins/box/filesmanager/filesmanager.plugin.php b/plugins/box/filesmanager/filesmanager.plugin.php new file mode 100644 index 0000000..28dc7c2 --- /dev/null +++ b/plugins/box/filesmanager/filesmanager.plugin.php @@ -0,0 +1,31 @@ + + + plugins/box/filesmanager/filesmanager.plugin.php + active + 2 + FilesManager + Simple file manger for Monstra + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/filesmanager/languages/en.lang.php b/plugins/box/filesmanager/languages/en.lang.php new file mode 100644 index 0000000..a8ed5f5 --- /dev/null +++ b/plugins/box/filesmanager/languages/en.lang.php @@ -0,0 +1,17 @@ + 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', + ) + ); \ No newline at end of file diff --git a/plugins/box/filesmanager/languages/ru.lang.php b/plugins/box/filesmanager/languages/ru.lang.php new file mode 100644 index 0000000..2c879fe --- /dev/null +++ b/plugins/box/filesmanager/languages/ru.lang.php @@ -0,0 +1,17 @@ + array( + 'Files' => 'Файлы', + 'Files manager' => 'Менеджер файлов', + 'Name' => 'Название', + 'Actions' => 'Действия', + 'Delete' => 'Удалить', + 'Upload' => 'Загрузить', + 'directory' => 'директория', + 'Delete directory: :dir' => 'Удалить директорию: :dir', + 'Delete file: :file' => 'Удалить файл :file', + 'Extension' => 'Расширение', + 'Size' => 'Размер', + ) + ); \ No newline at end of file diff --git a/plugins/box/filesmanager/views/backend/index.view.php b/plugins/box/filesmanager/views/backend/index.view.php new file mode 100644 index 0000000..8e5fb49 --- /dev/null +++ b/plugins/box/filesmanager/views/backend/index.view.php @@ -0,0 +1,80 @@ +

    +
    + + + '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() + ) + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + 'btn', 'onclick' => "return confirmDelete('".__('Delete directory: :dir', 'filesmanager', array(':dir' => $dir))."')")); + ?> +
    + '_blank'));?> + + + + + + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete file: :file', 'filesmanager', array(':file' => $file))."')")); + ?> +
    \ No newline at end of file diff --git a/plugins/box/information/information.admin.php b/plugins/box/information/information.admin.php new file mode 100644 index 0000000..affdaec --- /dev/null +++ b/plugins/box/information/information.admin.php @@ -0,0 +1,20 @@ +display(); + } + + + } diff --git a/plugins/box/information/information.plugin.php b/plugins/box/information/information.plugin.php new file mode 100644 index 0000000..02e7eaa --- /dev/null +++ b/plugins/box/information/information.plugin.php @@ -0,0 +1,31 @@ + + + plugins/box/information/information.plugin.php + active + 7 + Information + Information plugin + 1.0.0 + Awilum + http://awilum.webdevart.ru/ + \ No newline at end of file diff --git a/plugins/box/information/languages/en.lang.php b/plugins/box/information/languages/en.lang.php new file mode 100644 index 0000000..8378a70 --- /dev/null +++ b/plugins/box/information/languages/en.lang.php @@ -0,0 +1,27 @@ + 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.
    You can do this on unix systems with: chmod -R a-w :path' => + '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.
    You can do this on unix systems with: chmod -R a-w :path', + 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => + 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path', + 'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => + 'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path', + '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.', + ) + ); \ No newline at end of file diff --git a/plugins/box/information/languages/ru.lang.php b/plugins/box/information/languages/ru.lang.php new file mode 100644 index 0000000..e89d7f9 --- /dev/null +++ b/plugins/box/information/languages/ru.lang.php @@ -0,0 +1,27 @@ + 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.
    You can do this on unix systems with: chmod -R a-w :path' => + 'Директория Monstra (":path") доступна для записи. Мы рекомендуем вам удалить права записи на директорию (":path") на живом сайте.
    Вы можете сделать это на UNIX системах так: chmod -R a-w :path', + 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => + 'Главный .htaccess доступен для записи. Мы рекомендуем вам удалить права записи на главный .htaccess файл.
    Вы можете сделать это на UNIX системах так: chmod -R a-w :path', + 'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => + 'Главный index.php файл доступен для записи. Мы рекомендуем вам удалить права записи на главный index.php файл.
    Вы можете сделать это на UNIX системах так: chmod -R a-w :path', + '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 на живом сайте.', + ) + ); \ No newline at end of file diff --git a/plugins/box/information/views/backend/index.view.php b/plugins/box/information/views/backend/index.view.php new file mode 100644 index 0000000..e47cc0c --- /dev/null +++ b/plugins/box/information/views/backend/index.view.php @@ -0,0 +1,89 @@ +

    +
    + +
    + + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    !
    ! You can do this on unix systems with: chmod -R a-w :path', 'information', array(':path' => MONSTRA . DS)); ?>
    ! You can do this on unix systems with: chmod a-w :path', 'information', array(':path' => ROOT . DS . '.htaccess')); ?>
    ! You can do this on unix systems with: chmod a-w :path', 'information', array(':path' => ROOT . DS . 'index.php')); ?>
    !
    + +
    + +
    +
    \ No newline at end of file diff --git a/plugins/box/menu/install/menu.manifest.xml b/plugins/box/menu/install/menu.manifest.xml new file mode 100644 index 0000000..303f589 --- /dev/null +++ b/plugins/box/menu/install/menu.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/menu/menu.plugin.php + active + 4 + Menu + Menu managment plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/menu/languages/en.lang.php b/plugins/box/menu/languages/en.lang.php new file mode 100644 index 0000000..92397ec --- /dev/null +++ b/plugins/box/menu/languages/en.lang.php @@ -0,0 +1,24 @@ + 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', + ) + ); \ No newline at end of file diff --git a/plugins/box/menu/languages/ru.lang.php b/plugins/box/menu/languages/ru.lang.php new file mode 100644 index 0000000..565651f --- /dev/null +++ b/plugins/box/menu/languages/ru.lang.php @@ -0,0 +1,24 @@ + 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' => 'Выбрать страницу', + ) + ); \ No newline at end of file diff --git a/plugins/box/menu/menu.admin.php b/plugins/box/menu/menu.admin.php new file mode 100644 index 0000000..8a91de8 --- /dev/null +++ b/plugins/box/menu/menu.admin.php @@ -0,0 +1,198 @@ + + function addMenuPage(slug, title) { + $('input[name=menu_item_link]').val(slug); + $('input[name=menu_item_name]').val(title); + $('#addMenuPageModal').modal('hide'); + } + + "); + } + + 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; + } + + } \ No newline at end of file diff --git a/plugins/box/menu/menu.plugin.php b/plugins/box/menu/menu.plugin.php new file mode 100644 index 0000000..2452e3b --- /dev/null +++ b/plugins/box/menu/menu.plugin.php @@ -0,0 +1,53 @@ +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(); + + } + + } \ No newline at end of file diff --git a/plugins/box/menu/views/backend/add.view.php b/plugins/box/menu/views/backend/add.view.php new file mode 100644 index 0000000..fdd499b --- /dev/null +++ b/plugins/box/menu/views/backend/add.view.php @@ -0,0 +1,62 @@ +

    +
    + + + + + + + +

    + + 'span6'.$error_class)); + + if (isset($errors['menu_item_name_empty'])) echo Html::nbsp(4).''.$errors['menu_item_name_empty'].''; + + echo ( + Form::label('menu_item_link', __('Item link', 'menu')). + Form::input('menu_item_link', $menu_item_link, array('class' => 'span6')) + ); +?> + + 'btn')). + Form::close() + ); +?> + + \ No newline at end of file diff --git a/plugins/box/menu/views/backend/edit.view.php b/plugins/box/menu/views/backend/edit.view.php new file mode 100644 index 0000000..e98cdde --- /dev/null +++ b/plugins/box/menu/views/backend/edit.view.php @@ -0,0 +1,62 @@ +

    +
    + + + + + + + +

    + + 'span6'.$error_class)); + + if (isset($errors['menu_item_name_empty'])) echo Html::nbsp(4).''.$errors['menu_item_name_empty'].''; + + echo ( + Form::label('menu_item_link', __('Item link', 'menu')). + Form::input('menu_item_link', $menu_item_link, array('class' => 'span6')) + ); +?> + + 'btn')). + Form::close() + ); +?> + + \ No newline at end of file diff --git a/plugins/box/menu/views/backend/index.view.php b/plugins/box/menu/views/backend/index.view.php new file mode 100644 index 0000000..bb3d987 --- /dev/null +++ b/plugins/box/menu/views/backend/index.view.php @@ -0,0 +1,51 @@ +

    +
    + + __('Create new page', 'menu'), 'class' => 'btn btn-small')) + ); +?> + +

    + + + + + + + + + + + + + + + + + + + +
    + + + + + 'btn btn-actions')); ?> + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete item :name', 'menu', array(':name' => $item['name']))."')")); + ?> +
    \ No newline at end of file diff --git a/plugins/box/menu/views/frontend/index.view.php b/plugins/box/menu/views/frontend/index.view.php new file mode 100644 index 0000000..838a1c0 --- /dev/null +++ b/plugins/box/menu/views/frontend/index.view.php @@ -0,0 +1,52 @@ + 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 ''.''.$item['name'].''.''; + + $anchor_active = ''; + $li_active = ''; + $target = ''; + } + } \ No newline at end of file diff --git a/plugins/box/pages/install/pages.manifest.xml b/plugins/box/pages/install/pages.manifest.xml new file mode 100644 index 0000000..b9fdaf3 --- /dev/null +++ b/plugins/box/pages/install/pages.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/pages/pages.plugin.php + active + 1 + Pages + Pages managment plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/pages/languages/en.lang.php b/plugins/box/pages/languages/en.lang.php new file mode 100644 index 0000000..5f1c9b1 --- /dev/null +++ b/plugins/box/pages/languages/en.lang.php @@ -0,0 +1,47 @@ + 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 :page have been saved.' => 'Your changes to the page :page have been saved.', + 'The page :page cloned.' => 'The page :page cloned.', + 'Status' => 'Status', + 'Actions' => 'Actions', + 'Add' => 'Add', + 'Published' => 'Published', + 'Draft' => 'Draft', + 'Published on' => 'Published on', + 'Edit 404 page' => 'Edit 404 page', + 'Page :page deleted' => 'Page :page deleted', + 'Search Engines Robots' => 'Search Engines Robots', + ) + ); \ No newline at end of file diff --git a/plugins/box/pages/languages/ru.lang.php b/plugins/box/pages/languages/ru.lang.php new file mode 100644 index 0000000..b0819cb --- /dev/null +++ b/plugins/box/pages/languages/ru.lang.php @@ -0,0 +1,47 @@ + 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 :page have been saved.' => 'Ваши изменения к странице :page были сохранены.', + 'The page :page cloned.' => 'Страница :page клонирована.', + 'Status' => 'Статус', + 'Actions' => 'Действия', + 'Add' => 'Добавить', + 'Published' => 'Опубликовано', + 'Draft' => 'Черновик', + 'Published on' => 'Опубликовано', + 'Edit 404 page' => 'Редактировать страницу 404', + 'Page :page deleted' => 'Страница :page удалена', + 'Search Engines Robots' => 'Поисковые роботы', + ), + ); \ No newline at end of file diff --git a/plugins/box/pages/pages.admin.php b/plugins/box/pages/pages.admin.php new file mode 100644 index 0000000..7d80ebd --- /dev/null +++ b/plugins/box/pages/pages.admin.php @@ -0,0 +1,499 @@ +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 :page 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 :page 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 :page 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 :page 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 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 :page 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(); + } + + } + } \ No newline at end of file diff --git a/plugins/box/pages/pages.plugin.php b/plugins/box/pages/pages.plugin.php new file mode 100644 index 0000000..8ce6f92 --- /dev/null +++ b/plugins/box/pages/pages.plugin.php @@ -0,0 +1,392 @@ +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 + * + * + * echo Page::title(); + * + * + * @return string + */ + public static function title() { + return Pages::$page['title']; + } + + + /** + * Get pages Description + * + * + * echo Page::description(); + * + * + * @return string + */ + public static function description() { + return Pages::$page['description']; + } + + + /** + * Get pages Keywords + * + * + * echo Page::keywords(); + * + * + * @return string + */ + public static function keywords() { + return Pages::$page['keywords']; + } + + } + + + class Page extends Pages { + + + /** + * Get date of current page + * + * + * echo Page::date(); + * + * + * @return string + */ + public static function date() { + return Date::format(Pages::$page['date'], 'Y-m-d'); + } + + + /** + * Get author of current page + * + * + * echo Page::author(); + * + * + * @return string + */ + public static function author() { + return Pages::$page['author']; + } + + + /** + * Get children pages for a specific parent page + * + * + * $pages = Page::children('page'); + * + * + * @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. + * + * + * echo Page::available(); + * + * + */ + 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 + * + * + * echo Page::breadcrumbs(); + * + * + */ + 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 + * + * + * echo Page::url(); + * + * + */ + public static function url() { + return Option::get('siteurl').Pages::$page['slug']; + } + + + /** + * Get page slug + * + * + * echo Page::slug(); + * + * + */ + public static function slug() { + return Pages::$page['slug']; + } + + + /** + * Get page meta robots + * + * + * echo Page::robots(); + * + * + */ + public static function robots() { + return (Pages::$page !== null) ? Pages::$page['robots_index'].', '.Pages::$page['robots_follow'] : ''; + } + + } \ No newline at end of file diff --git a/plugins/box/pages/views/backend/add.view.php b/plugins/box/pages/views/backend/add.view.php new file mode 100644 index 0000000..f5a4519 --- /dev/null +++ b/plugins/box/pages/views/backend/add.view.php @@ -0,0 +1,133 @@ +
    + +
    + +

    +
    + + + + + + + 'form-horizontal')) + ); + ?> + + + + + + 'span6')) + ); + + if (isset($errors['pages_empty_name'])) echo Html::nbsp(3).''.$errors['pages_empty_name'].''; + if (isset($errors['pages_exists'])) echo Html::nbsp(3).''.$errors['pages_exists'].''; + ?> + + + + + 'span6')) + ); + if (isset($errors['pages_empty_title'])) echo Html::nbsp(3).''.$errors['pages_empty_title'].''; + ?> + + + 'span8')). + Html::br(2). + Form::label('page_keywords', __('Keywords', 'pages')). + Form::input('page_keywords', $post_keywords, array('class' => 'span8')) + ); + ?> + +

    + + + +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    + +
    +
    + 'input-mini')). ' ' . + Form::input('month', $date[1], array('class' => 'input-mini')). ' ' . + Form::input('day', $date[2], array('class' => 'input-mini')). ' @ '. + Form::input('minute', $date[3], array('class' => 'input-mini')). ' : '. + Form::input('second', $date[4], array('class' => 'input-mini')) + ); + ?> +
    +
    + +
    +
    + +
    + + 'btn')).Html::nbsp(2). + Form::submit('add_page', __('Save', 'pages'), array('class' => 'btn')). + Form::close() + ); + ?> + +
    +
    \ No newline at end of file diff --git a/plugins/box/pages/views/backend/edit.view.php b/plugins/box/pages/views/backend/edit.view.php new file mode 100644 index 0000000..8b88b38 --- /dev/null +++ b/plugins/box/pages/views/backend/edit.view.php @@ -0,0 +1,171 @@ +
    + +
    + +

    + +

    + +
    + + + + + + + + 'form-horizontal')) + ); + ?> + + + + + + 'span6')) + ); + } + + if (isset($errors['pages_empty_name'])) echo Html::nbsp(3).''.$errors['pages_empty_name'].''; + if (isset($errors['pages_exists'])) echo Html::nbsp(3).''.$errors['pages_exists'].''; + ?> + + + + + 'span6')) + ); + if (isset($errors['pages_empty_title'])) echo Html::nbsp(3).''.$errors['pages_empty_title'].''; + ?> + + + 'span8')). + Html::br(2). + Form::label('page_keywords', __('Keywords', 'pages')). + Form::input('page_keywords', $keywords_to_edit, array('class' => 'span8')). + Form::hidden('old_parent', $page['parent']). + Form::hidden('page_id', $page['id']) + ); + ?> + +

    + + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    +
    + 'input-mini')). ' ' . + Form::input('month', $date[1], array('class' => 'input-mini')). ' ' . + Form::input('day', $date[2], array('class' => 'input-mini')). ' @ '. + Form::input('minute', $date[3], array('class' => 'input-mini')). ' : '. + Form::input('second', $date[4], array('class' => 'input-mini')) + ); + ?> +
    +
    + +
    +
    + +
    + + 'btn')).Html::nbsp(2). + Form::submit('edit_page', __('Save', 'pages'), array('class' => 'btn')). + Form::close() + ); + ?> + +
    +
    \ No newline at end of file diff --git a/plugins/box/pages/views/backend/index.view.php b/plugins/box/pages/views/backend/index.view.php new file mode 100644 index 0000000..9a2c77b --- /dev/null +++ b/plugins/box/pages/views/backend/index.view.php @@ -0,0 +1,91 @@ +
    + +
    + +

    +
    + + + + + + __('Create new page', 'pages'), 'class' => 'btn default btn-small')). Html::nbsp(3). + Html::anchor(__('Edit 404 page', 'pages'), 'index.php?id=pages&action=edit_page&name=error404', array('title' => __('Create new page', 'pages'), 'class' => 'btn default btn-small')) + ); + ?> + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + '_blank')); ?> + + + + + + + +
    +
    + 'btn btn-actions')); ?> + + + 'btn btn-actions btn-actions-default', 'onclick' => "return confirmDelete('".__("Delete page: :page", 'pages', array(':page' => Html::toText($page['title'])))."')")); + ?> +
    +
    +
    + +
    +
    \ No newline at end of file diff --git a/plugins/box/pages/views/frontend/available_pages.view.php b/plugins/box/pages/views/frontend/available_pages.view.php new file mode 100644 index 0000000..b904a0b --- /dev/null +++ b/plugins/box/pages/views/frontend/available_pages.view.php @@ -0,0 +1,5 @@ +
      + +
    • + +
    \ No newline at end of file diff --git a/plugins/box/pages/views/frontend/breadcrumbs.view.php b/plugins/box/pages/views/frontend/breadcrumbs.view.php new file mode 100644 index 0000000..998d2ae --- /dev/null +++ b/plugins/box/pages/views/frontend/breadcrumbs.view.php @@ -0,0 +1,5 @@ + +    + + + \ No newline at end of file diff --git a/plugins/box/plugins/install/plugins.manifest.xml b/plugins/box/plugins/install/plugins.manifest.xml new file mode 100644 index 0000000..3f87e58 --- /dev/null +++ b/plugins/box/plugins/install/plugins.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/plugins/plugins.plugin.php + active + 2 + Plugins + Plugins manager plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/plugins/languages/en.lang.php b/plugins/box/plugins/languages/en.lang.php new file mode 100644 index 0000000..804a02f --- /dev/null +++ b/plugins/box/plugins/languages/en.lang.php @@ -0,0 +1,20 @@ + array( + 'Plugins' => 'Plugins', + 'Name' => 'Name', + 'Actions' => 'Actions', + 'Description' => 'Description', + 'Installed' => 'Installed', + 'Install New' => 'Install New', + 'Delete' => 'Delete', + 'Delete plugin :plugin' => 'Delete plugin :plugin', + 'This plugins does not exist' => 'This plugins does not exist', + 'Version' => 'Version', + 'Author' => 'Author', + 'Get More Plugins' => 'Get More Plugins', + 'Install' => 'Install', + 'Uninstall' => 'Uninstall', + ) + ); \ No newline at end of file diff --git a/plugins/box/plugins/languages/ru.lang.php b/plugins/box/plugins/languages/ru.lang.php new file mode 100644 index 0000000..a0cd8c7 --- /dev/null +++ b/plugins/box/plugins/languages/ru.lang.php @@ -0,0 +1,20 @@ + array( + 'Plugins' => 'Плагины', + 'Installed' => 'Установленные', + 'Install New' => 'Установить новые', + 'Actions' => 'Действия', + 'Name' => 'Название', + 'Description' => 'Описание', + 'Delete' => 'Удалить', + 'Delete plugin :plugin' => 'Удалить плагин :plugin', + 'This plugins does not exist' => 'Такой плагин не существует', + 'Version' => 'Версия', + 'Author' => 'Автор', + 'Get More Plugins' => 'Скачать другие плагины', + 'Install' => 'Установить', + 'Uninstall' => 'Удалить', + ) + ); \ No newline at end of file diff --git a/plugins/box/plugins/plugins.admin.php b/plugins/box/plugins/plugins.admin.php new file mode 100644 index 0000000..fb44006 --- /dev/null +++ b/plugins/box/plugins/plugins.admin.php @@ -0,0 +1,127 @@ +deleteWhere('[name="'.Request::get('delete_plugin').'"]'); + + Request::redirect('index.php?id=plugins'); + } + } + + + // Install new plugin + // ------------------------------------- + if (Request::get('install')) { + + // Load plugin install xml file + $plugin_xml = XML::loadFile(PLUGINS . DS . basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . Request::get('install')); + + // Add plugin to plugins table + $plugins->insert(array('name' => basename(Request::get('install'), '.manifest.xml'), + 'location' => (string)$plugin_xml->plugin_location, + 'status' => (string)$plugin_xml->plugin_status, + 'priority' => (int)$plugin_xml->plugin_priority)); + + // Clean i18n cache + Cache::clean('i18n'); + + // Run plugin installer file + $plugin_name = str_replace(array("Plugin", ".manifest.xml"), "", Request::get('install')); + if (File::exists(PLUGINS . DS .basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS .$plugin_name . '.install.php')) { + include PLUGINS . DS . basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . $plugin_name . '.install.php'; + } + + Request::redirect('index.php?id=plugins'); + } + + + // Delete plugin from server + // ------------------------------------- + if (Request::get('delete_plugin_from_server')) { + Dir::delete(PLUGINS . DS . basename(Request::get('delete_plugin_from_server'), '.manifest.xml')); + Request::redirect('index.php?id=plugins'); + } + + + // Installed plugins + $plugins_installed = array(); + + // New plugins + $plugins_new = array(); + + // Plugins to install + $plugins_to_intall = array(); + + // Scan plugins directory for .manifest.xml + $plugins_new = File::scan(PLUGINS, '.manifest.xml'); + + // Get installed plugins from plugins table + $plugins_installed = $plugins->select(null, 'all', null, array('location', 'priority'), 'priority', 'ASC'); + + // Update $plugins_installed array. extract plugins names + foreach ($plugins_installed as $plg) { + $_plg[] = basename($plg['location'], 'plugin.php').'manifest.xml'; + } + + // Diff + $plugins_to_install = array_diff($plugins_new, $_plg); + + // Create array of plugins to install + $count = 0; + foreach ($plugins_to_install as $plugin) { + $plg_path = PLUGINS . DS . Text::lowercase(basename($plugin, '.manifest.xml')) . DS . 'install' . DS . $plugin; + if (file_exists($plg_path)) { + $plugins_to_intall[$count]['path'] = $plg_path; + $plugins_to_intall[$count]['plugin'] = $plugin; + $count++; + } + } + + // Draw template + View::factory('box/plugins/views/backend/index') + ->assign('installed_plugins', $installed_plugins) + ->assign('plugins_to_intall', $plugins_to_intall) + ->assign('_users_plugins', $_users_plugins) + ->display(); + } + } \ No newline at end of file diff --git a/plugins/box/plugins/plugins.plugin.php b/plugins/box/plugins/plugins.plugin.php new file mode 100644 index 0000000..6a7d03f --- /dev/null +++ b/plugins/box/plugins/plugins.plugin.php @@ -0,0 +1,31 @@ + +
    + + +
    + + + + + +
    + +
    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete plugin :plugin', 'plugins', array(':plugin' => $plugin['id']))."')")); + ?> +
    +
    + + +
    + + + + + + + + + + + + + + + + + + + + + + +
    + plugin_name; ?> + + plugin_description; ?> + + plugin_author; ?> + + plugin_version; ?> + + 'btn btn-actions')); ?> + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete plugin :plugin', 'plugins', array(':plugin' => Text::lowercase(basename($plug['path'],'.manifest.xml'))) )."')")); + ?> +
    +
    + + +
    + +
    \ No newline at end of file diff --git a/plugins/box/sitemap/install/sitemap.manifest.xml b/plugins/box/sitemap/install/sitemap.manifest.xml new file mode 100644 index 0000000..afb0338 --- /dev/null +++ b/plugins/box/sitemap/install/sitemap.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/sitemap/sitemap.plugin.php + active + 10 + Sitemap + Show sitemap + 1.0.0 + Awilum + http://awilum.webdevart.ru/ + \ No newline at end of file diff --git a/plugins/box/sitemap/languages/en.lang.php b/plugins/box/sitemap/languages/en.lang.php new file mode 100644 index 0000000..75e369d --- /dev/null +++ b/plugins/box/sitemap/languages/en.lang.php @@ -0,0 +1,7 @@ + array( + 'Sitemap' => 'Sitemap', + ) + ); \ No newline at end of file diff --git a/plugins/box/sitemap/languages/ru.lang.php b/plugins/box/sitemap/languages/ru.lang.php new file mode 100644 index 0000000..eda9c64 --- /dev/null +++ b/plugins/box/sitemap/languages/ru.lang.php @@ -0,0 +1,7 @@ + array( + 'Sitemap' => 'Карта сайта', + ) + ); \ No newline at end of file diff --git a/plugins/box/sitemap/sitemap.plugin.php b/plugins/box/sitemap/sitemap.plugin.php new file mode 100644 index 0000000..55d3b94 --- /dev/null +++ b/plugins/box/sitemap/sitemap.plugin.php @@ -0,0 +1,160 @@ +select('[slug!="error404" and status="published"]'); + + $pages_array = array(); + + $count = 0; + + foreach ($pages_list as $page) { + + $pages_array[$count]['title'] = Html::toText($page['title']); + $pages_array[$count]['parent'] = $page['parent']; + $pages_array[$count]['date'] = $page['date']; + $pages_array[$count]['author'] = $page['author']; + $pages_array[$count]['slug'] = $page['slug']; + + if (isset($page['parent'])) { + $c_p = $page['parent']; + } else { + $c_p = ''; + } + + if ($c_p != '') { + $_page = $pages->select('[slug="'.$page['parent'].'"]', null); + + if (isset($_page['title'])) { + $_title = $_page['title']; + } else { + $_title = ''; + } + $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; + } else { + $pages_array[$count]['sort'] = $page['title']; + } + $_title = ''; + $count++; + } + + // Sort pages + $_pages_list = Arr::subvalSort($pages_array, 'sort'); + + // Display view + return View::factory('box/sitemap/views/frontend/index') + ->assign('pages_list', $_pages_list) + ->assign('components', Sitemap::getComponents()) + ->render(); + } + + + /** + * Create sitemap + */ + public static function create() { + + // Get pages table + $pages = new Table('pages'); + + // Get pages list + $pages_list = $pages->select('[slug!="error404" and status="published"]'); + + // Create sitemap content + $map = ''."\n"; + $map .= ''."\n"; + foreach ($pages_list as $page) { + if ($page['parent'] != '') { $parent = $page['parent'].'/'; } else { $parent = ''; } + $map .= "\t".''."\n\t\t".''.Option::get('siteurl').$parent.$page['slug'].''."\n\t\t".''.date("Y-m-d", (int)$page['date']).''."\n\t\t".'weekly'."\n\t\t".'1.0'."\n\t".''."\n"; + } + + // Get list of components + $components = Sitemap::getComponents(); + + // Add components to sitemap + if (count($components) > 0) { + foreach ($components as $component) { + $map .= "\t".''."\n\t\t".''.Option::get('siteurl').Text::lowercase($component).''."\n\t\t".''.date("Y-m-d", time()).''."\n\t\t".'weekly'."\n\t\t".'1.0'."\n\t".''."\n"; + } + } + + // Close sitemap + $map .= ''; + + // Save sitemap + return File::setContent(ROOT . DS . 'sitemap.xml', $map); + } + + + /** + * 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; + } + + } \ No newline at end of file diff --git a/plugins/box/sitemap/views/frontend/index.view.php b/plugins/box/sitemap/views/frontend/index.view.php new file mode 100644 index 0000000..a03a0a5 --- /dev/null +++ b/plugins/box/sitemap/views/frontend/index.view.php @@ -0,0 +1,28 @@ +

    +
    +
      + 0) { + foreach ($pages_list as $page) { + if (trim($page['parent']) !== '') $parent = $page['parent'].'/'; else $parent = ''; + if (trim($page['parent']) !== '') { echo ''; } + } + if (count($components) == 0) { echo '
        '; } + } + + // Display components + if (count($components) > 0) { + if (count($pages_list) == 0) { echo ''; + + } + +?> +
      diff --git a/plugins/box/snippets/install/snippets.manifest.xml b/plugins/box/snippets/install/snippets.manifest.xml new file mode 100644 index 0000000..aa1bacb --- /dev/null +++ b/plugins/box/snippets/install/snippets.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/snippets/snippets.plugin.php + active + 6 + Snippets + Snippets manager plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/snippets/languages/en.lang.php b/plugins/box/snippets/languages/en.lang.php new file mode 100644 index 0000000..052d1c7 --- /dev/null +++ b/plugins/box/snippets/languages/en.lang.php @@ -0,0 +1,25 @@ + array( + 'Snippets' => 'Snippets', + 'Snippets manager' => 'Snippets manager', + 'Actions' => 'Actions', + 'Delete' => 'Delete', + 'Edit' => 'Edit', + 'Name' => 'Name', + 'Create new snippet' => 'Create new snippet', + 'New snippet' => 'New snippet', + 'Edit snippet' => 'Edit snippet', + 'Save' => 'Save', + 'Save and exit' => 'Save and exit', + 'This field should not be empty' => 'This field should not be empty', + 'This snippet already exists' => 'This snippet already exists', + 'This snippet does not exist' => 'This snippet does not exist', + 'Delete snippet: :snippet' => 'Delete snippet: :snippet', + 'Snippet content' => 'Snippet content', + 'Snippet :name deleted' => 'Snippet :name deleted', + 'Your changes to the snippet :name have been saved.' => 'Your changes to the snippet :name have been saved.', + 'Delete snippet: :snippet' => 'Delete snippet: :snippet', + ) + ); \ No newline at end of file diff --git a/plugins/box/snippets/languages/ru.lang.php b/plugins/box/snippets/languages/ru.lang.php new file mode 100644 index 0000000..6706a4f --- /dev/null +++ b/plugins/box/snippets/languages/ru.lang.php @@ -0,0 +1,25 @@ + array( + 'Snippets' => 'Сниппеты', + 'Snippets manager' => 'Менеджер сниппетов', + 'Actions' => 'Действия', + 'Delete' => 'Удалить', + 'Edit' => 'Редактировать', + 'New snippet' => 'Новый сниппет', + 'Create new snippet' => 'Создать новый сниппет', + 'Name' => 'Название', + 'Edit snippet' => 'Редактирование сниппета', + 'Save' => 'Сохранить', + 'Save and exit' => 'Сохранить и выйти', + 'This field should not be empty' => 'Это поле не должно быть пустым', + 'This snippet already exists' => 'Такой сниппет уже существует', + 'This snippet does not exist' => 'Такого сниппета не существует', + 'Delete snippet: :block' => 'Удалить сниппет: :snippet', + 'Snippet content' => 'Содержимое сниппета', + 'Snippet :name deleted' => 'Сниппет :name удален', + 'Your changes to the snippet :name have been saved.' => 'Ваши изменения к сниппету :name были сохранены.', + 'Delete snippet: :snippet' => 'Удалить сниппет: :snippet', + ) + ); \ No newline at end of file diff --git a/plugins/box/snippets/snippets.admin.php b/plugins/box/snippets/snippets.admin.php new file mode 100644 index 0000000..0330a21 --- /dev/null +++ b/plugins/box/snippets/snippets.admin.php @@ -0,0 +1,135 @@ +:name have been saved.', 'snippets', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_snippets_and_exit')) { + Request::redirect('index.php?id=snippets'); + } else { + Request::redirect('index.php?id=snippets&action=edit_snippet&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('content')) $content = Request::post('content'); else $content = ''; + + // Display view + View::factory('box/snippets/views/backend/add') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->display(); + break; + + // Edit snippet + // ------------------------------------- + case "edit_snippet": + // Save current snippet action + if (Request::post('edit_snippets') || Request::post('edit_snippets_and_exit') ) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['snippets_empty_name'] = __('This field should not be empty', 'snippets'); + if ((file_exists($snippets_path.Security::safeName(Request::post('name')).'.snippet.php')) and (Security::safeName(Request::post('snippets_old_name')) !== Security::safeName(Request::post('name')))) $errors['snippets_exists'] = __('This snippet already exists', 'snippets'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $snippet_old_filename = $snippets_path.Request::post('snippets_old_name').'.snippet.php'; + $snippet_new_filename = $snippets_path.Security::safeName(Request::post('name')).'.snippet.php'; + if ( ! empty($snippet_old_filename)) { + if ($snippet_old_filename !== $snippet_new_filename) { + rename($snippet_old_filename, $snippet_new_filename); + $save_filename = $snippet_new_filename; + } else { + $save_filename = $snippet_new_filename; + } + } else { + $save_filename = $snippet_new_filename; + } + + // Save snippet + File::setContent($save_filename, Request::post('content')); + + Notification::set('success', __('Your changes to the snippet :name have been saved.', 'snippets', array(':name' => basename($save_filename, '.snippet.php')))); + + if (Request::post('edit_snippets_and_exit')) { + Request::redirect('index.php?id=snippets'); + } else { + Request::redirect('index.php?id=snippets&action=edit_snippet&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')); + $content = File::getContent($snippets_path.Request::get('filename').'.snippet.php'); + + // Display view + View::factory('box/snippets/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->display(); + break; + case "delete_snippet": + File::delete($snippets_path.Request::get('filename').'.snippet.php'); + Notification::set('success', __('Snippet :name deleted', 'snippets', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=snippets'); + break; + } + } else { + + // Get snippets + $snippets_list = File::scan($snippets_path, '.snippet.php'); + + // Display view + View::factory('box/snippets/views/backend/index') + ->assign('snippets_list', $snippets_list) + ->display(); + + } + } + + } \ No newline at end of file diff --git a/plugins/box/snippets/snippets.plugin.php b/plugins/box/snippets/snippets.plugin.php new file mode 100644 index 0000000..a242835 --- /dev/null +++ b/plugins/box/snippets/snippets.plugin.php @@ -0,0 +1,73 @@ + $name)); + } + + + /** + * Returns snippet content for shortcode {snippet get="snippetname"} + * + * @param array $attributes snippet filename + */ + public static function _content($attributes) { + + if (isset($attributes['get'])) $name = (string)$attributes['get']; else $name = ''; + + $snippet_path = STORAGE . DS . 'snippets' . DS . $name . '.snippet.php'; + + if (File::exists($snippet_path)) { + ob_start(); + include $snippet_path; + $snippet_contents = ob_get_contents(); + ob_end_clean(); + return $snippet_contents; + } else { + if (Session::exists('admin') && Session::get('admin') == true) { + return __('Snippet :name is not found!', 'snippets', array(':name' => $name)); + } + } + } + } \ No newline at end of file diff --git a/plugins/box/snippets/views/backend/add.view.php b/plugins/box/snippets/views/backend/add.view.php new file mode 100644 index 0000000..eab440f --- /dev/null +++ b/plugins/box/snippets/views/backend/add.view.php @@ -0,0 +1,36 @@ +

      +
      + + + + + + + 'form-horizontal'))); ?> + + + + + + +
      + 'input-xlarge'))); ?>.snippet.php +
      + + '.$errors['snippets_empty_name'].''; + if (isset($errors['snippets_exists'])) echo '   '.$errors['snippets_exists'].''; + ?> + + 'width:100%;height:400px;', 'class'=>'source-editor')). + Html::br(2). + Form::submit('add_snippets_and_exit', __('Save and exit', 'snippets'), array('class' => 'btn')).Html::nbsp(2). + Form::submit('add_snippets', __('Save', 'snippets'), array('class' => 'btn')). + Form::close() + ); + +?> diff --git a/plugins/box/snippets/views/backend/edit.view.php b/plugins/box/snippets/views/backend/edit.view.php new file mode 100644 index 0000000..5cd8415 --- /dev/null +++ b/plugins/box/snippets/views/backend/edit.view.php @@ -0,0 +1,46 @@ +

      +
      + + + + 'form-horizontal'))); + + echo (Form::hidden('csrf', Security::token())); + + echo (Form::hidden('snippets_old_name', Request::get('filename'))); + +?> + + + + +
      + 'input-xlarge'))); ?>.snippet.php +
      + + '.$errors['snippets_empty_name'].''; + if (isset($errors['snippets_exists'])) echo '   '.$errors['snippets_exists'].''; + ?> + + 'width:100%;height:400px;', 'class' => 'source-editor')). + Html::br(2). + Form::submit('edit_snippets_and_exit', __('Save and exit', 'snippets'), array('class' => 'btn default')).Html::nbsp(2). + Form::submit('edit_snippets', __('Save', 'snippets'), array('class' => 'btn default')). Html::nbsp(). + Form::close() + ); + + } else { + echo '
      '.__('This snippet does not exist').'
      '; + } +?> \ No newline at end of file diff --git a/plugins/box/snippets/views/backend/index.view.php b/plugins/box/snippets/views/backend/index.view.php new file mode 100644 index 0000000..c5da2be --- /dev/null +++ b/plugins/box/snippets/views/backend/index.view.php @@ -0,0 +1,34 @@ +

      +
      + + + + __('Create new snippet', 'snippets'), 'class' => 'btn default btn-small')). Html::nbsp(3) + ); +?> + +

      + + + + + + + + + + + + + + +
      + 'btn btn-actions')); ?> + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete snippet: :snippet', 'snippets', array(':snippet' => basename($snippet, '.snippet.php')))."')")); + ?> +
      + \ No newline at end of file diff --git a/plugins/box/system/install/system.manifest.xml b/plugins/box/system/install/system.manifest.xml new file mode 100644 index 0000000..36aa859 --- /dev/null +++ b/plugins/box/system/install/system.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/system/system.plugin.php + active + 4 + System + Monstra System plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/system/languages/en.lang.php b/plugins/box/system/languages/en.lang.php new file mode 100644 index 0000000..d76496e --- /dev/null +++ b/plugins/box/system/languages/en.lang.php @@ -0,0 +1,79 @@ + array( + 'System' => 'System', + 'Published a new version of the :monstra' => 'Published a new version of the :monstra', + 'Sitemap created' => 'Sitemap created', + 'Create sitemap' => 'Create sitemap', + 'on' => 'on', + 'off'=> 'off', + 'Site url' => 'Site url', + 'Maintenance Mode' => 'Maintenance Mode', + 'Maintenance Mode On' => 'Maintenance Mode On', + 'Maintenance Mode Off' => 'Maintenance Mode Off', + 'Site settings' => 'Site settings', + 'System settings' => 'System settings', + 'Site name' => 'Site name', + 'Site description' => 'Site description', + 'Site keywords' => 'Site keywords', + 'Site slogan' => 'Site slogan', + 'Default page' => 'Default page', + 'Time zone' => 'Time zone', + 'Language' => 'Language', + 'Save' => 'Save', + 'Site' => 'Site', + 'System version' => 'System version', + 'System version ID' => 'System version ID', + 'GZIP' => 'GZIP', + 'Debugging' => 'Debugging', + 'Plugin API' => 'Plugin API', + 'Plugins active' => 'Plugins active', + 'Actions registered' => 'Actions registered', + 'Filters registered' => 'Filters registered', + 'logout' => 'logout', + 'site' => 'site', + 'Core' => 'Core', + 'Delete temporary files' => 'Delete temporary files', + 'Download the latest version' => 'Download the latest version', + 'Powered by' => 'Powered by', + 'Administration' => 'Administration', + 'Settings' => 'Settings', + 'Temporary files deleted' => 'Temporary files deleted', + 'Extends' => 'Extends', + 'View site' => 'View site', + 'Welcome, :username' => 'Welcome, :username', + 'Reset Password' => 'Reset Password', + '< Back to Website' => '< Back to Website', + 'Forgot your password? >' => 'Forgot your password? >', + 'Administration >' => 'Administration >', + 'Send New Password' => 'Send New Password', + 'This user does not exist' => 'This user does not exist', + 'Version' => 'Version', + + 'Install script writable' => 'Install script writable', + 'Install script not writable' => 'Install script not writable', + 'Directory: :dir writable' => 'Directory: :dir writable', + 'Directory: :dir not writable' => 'Directory: :dir not writable', + 'PHP Version' => 'PHP Version', + 'Module DOM is installed' => 'Module DOM is installed', + 'Module DOM is required' => 'Module DOM is required', + 'Module Mod Rewrite is installed' => 'Module Mod Rewrite is installed', + 'Module SimpleXML is installed' => 'Module SimpleXML is installed', + 'PHP 5.2 or greater is required' => 'PHP 5.2 or greater is required', + 'Apache Mod Rewrite is required' => 'Apache Mod Rewrite is required', + 'SimpleXML module is required' => 'SimpleXML module is required', + 'Field "Site name" is empty' => 'Field "Site name" is empty', + 'Field "Email" is empty' => 'Field "Email" is empty', + 'Field "Username" is empty' => 'Field "Username" is empty', + 'Field "Password" is empty' => 'Field "Password" is empty', + 'Field "Site url" is empty' => 'Field "Site url" is empty', + 'Email not valid' => 'Email not valid', + 'Install' => 'Install', + '...Monstra says...' => '...Monstra says...', + 'Sitemap file writable' => 'Sitemap file writable', + 'Sitemap file not writable' => 'Sitemap file not writable', + 'Main .htaccess file writable' => 'Main .htaccess file writable', + 'Main .htaccess file not writable' => 'Main .htaccess file not writable', + ) + ); \ No newline at end of file diff --git a/plugins/box/system/languages/ru.lang.php b/plugins/box/system/languages/ru.lang.php new file mode 100644 index 0000000..b2c8bd3 --- /dev/null +++ b/plugins/box/system/languages/ru.lang.php @@ -0,0 +1,80 @@ + array( + 'System' => 'Система', + 'Published a new version of the :monstra' => 'Опубликована новая версия :monstra', + 'Sitemap created' => 'Карта сайта создана', + 'Create sitemap' => 'Создать карту сайта', + 'on' => 'включен', + 'off'=> 'выключен', + 'Site url' => 'Адрес сайта', + 'Maintenance Mode' => 'Техническое обслуживание', + 'Maintenance Mode On' => 'Поставить на тех.обслуживание', + 'Maintenance Mode Off' => 'Снять с тех.обслуживания', + 'Site settings' => 'Настройки сайта', + 'System settings' => 'Настройки системы', + 'Site name' => 'Название сайта', + 'Site description' => 'Описание сайта', + 'Site keywords' => 'Ключевые слова сайта', + 'Site slogan' => 'Слоган сайта', + 'Default page' => 'Страница по умолчанию', + 'Time zone' => 'Временная зона', + 'Language' => 'Язык', + 'Save' => 'Сохранить', + 'Site' => 'Сайт', + 'System version' => 'Версия системы ID', + 'System version ID' => 'Версия системы ID', + 'GZIP' => 'Cжатие GZIP', + 'Debugging' => 'Дебаггинг', + 'Plugin API' => 'Plugin API', + 'Plugins active' => 'Подключенные плагины', + 'Actions registered' => 'Зарегистрированные эыкшены', + 'Filters registered' => 'Скачать последнюю версию', + 'logout' => 'выход', + 'site' => 'Сайт', + 'Core' => 'Ядро', + 'Delete temporary files' => 'Удалить временные файлы', + 'Download the latest version' => 'Скачать последнюю версию', + 'Powered by' => 'Работает на', + 'Administration' => 'Администрирование', + 'Settings' => 'Настройки', + 'Temporary files deleted' => 'Временные файлы удалены', + 'Extends' => 'Расширения', + 'View site' => 'Сайт', + 'Welcome, :username' => 'Добро пожаловать, :username', + 'Reset Password' => 'Сброс пароля', + '< Back to Website' => '< Обратно на сайт', + 'Forgot your password? >' => 'Забыли пароль ? >', + 'Administration >' => 'Администрирование >', + 'Send New Password' => 'Выслать новый пароль', + 'This user does not exist' => 'Нет такого пользователя', + 'Version' => 'Версия', + + + 'Install script writable' => 'Установочный скрипт доступен для записи', + 'Install script not writable' => 'Установочный скрипт не доступен для записи', + 'Directory: :dir writable' => 'Директория :dir доступна для записи', + 'Directory: :dir not writable' => 'Директория :dir не доступна для записи', + 'PHP Version' => 'Версия PHP', + 'Module DOM is installed' => 'Модуль DOM установлен', + 'Module DOM is required' => 'Требуется DOM модуль', + 'Module Mod Rewrite is installed' => 'Модуль Mod Rewrite установлен', + 'Module SimpleXML is installed' => 'Модуль SimpleXML установлен', + 'PHP 5.2 or greater is required' => 'PHP 5.2 или высше', + 'Apache Mod Rewrite is required' => 'Требуется Apache Mod Rewrite', + 'SimpleXML module is required' => 'Требуется SimpleXML модуль', + 'Field "Site name" is empty' => 'Поле "Название сайта" пустое', + 'Field "Email" is empty' => 'Поле "Емейл" пустое', + 'Field "Username" is empty' => 'Поле "Имя пользователя" пустое', + 'Field "Password" is empty' => 'Поле "Пароль" пустое', + 'Field "Site url" is empty' => 'Поле "Адрес сайта" пустое', + 'Email not valid' => 'Емейл невалидный', + 'Install' => 'Установить', + '...Monstra says...' => '...Monstra говорит...', + 'Sitemap file writable' => 'Карта сайта доступна для записи', + 'Sitemap file not writable' => 'Карта сайта не доступна для записи', + 'Main .htaccess file writable' => 'Главный .htaccess файл доступен для записи', + 'Main .htaccess file not writable' => 'Главный .htaccess файл не доступен для записи', + ) + ); \ No newline at end of file diff --git a/plugins/box/system/system.admin.php b/plugins/box/system/system.admin.php new file mode 100644 index 0000000..26e5da1 --- /dev/null +++ b/plugins/box/system/system.admin.php @@ -0,0 +1,159 @@ + + $.getJSON("http://monstra.org/api/basic.php?jsoncallback=?", + function(data){ + var current_monstra_version_id = '.MONSTRA_VERSION_ID.'; + var api_monstra_version_id = data.version_id; + if (current_monstra_version_id < api_monstra_version_id) { + $("#update-monstra").addClass("alert").html("'.__("Published a new version of the :monstra", "system", array(":monstra" => "Monstra")).'"); + } + } + ); + + '); + } + + class SystemAdmin extends Backend { + + /** + * System plugin admin + */ + public static function main() { + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + + $filters = Filter::$filters; + $plugins = Plugin::$plugins; + $components = Plugin::$components; + $actions = Action::$actions; + + // Get pages table + $pages = new Table('pages'); + + + // Get system timezone + $system_timezone = Option::get('timezone'); + + + // Get languages files + $language_files = File::scan('../plugins/box/system/languages/', '.lang.php'); + foreach ($language_files as $language) { + $parts = explode('.', $language); + $l = $parts[0]; + $languages_array[$l] = $l; + } + + + // Get all pages + $pages_array = array(); + $pages_list = $pages->select('[slug!="error404" and parent=""]'); + foreach ($pages_list as $page) { + $pages_array[$page['slug']] = Html::toText($page['title']); + } + + + // Create Sitemap + // ------------------------------------- + if (Request::get('sitemap')) { + if ('create' == Request::get('sitemap')) { + Notification::set('success', __('Sitemap created', 'system')); + Sitemap::create(); + Request::redirect('index.php?id=system'); + } + } + + + // Delete temporary files + // ------------------------------------- + if (Request::get('temporary_files')) { + if ('delete' == Request::get('temporary_files')) { + + $namespaces = Dir::scan(CACHE); + if (count($namespaces) > 0) { + foreach ($namespaces as $namespace) { + Dir::delete(CACHE . DS . $namespace); + } + } + + $files = File::scan(MINIFY, array('css','js','php')); + if (count($files) > 0) { + foreach ($files as $file) { + File::delete(MINIFY . DS . $file); + } + } + + if (count(File::scan(MINIFY, array('css', 'js', 'php'))) == 0 && count(Dir::scan(CACHE)) == 0) { + Notification::set('success', __('Temporary files deleted', 'system')); + Request::redirect('index.php?id=system'); + } + } + } + + // Set maintenance state on or off + // ------------------------------------- + if (Request::get('maintenance')) { + if ('on' == Request::get('maintenance')) { + Option::update('maintenance_status', 'on'); + Request::redirect('index.php?id=system'); + } + if ('off' == Request::get('maintenance')) { + Option::update('maintenance_status', 'off'); + Request::redirect('index.php?id=system'); + } + } + + // Edit settings + // ------------------------------------- + if (Request::post('edit_settings')) { + + if (Security::check(Request::post('csrf'))) { + + // Add trailing slashes + $_site_url = Request::post('system_url'); + if ($_site_url[strlen($_site_url)-1] !== '/') { + $_site_url = $_site_url.'/'; + } + + Option::update(array('sitename' => Request::post('site_name'), + 'keywords' => Request::post('site_keywords'), + 'description' => Request::post('site_description'), + 'slogan' => Request::post('site_slogan'), + 'defaultpage' => Request::post('site_default_page'), + 'siteurl' => $_site_url, + 'timezone' => Request::post('system_timezone'), + 'language' => Request::post('system_language'), + 'maintenance_message' => Request::post('site_maintenance_message'))); + + Notification::set('success', __('Your changes have been saved.', 'system')); + Request::redirect('index.php?id=system'); + + } else { die('csrf detected!'); } + } + + // Its mean that you can add your own actions for this plugin + Action::run('admin_system_extra_actions'); + + // Display view + View::factory('box/system/views/backend/index') + ->assign('pages_array', $pages_array) + ->assign('languages_array', $languages_array) + ->display(); + + } else { + + Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); + } + } + } \ No newline at end of file diff --git a/plugins/box/system/system.plugin.php b/plugins/box/system/system.plugin.php new file mode 100644 index 0000000..68d7c72 --- /dev/null +++ b/plugins/box/system/system.plugin.php @@ -0,0 +1,43 @@ + Session::get('user_login'))), 'top', 'users&action=edit&user_id='.Session::get('user_id'), 1, Navigation::TOP, false); + Navigation::add(__('View site', 'system'), 'top', Option::get('siteurl'), 2, Navigation::TOP, true); + Navigation::add(__('Logout', 'users'), 'top', '&logout=do', 3, Navigation::TOP, false); + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + Navigation::add(__('Settings', 'system'), 'system', 'system', 1); + } + + } + + + Plugin::Admin('system', 'box'); + \ No newline at end of file diff --git a/plugins/box/system/views/backend/index.view.php b/plugins/box/system/views/backend/index.view.php new file mode 100644 index 0000000..0a4671c --- /dev/null +++ b/plugins/box/system/views/backend/index.view.php @@ -0,0 +1,58 @@ + + +
      + + + + 'btn')).Html::nbsp(2); ?> + 'btn')).Html::nbsp(2); ?> + + 'btn')); ?> + + 'btn btn-danger')); ?> + + + +
      + +

      +
      + 'span7')). Html::br(). + Form::label('site_description', __('Site description', 'system')). + Form::input('site_description', Option::get('description'), array('class' => 'span7')). Html::br(). + Form::label('site_keywords', __('Site keywords', 'system')). + Form::input('site_keywords', Option::get('keywords'), array('class' => 'span7')). Html::br(). + Form::label('site_slogan', __('Site slogan', 'system')). + Form::input('site_slogan', Option::get('slogan'), array('class' => 'span7')). Html::br(). + Form::label('site_default_page', __('Default page', 'system')). + Form::select('site_default_page', $pages_array, Option::get('defaultpage'), array('class' => 'span3')). Html::br(2) + ); +?> + +

      +
      + 'span7')). Html::br(). + Form::label('system_timezone', __('Time zone', 'system')). + Form::select('system_timezone', Date::timezones(), Option::get('timezone'), array('class' => 'span7')). Html::br(). + Form::label('system_language', __('Language', 'system')). + Form::select('system_language', $languages_array, Option::get('language'), array('class' => 'span2')). Html::br(). + Form::label('site_maintenance_message', __('Maintenance Mode', 'system')). + Form::textarea('site_maintenance_message', Html::toText(Option::get('maintenance_message')), array('style' => 'width:640px;height:160px;')). Html::br(2) + ); +?> + + 'btn')). + Form::close() + ); +?> + diff --git a/plugins/box/themes/install/themes.manifest.xml b/plugins/box/themes/install/themes.manifest.xml new file mode 100644 index 0000000..28d662f --- /dev/null +++ b/plugins/box/themes/install/themes.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/themes/themes.plugin.php + active + 3 + Themes + Themes managment plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/themes/languages/en.lang.php b/plugins/box/themes/languages/en.lang.php new file mode 100644 index 0000000..eced7e3 --- /dev/null +++ b/plugins/box/themes/languages/en.lang.php @@ -0,0 +1,49 @@ + array( + 'Themes' => 'Themes', + 'Themes manager' => 'Themes manager', + 'Select theme' => 'Select theme', + 'Save' => 'Save', + 'Save and exit' => 'Save and exit', + 'Name' => 'Name', + 'Create new template' => 'Create new template', + 'New template' => 'New template', + 'Delete template: :name' => 'Delete template: :name', + 'Delete chunk: :name' => 'Delete chunk: :name', + 'Delete styles: :name' => 'Delete styles: :name', + 'Templates' => 'Templates', + 'Clone' => 'Clone', + 'Edit' => 'Edit', + 'Delete' => 'Delete', + 'Actions' => 'Actions', + 'Create new chunk' => 'Create new chunk', + 'New chunk' => 'New chunk', + 'Chunks' => 'Chunks', + 'Create new styles' => 'Create new styles', + 'New styles' => 'New styles', + 'Styles' => 'Styles', + 'Template content' => 'Template content', + 'Styles content' => 'Styles content', + 'Chunk content' => 'Chunk content', + 'Edit template' => 'Edit template', + 'Edit chunk' => 'Edit chunk', + 'Edit styles' => 'Edit styles', + 'Current site theme' => 'Current site theme', + 'Current admin theme' => 'Current admin theme', + 'This template already exists' => 'This template already exists', + 'This chunk already exists' => 'This chunk already exists', + 'This styles already exists' => 'This styles already exists', + 'Components templates' => 'Components templates', + 'Your changes to the chunk :name have been saved.' => 'Your changes to the chunk :name have been saved.', + 'Your changes to the styles :name have been saved.' => 'Your changes to the styles :name have been saved.', + 'Your changes to the template :name have been saved.' => 'Your changes to the template :name have been saved.', + 'This field should not be empty' => 'This field should not be empty', + 'Scripts' => 'Scripts', + 'Create new script' => 'Create new script', + 'Script content' => 'Script content', + 'New script' => 'New script', + 'Edit script' => 'Edit script', + ) + ); \ No newline at end of file diff --git a/plugins/box/themes/languages/ru.lang.php b/plugins/box/themes/languages/ru.lang.php new file mode 100644 index 0000000..5a20ce4 --- /dev/null +++ b/plugins/box/themes/languages/ru.lang.php @@ -0,0 +1,51 @@ + array( + 'Themes' => 'Темы', + 'Themes manager' => 'Менеджер тем', + 'Select theme' => 'Выбрать тему', + 'Save' => 'Сохранить', + 'Name' => 'Название', + 'Save and exit' => 'Сохранить и выйти', + 'Create new template' => 'Создать новый шаблон', + 'New template' => 'Новый шаблон', + 'Delete template: :name' => 'Удалить шаблон: :name', + 'Delete chunk: :name' => 'Удалить чанк: :name', + 'Delete styles: :name' => 'Удалить стили: :name', + 'Templates' => 'Шаблоны', + 'Clone' => 'Клонировать', + 'Edit' => 'Редактировать', + 'Delete' => 'Удалить', + 'Actions' => 'Действия', + 'Create new chunk' => 'Создать новый чанк', + 'New chunk' => 'Новый чанк', + 'Chunks' => 'Чанки', + 'Create new styles' => 'Создать новые стили', + 'New styles' => 'Новые стили', + 'Styles' => 'Стили', + 'Template content' => 'Содержимое шаблона', + 'Styles content' => 'Содержимое стилей', + 'Chunk content' => 'Содержимое чанка', + 'Edit template' => 'Редактирование шаблона', + 'Edit chunk' => 'Редактирование чанка', + 'Edit styles' => 'Редкатирование стилей', + 'Site theme' => 'Тема сайта', + 'Admin theme' => 'Тема админки', + 'Current site theme' => 'Текущая тема сайта', + 'Current admin theme' => 'Текущая тема админки', + 'This template already exists' => 'Этот шаблон уже существует', + 'This chunk already exists' => 'Этот чанк уже существует', + 'This styles already exists' => 'Эти стили уже существуют', + 'Components templates' => 'Шаблоны компонентов', + 'Your changes to the chunk :name have been saved.' => 'Ваши изменения к чанку :name были сохранены', + 'Your changes to the styles :name have been saved.' => 'Ваши изменения к стилям :name были сохранены', + 'Your changes to the template :name have been saved.' => 'Ваши изменения к шаблону :name были сохранены', + 'This field should not be empty' => 'Это поле не должно быть пустым', + 'Scripts' => 'Скрипты', + 'Create new script' => 'Создать новый скрипт', + 'Script content' => 'Содержимое скрипта', + 'New script' => 'Новый скрипт', + 'Edit script' => 'Редактирование скрипта', + ) + ); \ No newline at end of file diff --git a/plugins/box/themes/themes.admin.php b/plugins/box/themes/themes.admin.php new file mode 100644 index 0000000..096784c --- /dev/null +++ b/plugins/box/themes/themes.admin.php @@ -0,0 +1,547 @@ + 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + + Request::redirect('index.php?id=themes'); + + } else { die('csrf detected!'); } + } + + // Save site theme + if (Request::post('save_admin_theme')) { + + if (Security::check(Request::post('csrf'))) { + + Option::update('theme_admin_name', Request::post('themes')); + + // Cleanup minify + if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + + Request::redirect('index.php?id=themes'); + + } else { die('csrf detected!'); } + } + + // Its mean that you can add your own actions for this plugin + Action::run('admin_themes_extra_actions'); + + // Check for get actions + // ------------------------------------- + if (Request::get('action')) { + + // Switch actions + // ------------------------------------- + switch (Request::get('action')) { + + // Add chunk + // ------------------------------------- + case "add_chunk": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($chunk_path.Security::safeName(Request::post('name')).'.chunk.php')) $errors['file_exists'] = __('This chunk already exists', 'themes'); + + if (count($errors) == 0) { + + // Save chunk + File::setContent($chunk_path.Security::safeName(Request::post('name')).'.chunk.php', Request::post('content')); + + Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_chunk&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('content')) $content = Request::post('content'); else $content = ''; + + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'chunk') + ->display(); + break; + + // Add template + // ------------------------------------- + case "add_template": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($template_path.Security::safeName(Request::post('name')).'.template.php')) $errors['file_exists'] = __('This template already exists', 'themes'); + + if (count($errors) == 0) { + + // Save chunk + File::setContent($template_path.Security::safeName(Request::post('name')).'.template.php', Request::post('content')); + + Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_template&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('content')) $content = Request::post('content'); else $content = ''; + + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'template') + ->display(); + break; + + // Add styles + // ------------------------------------- + case "add_styles": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($style_path.Security::safeName(Request::post('name')).'.css')) $errors['file_exists'] = __('This styles already exists', 'themes'); + + if (count($errors) == 0) { + + // Save chunk + File::setContent($style_path.Security::safeName(Request::post('name')).'.css', Request::post('content')); + + Notification::set('success', __('Your changes to the styles :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_styles&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('content')) $content = Request::post('content'); else $content = ''; + + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'styles') + ->display(); + break; + + // Add script + // ------------------------------------- + case "add_script": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($script_path.Security::safeName(Request::post('name')).'.js')) $errors['file_exists'] = __('This script already exists', 'themes'); + + if (count($errors) == 0) { + + // Save chunk + File::setContent($script_path.Security::safeName(Request::post('name')).'.js', Request::post('content')); + + Notification::set('success', __('Your changes to the script :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_script&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('content')) $content = Request::post('content'); else $content = ''; + + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'script') + ->display(); + break; + + + // Edit chunk + // ------------------------------------- + case "edit_chunk": + + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($chunk_path.Security::safeName(Request::post('name')).'.chunk.php')) and (Security::safeName(Request::post('chunk_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This chunk already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $chunk_old_filename = $chunk_path.Request::post('chunk_old_name').'.chunk.php'; + $chunk_new_filename = $chunk_path.Security::safeName(Request::post('name')).'.chunk.php'; + if ( ! empty($chunk_old_filename)) { + if ($chunk_old_filename !== $chunk_new_filename) { + rename($chunk_old_filename, $chunk_new_filename); + $save_filename = $chunk_new_filename; + } else { + $save_filename = $chunk_new_filename; + } + } else { + $save_filename = $chunk_new_filename; + } + + // Save chunk + File::setContent($save_filename, Request::post('content')); + + Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => basename($save_filename, '.chunk.php')))); + + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_chunk&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')); + $content = File::getContent($chunk_path.Request::get('filename').'.chunk.php'); + + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'chunk') + ->display(); + + break; + + // Edit template + // ------------------------------------- + case "edit_template": + + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($template_path.Security::safeName(Request::post('name')).'.template.php')) and (Security::safeName(Request::post('template_old_name')) !== Security::safeName(Request::post('name')))) $errors['template_exists'] = __('This template already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $template_old_filename = $template_path.Request::post('template_old_name').'.template.php'; + $template_new_filename = $template_path.Security::safeName(Request::post('name')).'.template.php'; + if ( ! empty($template_old_filename)) { + if ($template_old_filename !== $template_new_filename) { + rename($template_old_filename, $template_new_filename); + $save_filename = $template_new_filename; + } else { + $save_filename = $template_new_filename; + } + } else { + $save_filename = $template_new_filename; + } + + // Save chunk + File::setContent($save_filename, Request::post('content')); + + Notification::set('success', __('Your changes to the template :name have been saved.', 'themes', array(':name' => basename($save_filename, '.template.php')))); + + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_template&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')); + $content = File::getContent($chunk_path.Request::get('filename').'.template.php'); + + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'template') + ->display(); + + break; + + // Edit styles + // ------------------------------------- + case "edit_styles": + + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($style_path.Security::safeName(Request::post('name')).'.css')) and (Security::safeName(Request::post('styles_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This styles already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $styles_old_filename = $style_path.Request::post('styles_old_name').'.css'; + $styles_new_filename = $style_path.Security::safeName(Request::post('name')).'.css'; + if ( ! empty($styles_old_filename)) { + if ($styles_old_filename !== $styles_new_filename) { + rename($styles_old_filename, $styles_new_filename); + $save_filename = $styles_new_filename; + } else { + $save_filename = $styles_new_filename; + } + } else { + $save_filename = $styles_new_filename; + } + + // Save chunk + File::setContent($save_filename, Request::post('content')); + + Notification::set('success', __('Your changes to the styles :name have been saved.', 'themes', array(':name' => basename($save_filename, '.css')))); + + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_styles&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')); + $content = File::getContent($style_path.Request::get('filename').'.css'); + + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'styles') + ->display(); + + break; + + + // Edit script + // ------------------------------------- + case "edit_script": + + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($script_path.Security::safeName(Request::post('name')).'.js')) and (Security::safeName(Request::post('script_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This script already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $script_old_filename = $script_path.Request::post('script_old_name').'.js'; + $script_new_filename = $script_path.Security::safeName(Request::post('name')).'.js'; + if ( ! empty($script_old_filename)) { + if ($script_old_filename !== $script_new_filename) { + rename($script_old_filename, $script_new_filename); + $save_filename = $script_new_filename; + } else { + $save_filename = $script_new_filename; + } + } else { + $save_filename = $script_new_filename; + } + + // Save chunk + File::setContent($save_filename, Request::post('content')); + + Notification::set('success', __('Your changes to the script :name have been saved.', 'themes', array(':name' => basename($save_filename, '.js')))); + + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_script&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')); + $content = File::getContent($script_path.Request::get('filename').'.js'); + + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'script') + ->display(); + + break; + + // Delete chunk + // ------------------------------------- + case "delete_chunk": + File::delete($chunk_path.Request::get('filename').'.chunk.php'); + Notification::set('success', __('Chunk :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); + break; + + + // Delete styles + // ------------------------------------- + case "delete_styles": + File::delete($style_path.Request::get('filename').'.css'); + Notification::set('success', __('Styles :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); + break; + + // Delete script + // ------------------------------------- + case "delete_script": + File::delete($style_path.Request::get('filename').'.js'); + Notification::set('success', __('Script :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); + break; + + // Delete template + // ------------------------------------- + case "delete_template": + File::delete($template_path.Request::get('filename').'.template.php'); + Notification::set('success', __('Template :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); + break; + + // Clone styles + // ------------------------------------- + case "clone_styles": + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.css', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') . '.css')); + + Request::redirect('index.php?id=themes'); + break; + + // Clone script + // ------------------------------------- + case "clone_script": + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.js', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') . '.js')); + + Request::redirect('index.php?id=themes'); + break; + + // Clone template + // ------------------------------------- + case "clone_template": + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.template.php', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.template.php')); + + Request::redirect('index.php?id=themes'); + break; + + // Clone chunk + // ------------------------------------- + case "clone_chunk": + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.chunk.php', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.chunk.php')); + + Request::redirect('index.php?id=themes'); + break; + + } + + } else { + + // Display view + View::factory('box/themes/views/backend/index') + ->assign('themes_site', $themes_site) + ->assign('themes_admin', $themes_admin) + ->assign('templates', $templates) + ->assign('chunks', $chunks) + ->assign('styles', $styles) + ->assign('scripts', $scripts) + ->assign('current_site_theme', $current_site_theme) + ->assign('current_admin_theme', $current_admin_theme) + ->display(); + + } + } + } diff --git a/plugins/box/themes/themes.plugin.php b/plugins/box/themes/themes.plugin.php new file mode 100644 index 0000000..961314f --- /dev/null +++ b/plugins/box/themes/themes.plugin.php @@ -0,0 +1,195 @@ + filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php')) { + $buffer = file_get_contents(THEMES_SITE. DS . $current_theme . DS . $name .'.chunk.php'); + $buffer = Minify::html($buffer); + file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php', $buffer); + } + + // Include chunk + include MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php'; + } + + } + + } \ No newline at end of file diff --git a/plugins/box/themes/views/backend/add.view.php b/plugins/box/themes/views/backend/add.view.php new file mode 100644 index 0000000..b7d67b8 --- /dev/null +++ b/plugins/box/themes/views/backend/add.view.php @@ -0,0 +1,47 @@ +

      +

      +

      +

      +
      + + + + + + 'form-horizontal'))); ?> + + + + + +
      + 'input-xlarge'))); ?> + .chunk.php + .template.php + .css + .js +
      + +'.$errors['file_empty_name'].''; + if (isset($errors['file_exists'])) echo '   '.$errors['file_exists'].''; +?> + +

      + + 'width:100%;height:400px;', 'class' => 'source-editor')); + + echo ( + Html::br(2). + Form::submit('add_file_and_exit', __('Save and exit', 'themes'), array('class' => 'btn')).Html::nbsp(2). + Form::submit('add_file', __('Save', 'themes'), array('class' => 'btn')). + Form::close() + ); +?> \ No newline at end of file diff --git a/plugins/box/themes/views/backend/edit.view.php b/plugins/box/themes/views/backend/edit.view.php new file mode 100644 index 0000000..d8997ef --- /dev/null +++ b/plugins/box/themes/views/backend/edit.view.php @@ -0,0 +1,64 @@ +

      +

      +

      +

      +
      + + + + 'form-horizontal'))); + + echo (Form::hidden('csrf', Security::token())); + +?> + + + + + + + + + +
      + 'input-xlarge'))); ?> + .chunk.php + .template.php + .css + .js +
      + +'.$errors['file_empty_name'].''; + if (isset($errors['file_exists'])) echo '   '.$errors['file_exists'].''; +?> + +

      + + 'width:100%;height:400px;', 'class' => 'source-editor')). + Html::br(2). + Form::submit('edit_file_and_exit', __('Save and exit', 'themes'), array('class' => 'btn default')).Html::nbsp(2). + Form::submit('edit_file', __('Save', 'themes'), array('class' => 'btn default')). Html::nbsp(). + Form::close() + ); + + } else { + if ($action == 'chunk') { echo '
      '.__('This chunk does not exist', 'themes').'
      '; } + if ($action == 'template') { echo '
      '.__('This template does not exist', 'themes').'
      '; } + if ($action == 'styles') { echo '
      '.__('This styles does not exist', 'themes').'
      '; } + if ($action == 'script') { echo '
      '.__('This script does not exist', 'themes').'
      '; } + } +?> \ No newline at end of file diff --git a/plugins/box/themes/views/backend/index.view.php b/plugins/box/themes/views/backend/index.view.php new file mode 100644 index 0000000..e529208 --- /dev/null +++ b/plugins/box/themes/views/backend/index.view.php @@ -0,0 +1,199 @@ +
      + +
      + +

      +
      + + + 'span6')). Html::br(). + Form::submit('save_site_theme', __('Save', 'themes'), array('class' => 'btn')). + Form::close() + ); + ?> + + +
      + + +
      + +

      +
      + + + 'span6')). Html::br(). + Form::submit('save_admin_theme', __('Save', 'themes'), array('class' => 'btn')). + Form::close() + ); + ?> + + +
      + +
      + +
      + +
      + +
      + + + + + __('Create new template'), 'class' => 'btn btn-small')).Html::br(2)); ?> + + + + + + + + + + + + + + +
      +
      +
      + 'btn btn-actions')); ?> + + + 'btn btn-actions btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete template: :name', 'themes', array(':name' => basename($template, '.template.php')))."')")); + ?> +
      +
      +
      + + + __('Create new chnuk', 'themes'), 'class' => 'btn btn-small')).Html::br(2)); ?> + + + + + + + + + + + + + + +
      +
      +
      + 'btn btn-actions')); ?> + + + 'btn btn-actions btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete chunk: :name', 'themes', array(':name' => basename($chunk, '.chunk.php')))."')")); + ?> +
      +
      +
      + + + __('Create new style', 'themes'), 'class' => 'btn btn-small')).Html::br(2)); ?> + + + + + + + + + + + + + + +
      +
      +
      + 'btn btn-actions')); ?> + + + 'btn btn-actions btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete styles: :name', 'themes', array(':name' => basename($style, '.css')))."')")); + ?> +
      +
      +
      + + + __('Create new script', 'themes'), 'class' => 'btn btn-small')).Html::br(2)); ?> + + + + + + + + + + + + + + +
      +
      +
      + 'btn btn-actions')); ?> + + + 'btn btn-actions btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete script: :name', 'themes', array(':name' => basename($script, '.js')))."')")); + ?> +
      +
      +
      + + + + 3) { +?> +


      + + +
      +
      \ No newline at end of file diff --git a/plugins/box/users/install/users.manifest.xml b/plugins/box/users/install/users.manifest.xml new file mode 100644 index 0000000..7c7bcff --- /dev/null +++ b/plugins/box/users/install/users.manifest.xml @@ -0,0 +1,11 @@ + + + plugins/box/users/users.plugin.php + active + 7 + Users + Users plugin + 1.0.0 + Awilum + http://monstra.org/ + \ No newline at end of file diff --git a/plugins/box/users/languages/en.lang.php b/plugins/box/users/languages/en.lang.php new file mode 100644 index 0000000..9582bb7 --- /dev/null +++ b/plugins/box/users/languages/en.lang.php @@ -0,0 +1,60 @@ + array( + 'Users' => 'Users', + 'Login' => 'Login', + 'Username' => 'Username', + 'Password' => 'Password', + 'Registered' => 'Registered', + 'Email' => 'Email', + 'Role' => 'Role', + 'Roles' => 'Roles', + 'Edit' => 'Edit', + 'Actions' => 'Actions', + 'Delete' => 'Delete', + 'Enter' => 'Enter', + 'Logout' => 'Logout', + 'Register new user' => 'Register new user', + 'New User Registration' => 'New User Registration', + 'Delete user: :user' => 'Delete user: :user', + 'User :user have been deleted.' => 'User :user have been deleted.', + 'This field should not be empty' => 'This field should not be empty', + 'This user alredy exist' => 'This user alredy exist', + 'Changes saved' => 'Changes saved', + 'Wrong old password' => 'Wrong old password', + 'Admin' => 'Admin', + 'User' => 'User', + 'Editor' => 'Editor', + 'Register' => 'Register', + 'Edit profile' => 'Edit profile', + 'Save' => 'Save', + 'Firstname' => 'Firstname', + 'Lastname' => 'Lastname', + 'Old password' => 'Old password', + 'New password' => 'New password', + 'Welcome' => 'Welcome', + 'Wrong username or password' => 'Wrong username or password', + 'Your changes have been saved.' => 'Your changes have been saved.', + 'New user have been registered.' => 'New user have been registered.', + 'Captcha' => 'Captcha', + 'Registration' => 'Registration', + 'Username' => 'Username', + 'User email is invalid' => 'User email is invalid', + 'Reset Password' => 'Reset Password', + 'Send New Password' => 'Send New Password', + 'This user doesnt alredy exist' => 'This user doesnt alredy exist', + 'Users - Profile' => 'Users - Profile', + 'Users - Edit Profile' => 'Users - Edit Profile', + 'Users - Login' => 'Users - Login', + 'Users - Registration' => 'Users - Registration', + 'Users - Password Recover' => 'Users - Password Recover', + 'New Password' => 'New Password', + 'Forgot your password?' => 'Forgot your password?', + 'New password has been sent' => 'New password has been sent', + 'Monstra says: This is not your profile...' => 'Monstra says: This is not your profile...', + 'User registration is closed.' => 'User registration is closed.', + 'Allow user registration' => 'Allow user registration', + 'Required field' => 'Required field', + ) + ); \ No newline at end of file diff --git a/plugins/box/users/languages/ru.lang.php b/plugins/box/users/languages/ru.lang.php new file mode 100644 index 0000000..0f39ee1 --- /dev/null +++ b/plugins/box/users/languages/ru.lang.php @@ -0,0 +1,59 @@ + array( + 'Users' => 'Пользователи', + 'Login' => 'Вход', + 'Password' => 'Пароль', + 'Email' => 'Емейл', + 'Registered' => 'Зарегистрирован', + 'Role' => 'Роль', + 'Roles' => 'Роли', + 'Actions' => 'Действия', + 'Edit' => 'Редактировать', + 'Delete' => 'Удалить', + 'Enter' => 'Вход', + 'Logout' => 'Выход', + 'New User Registration' => 'Регистрация нового пользователя', + 'Register new user' => 'Регистрация нового пользователя', + 'Delete user: :user' => 'Удалить пользователя: :user', + 'User :user have been deleted.' => 'Пользователь :user удален.', + 'This field should not be empty' => 'Это поле не должно быть пустым', + 'This user alredy exist' => 'Такой пользователь уже существует', + 'Changes saved' => 'Изменения сохранены', + 'Wrong old password' => 'Неправильный старый пароль', + 'Admin' => 'Администратор', + 'User' => 'Пользователь', + 'Editor' => 'Редактор', + 'Register' => 'Регистрация', + 'Edit profile' => 'Редактирование профиля пользователя', + 'Save' => 'Сохранить', + 'Firstname' => 'Имя', + 'Lastname' => 'Фамилия', + 'Old password' => 'Старый пароль', + 'New password' => 'Новый пароль', + 'Welcome' => 'Добро пожаловать', + 'Wrong login or password' => 'Неправильный логин или пароль', + 'Your changes have been saved.' => 'Ваши изменения были сохранены.', + 'New user have been registered.' => 'Новый пользователь был зарегистрирован.', + 'Captcha' => 'Капча', + 'Registration' => 'Регистрация', + 'Username' => 'Имя пользователя', + 'User email is invalid' => 'Электронная почта является недействительной', + 'Reset Password' => 'Сбросить пароль', + 'Send New Password' => 'Отослать пароль', + 'This user doesnt alredy exist' => 'Такого пользователя не существует', + 'Users - Profile' => 'Пользователи - Профиль', + 'Users - Edit Profile' => 'Пользователи - Редактирование профиля', + 'Users - Login' => 'Пользователи - Вход', + 'Users - Registration' => 'Пользователи - Регистрация', + 'Users - Password Recover' => 'Пользователи - Восстановление пароля', + 'New Password' => 'Новый пароль', + 'Forgot your password?' => 'Забыли пароль ?', + 'New password has been sent' => 'Новый пароль был отправлен', + 'Monstra says: This is not your profile...' => 'Монстра говорит: Это не твой профиль.', + 'User registration is closed.' => 'Регистрация пользователей закрыта.', + 'Allow user registration' => 'Разрешить регистрацию пользователей.', + 'Required field' => 'Обязательное поле', + ) + ); \ No newline at end of file diff --git a/plugins/box/users/users.admin.php b/plugins/box/users/users.admin.php new file mode 100644 index 0000000..8837a04 --- /dev/null +++ b/plugins/box/users/users.admin.php @@ -0,0 +1,214 @@ + + $(document).ready(function(){ + $("[name=users_frontend_registration] , [name=users_frontend_authorization]").click(function() { + $("[name=users_frontend]").submit(); + }); + }); + + '); + } + + /** + * Users admin + */ + public static function main() { + + // Users roles + $roles = array('admin' => __('Admin', 'users'), + 'editor' => __('Editor', 'users'), + 'user' => __('User', 'users')); + + // Get uses table + $users = new Table('users'); + + if (Option::get('users_frontend_registration') == 'true') { + $users_frontend_registration = true; + } else { + $users_frontend_registration = false; + } + + if (Request::post('users_frontend_submit')) { + if (Request::post('users_frontend_registration')) $users_frontend_registration = 'true'; else $users_frontend_registration = 'false'; + Option::update('users_frontend_registration', $users_frontend_registration); + Request::redirect('index.php?id=users'); + } + + // Check for get actions + // --------------------------------------------- + if (Request::get('action')) { + + // Switch actions + // ----------------------------------------- + switch (Request::get('action')) { + + // Add + // ------------------------------------- + case "add": + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + + $errors = array(); + if (Request::post('register')) { + + if (Security::check(Request::post('csrf'))) { + + $user_login = trim(Request::post('login')); + $user_password = trim(Request::post('password')); + if ($user_login == '') $errors['users_empty_login'] = __('This field should not be empty', 'users'); + if ($user_password == '') $errors['users_empty_password'] = __('This field should not be empty', 'users'); + $user = $users->select("[login='".$user_login."']"); + if ($user != null) $errors['users_this_user_alredy_exists'] = __('This user alredy exist', 'users'); + + if (count($errors) == 0) { + $users->insert(array('login' => Security::safeName($user_login), + 'password' => Security::encryptPassword(Request::post('password')), + 'email' => Request::post('email'), + 'date_registered' => time(), + 'role' => Request::post('role'))); + + Notification::set('success', __('New user have been registered.', 'users')); + Request::redirect('index.php?id=users'); + } + + } else { die('csrf detected!'); } + } + + // Display view + View::factory('box/users/views/backend/add') + ->assign('roles', $roles) + ->assign('errors', $errors) + ->display(); + + } else { + Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); + } + + break; + + // Edit + // ------------------------------------- + case "edit": + + // Get current user record + $user = $users->select("[id='".(int)Request::get('user_id')."']", null); + + if (isset($user['firstname'])) $user_firstname = $user['firstname']; else $user_firstname = ''; + if (isset($user['lastname'])) $user_lastname = $user['lastname']; else $user_lastname = ''; + if (isset($user['email'])) $user_email = $user['email']; else $user_email = ''; + if (isset($user['twitter'])) $user_twitter = $user['twitter']; else $user_twitter = ''; + if (isset($user['skype'])) $user_skype = $user['skype']; else $user_skype = ''; + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) { + + if ((Request::post('edit_profile')) and + (((int)Session::get('user_id') == (int)Request::get('user_id')) or + (in_array(Session::get('user_role'), array('admin'))))){ + + if (Security::check(Request::post('csrf'))) { + + if (Security::safeName(Request::post('login')) != '') { + if ($users->update(Request::post('user_id'), array('login' => Security::safeName(Request::post('login')), + 'firstname' => Request::post('firstname'), + 'lastname' => Request::post('lastname'), + 'email' => Request::post('email'), + 'skype' => Request::post('skype'), + 'twitter' => Request::post('twitter'), + 'role' => Request::post('role')))) { + + Notification::set('success', __('Your changes have been saved.', 'users')); + Request::redirect('index.php?id=users&action=edit&user_id='.Request::post('user_id')); + } + } else { } + + } else { die('csrf detected!'); } + + } + + if (Request::post('edit_profile_password')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('new_password')) != '') { + $users->update(Request::post('user_id'), array('password' => Security::encryptPassword(trim(Request::post('new_password'))))); + Notification::set('success', __('Your changes have been saved.', 'users')); + Request::redirect('index.php?id=users&action=edit&user_id='.Request::post('user_id')); + } + + } else { die('csrf detected!'); } + } + + if ( ((int)Session::get('user_id') == (int)Request::get('user_id')) or (in_array(Session::get('user_role'), array('admin')) && count($user) != 0) ) { + + // Display view + View::factory('box/users/views/backend/edit') + ->assign('user', $user) + ->assign('user_firstname', $user_firstname) + ->assign('user_lastname', $user_lastname) + ->assign('user_email', $user_email) + ->assign('user_twitter', $user_twitter) + ->assign('user_skype', $user_skype) + ->assign('roles', $roles) + ->display(); + + } else { + echo __('Monstra says: This is not your profile...', 'users'); + } + + } + + break; + + // Delete + // ------------------------------------- + case "delete": + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + $user = $users->select('[id="'.Request::get('user_id').'"]', null); + $users->delete(Request::get('user_id')); + Notification::set('success', __('User :user have been deleted.', 'users', array(':user' => $user['login']))); + Request::redirect('index.php?id=users'); + } + + break; + } + } else { + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + + // Get all records from users table + $users_list = $users->select(); + + // Dislay view + View::factory('box/users/views/backend/index') + ->assign('roles', $roles) + ->assign('users_list', $users_list) + ->assign('users_frontend_registration', $users_frontend_registration) + ->display(); + + } else { + Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); + } + } + + } + } \ No newline at end of file diff --git a/plugins/box/users/users.plugin.php b/plugins/box/users/users.plugin.php new file mode 100644 index 0000000..6820486 --- /dev/null +++ b/plugins/box/users/users.plugin.php @@ -0,0 +1,399 @@ +assign('users', Users::$users->select(null, 'all')) + ->display(); + } + + + /** + * Get user profile + */ + public static function getProfile($id) { + View::factory('box/users/views/frontend/profile') + ->assign('user', Users::$users->select("[id=".(int)$id."]", null)) + ->display(); + } + + + /** + * Get New User Registration + */ + public static function getRegistration() { + + if (Option::get('users_frontend_registration') == 'true') { + + // Is User Loged in ? + if ( ! Session::get('user_id')) { + + $errors = array(); + + $user_email = Request::post('email'); + $user_login = Request::post('login'); + $user_password = Request::post('password'); + + // Register form submit + if (Request::post('register')) { + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + $user_email = trim($user_email); + $user_login = trim($user_login); + $user_password = trim($user_password); + + if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'captcha'); + if ($user_login == '') $errors['users_empty_login'] = __('Required field', 'users'); + if ($user_password == '') $errors['users_empty_password'] = __('Required field', 'users'); + if ($user_email == '') $errors['users_empty_email'] = __('Required field', 'users'); + if ($user_email != '' && ! Valid::email($user_email)) $errors['users_invalid_email'] = __('User email is invalid', 'users'); + if (Users::$users->select("[login='".$user_login."']")) $errors['users_this_user_alredy_exists'] = __('This user alredy exist', 'users'); + if (Users::$users->select("[email='".$user_email."']")) $errors['users_this_email_alredy_exists'] = __('This email alredy exist', 'users'); + + if (count($errors) == 0) { + + Users::$users->insert(array('login' => Security::safeName($user_login), + 'password' => Security::encryptPassword(Request::post('password')), + 'email' => Request::post('email'), + 'date_registered' => time(), + 'role' => 'user')); + + // Log in + $user = Users::$users->select("[id='".Users::$users->lastId()."']", null); + Session::set('user_id', (int)$user['id']); + Session::set('user_login', (string)$user['login']); + Session::set('user_role', (string)$user['role']); + + // Redirect to user profile + Request::redirect(Option::get('siteurl').'users/'.Users::$users->lastId()); + } + + + + } else { die('csrf detected!'); } + } + + // Display view + View::factory('box/users/views/frontend/registration') + ->assign('errors', $errors) + ->assign('user_email', $user_email) + ->assign('user_login', $user_login) + ->assign('user_password', $user_password) + ->display(); + + } else { + Request::redirect(Site::url().'users/'.Session::get('user_id')); + } + + } else { + echo __('User registration is closed.', 'users'); + } + + } + + + /** + * Get user panel + */ + public static function getPanel() { + View::factory('box/users/views/frontend/userspanel')->display(); + } + + + /** + * Is User Loged + */ + public static function isLoged() { + if ((Session::get('user_id')) and (((int)Session::get('user_id') == Uri::segment(1)) or (in_array(Session::get('user_role'), array('admin'))))) { + return true; + } else { + return false; + } + } + + + /** + * Logout + */ + public static function logout() { + Session::destroy(); Request::redirect(Site::url().'users/login'); + } + + + /** + * Edit user profile + */ + public static function getProfileEdit($id) { + + // Is Current User Loged in ? + if (Users::isLoged()) { + + $user = Users::$users->select("[id='".(int)$id."']", null); + + // Edit Profile Submit + if (Request::post('edit_profile')) { + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + + if (Security::safeName(Request::post('login')) != '') { + if (Users::$users->update(Request::post('user_id'), + array('login' => Security::safeName(Request::post('login')), + 'firstname' => Request::post('firstname'), + 'lastname' => Request::post('lastname'), + 'email' => Request::post('email'), + 'skype' => Request::post('skype'), + 'twitter' => Request::post('twitter')))) { + + // Change password + if (trim(Request::post('new_password')) != '') { + Users::$users->update(Request::post('user_id'), array('password' => Security::encryptPassword(trim(Request::post('new_password'))))); + } + + Notification::set('success', __('Your changes have been saved.', 'users')); + Request::redirect(Site::url().'users/'.$user['id'].'/edit'); + } + } else { } + + } else { die('csrf detected!'); } + + } + + View::factory('box/users/views/frontend/edit') + ->assign('user', $user) + ->display(); + + } else { + Request::redirect(Site::url().'users/login'); + } + } + + /** + * Get Password Reset + */ + public static function getPasswordReset() { + + // Is User Loged in ? + if ( ! Session::get('user_id')) { + + $errors = array(); + + $user_login = Request::post('login'); + + // Reset Password Form Submit + if (Request::post('reset_password_submit')) { + + $user_login = trim($user_login); + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users'); + if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users'); + if ($user_login != '' && ! Users::$users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt alredy exist', 'users'); + + if (count($errors) == 0) { + + $user = Users::$users->select("[login='" . $user_login . "']", null); + + // Generate new password + $new_password = Text::random('alnum', 6); + + // Update user profile + Users::$users->updateWhere("[login='" . $user_login . "']", array('password' => Security::encryptPassword($new_password))); + + // Message + $message = "Login: {$user['login']}\nNew Password: {$new_password}"; + + // Send + @mail($user['email'], 'MonstraPasswordReset', $message); + + // Set notification + Notification::set('success', __('New password has been sent', 'users')); + + // Redirect to password-reset page + Request::redirect(Site::url().'users/password-reset'); + + } + + + } else { die('csrf detected!'); } + + } + + View::factory('box/users/views/frontend/password_reset') + ->assign('errors', $errors) + ->assign('user_login', $user_login) + ->display(); + + } + } + + /** + * Get User login + */ + public static function getLogin() { + + // Is User Loged in ? + if ( ! Session::get('user_id')) { + + // Login Form Submit + if (Request::post('login_submit')) { + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + $user = Users::$users->select("[login='" . trim(Request::post('username')) . "']", null); + + if (count($user) !== 0) { + if ($user['login'] == Request::post('username')) { + 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(Site::url().'users/'.Session::get('user_id')); + } else { + Notification::setNow('error', __('Wrong login or password', 'users')); + } + } + } else { + Notification::setNow('error', __('Wrong login or password', 'users')); + } + + } else { die('csrf detected!'); } + + } + + View::factory('box/users/views/frontend/login')->display(); + } else { + Request::redirect(Site::url().'users/'.Session::get('user_id')); + } + } + + + /** + * Set title + */ + public static function title(){ + switch (Users::route()) { + case 'list': return __('Users'); break; + case 'profile': return __('Users - Profile'); break; + case 'edit': return __('Users - Edit Profile'); break; + case 'login': return __('Users - Login'); break; + case 'registration': return __('Users - Registration'); break; + case 'password-reset': return __('Users - Password Recover'); break; + } + } + + + /** + * Set content + */ + public static function content(){ + switch (Users::route()) { + case 'list': Users::getList(); break; + case 'profile': Users::getProfile(Uri::segment(1)); break; + case 'edit': Users::getProfileEdit(Uri::segment(1)); break; + case 'login': Users::getLogin(); break; + case 'registration': Users::getRegistration(); break; + case 'password-reset': Users::getPasswordReset(); break; + + } + } + + /** + * Set template + */ + public static function template() { + return 'index'; + } + + + /** + * Get Gravatar + */ + public static function getGravatarURL($email, $size) { + return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).'&rating=PG'.'&size='.$size; + } + + } diff --git a/plugins/box/users/views/backend/add.view.php b/plugins/box/users/views/backend/add.view.php new file mode 100644 index 0000000..90d09ea --- /dev/null +++ b/plugins/box/users/views/backend/add.view.php @@ -0,0 +1,32 @@ + +'.__('New User Registration', 'users').'' ); + + echo ( + Html::br(). + Form::open(). + Form::hidden('csrf', Security::token()). + Form::label('login', __('Username', 'users')). + Form::input('login', null, array('class' => 'span3')) + ); + + if (isset($errors['users_this_user_alredy_exists'])) echo Html::nbsp(3).''.$errors['users_this_user_alredy_exists'].''; + if (isset($errors['users_empty_login'])) echo Html::nbsp(3).''.$errors['users_empty_login'].''; + + echo ( + Form::label('password', __('Password', 'users')). + Form::password('password', null, array('class' => 'span3')) + ); + + if (isset($errors['users_empty_password'])) echo Html::nbsp(3).''.$errors['users_empty_password'].''; + + echo ( + Form::label('email', __('Email', 'users')). + Form::input('email', null, array('class' => 'span3')). Html::br(). + Form::label('role', __('Role', 'users')). + Form::select('role', array('admin' => __('Admin', 'users'), 'editor' => __('Editor', 'users'), 'user' => __('User', 'users')), null, array('class' => 'span3')). Html::br(2). + Form::submit('register', __('Register', 'users'), array('class' => 'btn default')). + Form::close() + ); +?> + \ No newline at end of file diff --git a/plugins/box/users/views/backend/edit.view.php b/plugins/box/users/views/backend/edit.view.php new file mode 100644 index 0000000..70b0e16 --- /dev/null +++ b/plugins/box/users/views/backend/edit.view.php @@ -0,0 +1,89 @@ + +'.__('Edit profile', 'users').'' ); + +?> + +
      + + + + +
      + +
      + 'span6')); + } else { + echo Form::hidden('login', $user['login']); + } + + echo ( + Html::br(). + Form::label('firstname', __('Firstname', 'users')). + Form::input('firstname', $user_firstname, array('class' => 'span6')).Html::br(). + Form::label('lastname', __('Lastname', 'users')). + Form::input('lastname', $user_lastname, array('class' => 'span6')).Html::br(). + Form::label('email', __('Email', 'users')). + Form::input('email', $user_email, array('class' => 'span6')).Html::br(). + Form::label('twitter', __('Twitter', 'users')). + Form::input('twitter', $user_twitter, array('class' => 'span6')).Html::br(). + Form::label('skype', __('Skype', 'users')). + Form::input('skype', $user_skype, array('class' => 'span6')).Html::br() + ); + + if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], array('admin'))) { + echo Form::label('role', __('Role', 'users')); + echo Form::select('role', array('admin' => __('Admin', 'users'), 'editor' => __('Editor', 'users'), 'user' => __('User', 'users')), $user['role'], array('class' => 'span3')). Html::br(); + } else { + echo Form::hidden('role', $_SESSION['user_role']); + } + + + echo ( + Html::br(). + Form::submit('edit_profile', __('Save', 'users'), array('class' => 'btn')). + Form::close() + ); + + ?> +
      + +
      + 'span6')).Html::br().Html::br(). + Form::submit('edit_profile_password', __('Save', 'users'), array('class' => 'btn')). + Form::close() + ); + ?> +
      + +
      + +
      + +'.__('This user does not exist', 'users').'
    '; + } +?> + \ No newline at end of file diff --git a/plugins/box/users/views/backend/index.view.php b/plugins/box/users/views/backend/index.view.php new file mode 100644 index 0000000..d01e0e7 --- /dev/null +++ b/plugins/box/users/views/backend/index.view.php @@ -0,0 +1,55 @@ +

    +
    + + + + __('Create new page', 'users'), 'class' => 'btn default btn-small')); ?> + +
    + 'users_frontend')); ?> + + + 'display:none;')); ?> + +
    + +

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + 'btn btn-actions')); ?> + 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete user: :user', 'users', array(':user' => Html::toText($user['login'])))."')")); + ?> +
    + \ No newline at end of file diff --git a/plugins/box/users/views/frontend/edit.view.php b/plugins/box/users/views/frontend/edit.view.php new file mode 100644 index 0000000..6b18345 --- /dev/null +++ b/plugins/box/users/views/frontend/edit.view.php @@ -0,0 +1,26 @@ +

    +
    + + + + +
    + + + + + + + + + + + +
    +
    +
    \ No newline at end of file diff --git a/plugins/box/users/views/frontend/index.view.php b/plugins/box/users/views/frontend/index.view.php new file mode 100644 index 0000000..6adfed3 --- /dev/null +++ b/plugins/box/users/views/frontend/index.view.php @@ -0,0 +1,14 @@ +

    +
    + + + + + + + + + +
    + +
    \ No newline at end of file diff --git a/plugins/box/users/views/frontend/login.view.php b/plugins/box/users/views/frontend/login.view.php new file mode 100644 index 0000000..be226a2 --- /dev/null +++ b/plugins/box/users/views/frontend/login.view.php @@ -0,0 +1,10 @@ +

    +
    + +
    + + + +
    +
    + diff --git a/plugins/box/users/views/frontend/password_reset.view.php b/plugins/box/users/views/frontend/password_reset.view.php new file mode 100644 index 0000000..6f9d2e4 --- /dev/null +++ b/plugins/box/users/views/frontend/password_reset.view.php @@ -0,0 +1,25 @@ +

    +
    + + + + +
    + + + +'.$errors['users_user_doesnt_exists'].''; + if (isset($errors['users_empty_field'])) echo Html::nbsp(3).''.$errors['users_empty_field'].''; +?> + + +