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

MONSTRA 4 CLEAN UP COMMIT

This commit is contained in:
Awilum
2018-02-26 23:20:56 +03:00
parent 8c318cdd03
commit 9a19078870
961 changed files with 0 additions and 104071 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

35
.gitignore vendored
View File

@@ -1,35 +0,0 @@
# ignore os/app generated files
Thumbs.db
.DS_Store
*.esproj
*.project
*.sublime-project
*.sublime-workspace
# ignore user .htaccess
/.htaccess
# ignore user sitemap
/sitemap.xml
# ignore user defines
/monstra/boot/defines.php
# ignore debug and custom themes
/public/themes/*
/admin/themes/*
!/public/themes/default
!/admin/themes/default
# ignore user plugins
/plugins/*
!/plugins/box
!/plugins/captcha
!/plugins/markitup
!/plugins/sandbox
# ignore user files and folders
/backups/*
/public/*
/storage/*
/tmp/*

View File

@@ -1,68 +0,0 @@
#
# This file is part of the Monstra.
#
# (c) Romanenko Sergey / Awilum <awilum@msn.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# Set default charset utf-8
AddDefaultCharset UTF-8
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_flag magic_quotes_gpc off
php_flag magic_quotes_sybase off
php_flag register_globals off
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine on
## Begin - Rewrite rules to block out some common exploits.
# If you experience problems on your site block out the operations listed below
# This attempts to block the most common type of exploit `attempts` to Monstra
#
# Block out any script trying to base64_encode data within the URL.
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
# Block out any script that includes a <script> tag in URL.
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL.
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL.
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Return 403 Forbidden header and show the content of the root homepage
RewriteRule .* index.php [F]
#
## End - Rewrite rules to block out some common exploits.
## Begin - Rewrite rules for Monstra
RewriteBase /%siteurlhere%/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
## End - Rewrite rules for Monstra
## Begin - Rewrite rules for SEO improvements.
# RewriteCond %{HTTP_HOST} ^www.example.org [NC]
# RewriteRule ^(.*)$ http://example.org/$1 [R=301,L]
# Redirect 301 /index http://example.org/
## End - Rewrite rules for SEO improvements.
</IfModule>
# Prevent visitors from viewing files directly.
<FilesMatch "(^#.*#|\.(md|txt|html|tpl|yml|yaml)|~)$">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
# Allow read files.
<Files robots.txt>
Allow from all
</Files>
# Don't show directory listings for URLs which map to a directory.
Options -Indexes

View File

@@ -1,368 +0,0 @@
Monstra 3.0.4, 2016-04-05
------------------------
- Fixed User Security by adding a check that compares POST id with SESSION
id for none admin edits
- Fixed ability to read robots.txt
- Stylesheet: Changed minified URIs to eliminate query strings
- FilesManager: added alphabetical order for files and directories
- Localization: Major Fixes for ES locale
Monstra 3.0.3, 2016-01-29
------------------------
- Improved Monstra Security
- Minimum PHP version for Monstra is 5.3.2
- Admin: Fixed 404 error when using certain server configurations
- Localization: Major Fixes for SR, KA-GE, and ES
- Install Script Fixes
Monstra 3.0.2, 2015-10-16
------------------------
- Added Monstra MIT LICENSE instead of GNU GENERAL PUBLIC LICENSE v3
- Code standards fixes.
- Localization: Major Fixes for ES and SR
Monstra 3.0.1, 2014-08-10
------------------------
- Minimum php is 5.3
- Themes Plugin: Imposible to create new CSS - fixed
- Themes Plugin: js and css counter does not recalculate - fixed
- Error in Monstra Notifications - fixed
- Updated plugins url from plugins.monstra.org to monstra.org/download/plugins
Monstra 3.0.0, 2014-08-01
------------------------
- Mobile Ready! Monstra fully responsive for mobile devices, tablets, and normal computer screens.
- Twitter Bootstrap updated to 3.1.1
- Idiorm updated to 1.4.1
- jQuery updated to 2.1.0
- Admin: New Modern User Interface
- Site: New default theme
- Layout fixes according to World Wide Web Consortium (W3C) Standards
- Prefetch DNS to reduce look up times
- Files Manager: added ability to create & rename directories.
- Files Manager: Maximum upload file size message - added.
- Files Manager: Bootstrap fileinput.js updated to 3.0.0
- Files Manager: File Info Popup
- Backup: Restore Site from Backup added
- Plugins Manager: Uploading new plugins via the admin panel added
- Plugins Manager: Read plugin help(README.MD) ability added.
- Responsive Chocolat Lightbox instead of TB Lightbox
- Blog Plugin as a part of Monstra CMS
- CodeMirror Plugin as a part of Monstra CMS
- Markdown Plugin as a part of Monstra CMS
- MarkItUp Color Pallete fixes
- Site Url without trailing slashes
- Admin Help Section - added.
- Pages Plugin: tags field added.
- Pages Plugin: Meta Title added.
- Sitemap Errors Fixes.
- Monstra automatically renames files - fixed
- Monstra Dashboard created and set as default Plugin for Admin Panel
- Ink Framework for Monstra Email Templates
- iCheck plugin for checkboxes added.
- Emails Manager Plugin added.
- HubSpot Messaging Library added for notifications
- Gelato: Unzip Functionality added.
- Gelato: Number Class new method convertToBytes() added.
- Gelato: ErroHandler styles updates
- Users Plugin getGravatarURL() improve
- Plugin API - Actions - Closure support added.
- Plugin API - Filters - Closure support added.
- Core: Better statuses notification (error,success,warning)
- Core: Store user_email in Session
- Core: Javascript may be broken if there is no break line - fixed
- Core: Added ability to avoid caching JS/CSS by the browser.
- Core: Monstra automatically rename files Issue - fixed
- Sandbox Plugin cleanup
- New Flags: Japanese(JA), Indonesian(ID), Chinese(ZH-CN), Turkish(TR) added.
- Localization: Japanese(JA), Indonesian(ID), Chinese(ZH-CN), Turkish(TR) translations added.
- Localization: Major Fixes
Monstra 2.3.1, 2013-12-25
------------------------
- Localization: Major Fixes
- Gelato: Image.php Major Fixes
- Sitemap: Errors #175 - fixes
- New favicon added #182 - by bernte
- Layouts: General Fixes - by bernte
- Installer: SERVER_PORT issue - fixed by KANekT
- Gelato: Number Class - updated bytes format (JEDEC & IEC 60027) by mbarzda
- Email Layout: footer fixes
Monstra 2.3.0, 2013-12-19
------------------------
- Update Twitter Bootstrap to 2.3.2
- Security: Added limits for login attempts #104
- Security: Obfuscate users email to prevent spam-bots from sniffing it.
- Core: Added ability to map Monstra Engine Directory.
- Core: Maintenance Mode Improvements
- Core: ORM::configure - driver options added
- Gelato: Image.php fix for PNG files
- Gelato: Number.php: Undefined offset fix
- XMLDB: error select for empty table fix
- Plugin API: Stylesheet.php updates - sourcecode misses a linebreak after minified css
- Files Manager: jasny bootstrap-fileupload - added #89
- Users Plugin: login page fixes
- Users Plugin: Deleting users - fixed by Oleg Gatseluk #158
- Pages Plugin: General method getPages() created #123
- Pages Plugin: page expand ajax bug #115 - fixed
- Pages Plugin: Improved available() method to show only published pages
- Pages Plugin: Bug with pages renaming - fixed
- Monstra Email Templates #164
- Localization: Major Fixes
- Localization: PL added
- Localization: NL added
- .htaccess SEO improvements
Monstra 2.2.1, 2013-04-06
------------------------
- Update Gelato to 1.0.3
- Error Handler turned off for Production environment
- Localization: Farsi(fa) translations fixes.
- Pages Manager: fix translates #107
- Missing Translation on Login Page - fixed #106
- Lithuanian flag and other languages fixes. Thanks to mbarzda
Monstra 2.2.0, 2013-03-25
------------------------
- Mobile Ready! Monstra fully responsive for mobile devices, tablets, and normal computer screens.
- Improved Monstra Architecture!
- New Stand-alone Monstra Library (Gelato) was created! Totally improved old classes and added new classes!
- Monstra Library with new useful classes - ClassLoader, ErrorHandler, Log, MinifyJS, MinifyCSS, MinifyHTML, Token, Registry.
- Adopted PSR-0 PSR-1 PSR-2
- Localization: Farsi(fa), Magyar(hu), Français(fr), Spanish(es), Serbian(sr-yu), Slovakian(sk) translations added. Thanks to Abdulhalim, Lez, Neri, Mapadesign, Hugomano and Nakome.
- Idiorm Updated to 1.3.0
- jQuery Updated to 1.9.1
- Twitter Bootstrap Updated to 2.3.0
- Default Theme: Social Meta Tags - added.
- Default Theme: Hook "theme_meta" - added.
- Admin Default Theme: Added missing meta tags.
- Improve Installer Usability. Flags Added.
- Default Site Email added.
- PHPMailer added.
- Pages Manager: added ability to quickly update page status and page access.
- Intstaller Layout: Added missing meta tags.
- Filesmanager plugin: added ability to view images.
- Filesmanager Plugin: forbidden types array - updated.
- CSRF detection text - updated.
- Engine Uri: code improvements.
- XMLDB: Table Class - fixed select method. Thanks to DmitriyMX
- Bootstrap CSS: Icons url - fixed.
- Plugins Manager: buttons confirm dialog message - fixed.
- Pages Manager: page cloning problem - fixed.
- Localizations: translations fixes.
Monstra 2.1.3, 2012-12-09
------------------------
- Pages Plugin: New shortcodes added - page_author, page_slug, page_url page_available, page_breadcrumbs, page_date, page_content.
- Pages Plugin: add ability to get content for specific page.
- XMLDB: New method factory() added.
- Twitter Bootstrap updated to Version 2.2.2
- Sitemap Plugin: `_blank` removed.
- Filesmanager Plugin: fixes.
- Backup Plugin: fixes.
Monstra 2.1.2, 2012-12-05
------------------------
- Blocks Plugin: added ability create and render inline content blocks with {block_inline} and {block_inline_create}
- Site Module: methods keywords() and description() fixes.
- Pages Plugin: pages.js fixes.
- Admin main index.php fixes.
Monstra 2.1.1, 2012-11-30
------------------------
- Plugins: Minify bug #71 - fixed.
- Menu Plugin: bug with categories #70 - fixed.
- Localization: IT translations - fixed.
Monstra 2.1.0, 2012-11-29
------------------------
- Localization: PT-BR, UK translations added.
- Default theme: hook "theme_header" added.
- System Plugin: new action "admin_system_extra_index_template_actions" added.
- Shortcodes API: new delete() clear() exists() methods added.
- Options API: new exists() method added.
- Core: new constant VERSION - added.
- Core: added ability to load: defines, actions, filters, shortcodes for current environment.
- Defines: deprecated constants: MONSTRA_GZIP_STYLES, MONSTRA_VERSION, MONSTRA_VERSION_ID, MONSTRA_SITEURL, MONSTRA_MOBILE deleted.
- Box Plugins: used Core::VERSION to compare Monstra CMS version.
- Installer: use version_compare() function to compare php versions.
- Installer: Get system timezone with date_default_timezone_get() function.
- Admin Default Theme: general improvements.
- Users Plugin: user profile editing fixed.
- Shortcodes API: bug with similar shortcode names fixed.
- Site: template() method improvements. Added ability to get template from specific theme.
- Menu Plugin: added ability to select children pages.
- Snippets Plugin: added ability to add parameters for snippets.
- Themes Plugin: added ability to add parameters for chunks.
- Pages Plugin: pages expand/collapse feature added.
- Pages Plugin: pages "access" feature added.
- Pages Plugin: tab "seo" changed to "metadata"
- Pages Table: "expand, "access" fields added.
- Information Plugin: new "Directory Permissions" tab added.
- Twitter Bootstrap updated to Version 2.2.1
- MarkitUp! updated to Version 1.1.13
- Sitemap Plugin: links title issue fixed.
- Core: Init Site module on frontend only.
- Core: IDIORM optimization.
- Site Class: code optimization.
- Sitemap Plugin: bug with priority fixed.
- File .gitignore added.
- Monstra logo updated.
- README: general updates
- Pages Plugin: "delete" action fixes.
- Plugins Manager: add ability to Cleanup minify with new plugin installation or plugin uninstallation.
- MarkitUp Plugin: unnecessary files removed.
- XMLDB: select() method fixes.
- XMLDB: new method existsField() added.
- Information Plugin: shows "PHP Built On", "Web Server", "WebServer to PHP Interface" information.
- Installer: general fixes.
- Blocks Plugin: view embed codes feature added.
- Snippets Plugin: view embed codes feature added.
- Text Helper: method strpSlashes() fixed.
- Text Helper: new method increment() added.
- Pages Plugin: method robots() fixes.
- Pages Plugin: improved page author detection.
- Pages Plugin: add, edit, delete, clone actions improvements.
- Users Plugin: apply "content" filter for "about_me" field.
- Plugin API: Stylesheet and Javascript load() methods - fixed.
- Pages Plugin: Page editing date issue - fixed.
- Localization: EN, RU, IT, LT, DE translations fixed.
- Imformation Plugin: config file(defines.php) checking removed.
- Box Plugins: general code refactoring.
Monstra 2.0.1, 2012-10-18
------------------------
- Localization: DE, LT, IT translations added
- Validation Helper: Updated email, ip and url methods with filter_var instead preg_match function.
- Localization: EN, RU translations fixed
- Users Plugin: field "about_me" fixed
Monstra 2.0.0, 2012-10-09
------------------------
- Idiorm Added! Idiorm - a lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.
- Added Crypt Capthca Plugin
- Users Plugin: Added 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.
- Pages Plugin: Added new actions: admin_pages_action_add, admin_pages_action_edit, admin_pages_action_clone, admin_pages_action_delete
- Pages Plugin: Updated date() method - added ability to set date format.
- Pages Plugin: UI and Logic updates.
- Users Plugin: Email templates added.
- Users Table: Added new fields: hash, about_me
- Users Plugin: Admin - New User Registration Validation - Fixed
- Users Plugin: Added ability to set "about me" information.
- Improved Password Reset Logic.
- Information Plugin: Added new tab "Server" with common server information.
- Box Plugins: CSRF vulnerability resolved.
- Sitemap Plugin: Basic search engine optimization.
- Improved Menu Plugin. Added ability to manage items categories.
- 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.
- Added Twitter Bootstrap icons.
- Dir Helper: Fixed size() method.
- New Default Theme: built with best frontend optimization practice.
- Options API: Updated get() method. Return empty string if option value doesnt exists.
- CSS variables: Added - @theme_site_url @theme_admin_url
- CSS variables: Deleted - @theme_url
- Themes Plugin: Added ability to create/edit/clone JavaScripts. Added 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.
- Plugin API: Fixed Javascript and Stylesheet class.
- Plugin API: Added ability to set view file from current theme folder.
- New options theme_admin_name, theme_site_name, users_frontend_registration added.
- Form Helper: Custom Macros - added
- Install Script Improvments.
- Monstra Localization Improvments. Added locales array to I18N class.
- Translates updates.
- 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

View File

@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2012 - 2016 Monstra Content Management
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,34 +0,0 @@
# Monstra
Monstra is a modern and lightweight Content Management System.
[![Join the chat at https://gitter.im/monstra-cms/monstra](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/monstra-cms/monstra?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## System Requirements
Operation system: Unix, Linux, Windows, Mac OS
Middleware: PHP 5.3.2 or higher with PHP's [SimpleXML module](http://php.net/simplexml) and [Multibyte String module](http://php.net/mbstring)
Webserver: Apache with [Mod Rewrite](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) or Ngnix with [Rewrite Module](http://wiki.nginx.org/HttpRewriteModule)
## Steps to Install
1. [Download the latest version.](http://monstra.org/download)
2. Unzip the contents to a new folder on your local computer.
3. Upload that whole folder with an FTP client to your host.
4. You may also need to recursively CHMOD the folder /storage/, /tmp/, /backups/ and /public/ to 755(or 777) if your host doesn't set it implicitly.
5. Also you may also need to recursively CHMOD the /install.php, /.htaccess and /sitemap.xml to 755(or 777) if your host doesn't set it implicitly.
6. Type http://example.org/install.php in the browser.
## Contributing
1. Help on the [Forum.](http://forum.monstra.org)
2. Donate to keep Monstra free. We will add you to Monstra [Sponsors Page.](http://monstra.org/contribute/sponsors)
3. Develop a new plugin.
4. Create a new theme.
5. Find and [report issues.](https://github.com/monstra-cms/monstra/issues)
6. Link back to [Monstra](http://monstra.org).
## Links
- [Site](http://monstra.org)
- [Forum](http://forum.monstra.org)
- [Documentation](http://monstra.org/documentation)
- [Github Repository](https://github.com/monstra-cms/monstra)
## License
See [LICENSE](https://github.com/monstra-cms/monstra/blob/master/LICENSE.md)

View File

@@ -1,189 +0,0 @@
<?php
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(str_replace(array('admin'), array(''), dirname(__FILE__)), '\\/'));
define('BACKEND', true);
define('MONSTRA_ACCESS', true);
// Load Monstra engine _init.php file
require_once ROOT. DS .'engine'. DS .'_init.php';
// Errors var when users login failed
$login_error = '';
// Get users Table
$users = new Table('users');
// Admin login
if (Request::post('login_submit')) {
if (Cookie::get('login_attempts') && Cookie::get('login_attempts') >= 5) {
$login_error = __('You are banned for 10 minutes. Try again later', 'users');
} else {
$user = $users->select("[login='" . trim(Request::post('login')) . "']", null);
if (count($user) !== 0) {
if ($user['login'] == Request::post('login')) {
if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) {
if ($user['role'] == 'admin' || $user['role'] == 'editor') {
Session::set('admin', true);
Session::set('user_id', (int) $user['id']);
Session::set('user_login', (string) $user['login']);
Session::set('user_role', (string) $user['role']);
Session::set('user_email', (string) $user['email']);
Request::redirect('index.php');
}
} else {
$login_error = __('Wrong <b>username</b> or <b>password</b>', 'users');
if (Cookie::get('login_attempts')) {
if (Cookie::get('login_attempts') < 5) {
$attempts = Cookie::get('login_attempts') + 1;
Cookie::set('login_attempts', $attempts, 600);
} else {
$login_error = __('You are banned for 10 minutes. Try again later', 'users');
}
} else {
Cookie::set('login_attempts', 1, 600);
}
}
}
} else {
$login_error = __('Wrong <b>username</b> or <b>password</b>', 'users');
if (Cookie::get('login_attempts')) {
if (Cookie::get('login_attempts') < 5) {
$attempts = Cookie::get('login_attempts') + 1;
Cookie::set('login_attempts', $attempts, 600);
} else {
$login_error = __('You are banned for 10 minutes. Try again later', 'users');
}
} else {
Cookie::set('login_attempts', 1, 600);
}
}
}
Notification::setNow('error', $login_error);
}
// Errors
$errors = array();
$site_url = Option::get('siteurl');
$site_name = Option::get('sitename');
$user_login = trim(Request::post('login'));
// Reset Password Form Submit
if (Request::post('reset_password_submit')) {
if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) {
$errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users');
}
if ($user_login == '') {
$errors['users_empty_field'] = __('Required field', 'users');
}
if ($user_login != '' && ! $users->select("[login='".$user_login."']")) {
$errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users');
}
if (count($errors) == 0) {
// Get user
$user = $users->select("[login='" . $user_login . "']", null);
// Generate new hash
$new_hash = Text::random('alnum', 12);
// Update user hash
$users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash));
$mail = new PHPMailer();
$mail->CharSet = 'utf-8';
$mail->ContentType = 'text/html';
$mail->SetFrom(Option::get('system_email'));
$mail->AddReplyTo(Option::get('system_email'));
$mail->AddAddress($user['email'], $user['login']);
$mail->Subject = __('Your login details for :site_name', 'users', array(':site_name' => $site_name));
$mail->MsgHTML(View::factory('box/emails/views/emails/email_layout')
->assign('site_url', $site_url)
->assign('site_name', $site_name)
->assign('user_id', $user['id'])
->assign('user_login', $user['login'])
->assign('new_hash', $new_hash)
->assign('email_template', 'reset-password')
->render());
$mail->Send();
// Set notification
Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name)));
Notification::set('reset_password', 'reset_password');
// Redirect to password-reset page
Request::redirect(Site::url().'/admin');
}
Notification::setNow('reset_password', 'reset_password');
}
// If admin user is login = true then set is_admin = true
if (Session::exists('admin') && Session::get('admin') == true) {
$is_admin = true;
} else {
$is_admin = false;
}
// 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')) {
$area = Request::get('id');
} else {
Request::redirect(Site::url().'/admin/index.php?id=dashboard');
}
$plugins_registered = Plugin::$plugins;
foreach ($plugins_registered as $plugin) {
$plugins_registered_areas[] = $plugin['id'];
}
// Show plugins admin area only for registered plugins
if (in_array($area, $plugins_registered_areas)) {
$plugin_admin_area = true;
} else {
$plugin_admin_area = false;
}
// Backend pre render
Action::run('admin_pre_render');
// Display admin template
require 'themes'. DS . Option::get('theme_admin_name') . DS . 'index.template.php';
// Backend post render
Action::run('admin_post_render');
} else {
// Display login template
require 'themes'. DS . Option::get('theme_admin_name') . DS . 'login.template.php';
}
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();

View File

@@ -1,661 +0,0 @@
/************************************
Monstra
default.css
*************************************
CONTENTS
1. GENERAL
2. COMPONENTS
3. MEDIA QUERIES
*************************************
1. GENERAL
*************************************/
@font-face {
font-family: 'Glyphicons Halflings';
src: url('@site_url/public/assets/fonts/glyphicons-halflings-regular.eot');
src: url('@site_url/public/assets/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
url('@site_url/public/assets/fonts/glyphicons-halflings-regular.woff') format('woff'),
url('@site_url/public/assets/fonts/glyphicons-halflings-regular.ttf') format('truetype'),
url('@site_url/public/assets/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
body {
background: #fafafa;
}
h1,
h2,
h3,
h4,
h5 {
color: #222;
}
.error-none {
display: none;
}
.error-field {
border: 1px solid red!important;
}
.error-message {
color: red;
}
a.btn-expand {
font-size: 14px;
font-weight: bold;
padding-right: 4px;
padding-left: 4px;
text-decoration: none;
color: #333;
}
.btn:active,
.btn.active {
outline: 0;
background-image: none;
box-shadow: none;
}
.login-footer,
.login-footer a {
font-size: 12px;
color: #777;
}
footer {
margin-top: 40px;
}
footer,
footer a {
font-size: 12px;
color: #777;
}
footer span {
padding-top: 10px;
border-top: 1px solid #e0e0e0;
}
footer .highlight {
color: #333;
}
/*************************************
2. COMPONENTS
*************************************/
/* Well */
.well {
color: #555;
border: none;
border-radius: 0px;
background: #fff;
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,.13);
box-shadow: 0 1px 3px rgba(0,0,0,.13);
-webkit-font-smoothing: subpixel-antialiased;
}
.dashboard-well {
padding-top: 6px;
padding-bottom: 6px;
}
.dashboard-well a.welcome-back {
font-size: 16px;
padding-left: 0;
text-decoration: none;
color: #333;
}
/* Admin Form */
.form-signin {
max-width: 400px;
}
.form-signin {
margin-top: 40px;
}
.form-signin .administration-area,
.form-signin .reset-password-area {
margin-top: 40px;
}
/* Dropdown Menu */
.dropdown-menu .divider {
background-color: #555454;
}
.dropdown-menu {
border: 1px solid #333;
background: #333;
box-shadow: none;
}
.dropdown-menu > li > a {
color: #eee;
}
/* Navbar */
.navbar-inverse .navbar-nav > li > a {
color: #eee;
}
.navbar-inverse {
background: #222;
}
.navbar-default {
border-radius: 0px;
}
ul.navbar-nav {
min-height: 60px;
}
.navbar-nav > li {
min-height: 60px;
}
.navbar-nav > li > a {
line-height: 30px;
}
.navbar-brand {
font-size: 24px;
line-height: inherit;
padding: 13px 15px;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
background: #333;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
background: #333;
}
a.navbar-brand {
font-weight: bold;
color: #fafafa!important;
}
.navbar-nav .dropdown-menu {
padding-top: 0;
padding-bottom: 0;
}
.navbar-nav .dropdown-menu > li > a {
padding: 7px 20px;
}
.nav > li > a {
padding-top: 15px;
padding-right: 20px;
padding-bottom: 15px;
padding-left: 20px;
}
.nav > li > a > img {
width: 28px;
height: 28px;
margin: 0 0 0 4px;
border: 1px solid #888;
}
/* Flat Elements */
.form-control,
.btn,
.dropdown-menu,
.modal-content,
.badge,
.label,
.input-group-addon,
.alert,
.tooltip,
.tooltip-inner,
pre,
code {
border-radius: 0px;
}
.badge,
.tooltip,
.tooltip-inner,
.label,
pre,
code {
font-weight: normal;
text-shadow: none;
}
pre {
border: none;
}
/* Inputs */
select,
textarea,
input[type="text"],
input[type="password"],
input[type="datetime"],
input[type="datetime-local"],
input[type="date"],
input[type="month"],
input[type="time"],
input[type="week"],
input[type="number"],
input[type="email"],
input[type="url"],
input[type="search"],
input[type="tel"],
input[type="color"],
.form-control,
.uneditable-input {
color: #3c3c3c;
border-color: #d0d0d0;
background-color: #fff;
}
select:focus,
textarea:focus,
input[type="text"]:focus,
input[type="password"]:focus,
input[type="datetime"]:focus,
input[type="datetime-local"]:focus,
input[type="date"]:focus,
input[type="month"]:focus,
input[type="time"]:focus,
input[type="week"]:focus,
input[type="number"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="search"]:focus,
input[type="tel"]:focus,
input[type="color"]:focus,
.form-control:focus,
.uneditable-input:focus {
border-color: #aaaaaa;
-webkit-box-shadow: 0 0 8px #dce1e5;
-moz-box-shadow: 0 0 8px #dce1e5;
box-shadow: 0 0 8px #dce1e5;
}
/* Datapicker */
.datapicker {
width: 200px;
}
/* Breadcrumb */
.breadcrumb {
border-radius: 0px;
background: #fff;
}
/* Tabs */
.nav-tabs > li > a {
border-radius: 0px;
}
.tab-page {
background: #fff;
}
.tab-pane > table {
border-top: none!important;
}
.tab-content {
overflow: visible;
}
.tab-page {
padding: 20px 10px 10px;
border-right: 1px solid #dddddd;
border-bottom: 1px solid #dddddd;
border-left: 1px solid #dddddd;
}
/* Tables */
table {
max-width: 100%;
border-spacing: 0;
border-collapse: collapse;
background-color: transparent;
}
.table {
width: 100%;
margin-bottom: 18px;
}
.table th,
.table td {
line-height: 18px;
padding: 8px;
text-align: left;
border-top: 1px solid #dddddd;
background: #fff;
}
.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-collapse: separate;
border: 1px solid #dddddd;
border-left: 0;
*border-collapse: collapsed;
}
.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 tr th {
font-weight: bold;
background-color: #fff;
}
.table-bordered thead:first-child tr:first-child > th:first-child,
.table-bordered tbody:first-child tr:first-child > td:first-child {
border-top-left-radius: 0px;
}
.table-bordered thead:last-child tr:last-child > th:last-child,
.table-bordered tbody:last-child tr:last-child > td:last-child {
border-top-right-radius: 0px;
}
.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 {
height: 50px;
border-left: none;
}
.table-bordered > thead > tr {
height: 45px;
}
td,
th {
display: table-cell;
vertical-align: inherit!important;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 0;
border-bottom: 1px solid #ccc;
}
.vertical-align {
display: table;
width: 100%;
}
.vertical-align > div {
display: table-cell;
vertical-align: middle;
}
.vertical-align > div > h1,
.vertical-align > div > h2,
.vertical-align > div > h3,
.vertical-align > div > h4,
.vertical-align > div > h5 {
margin-top: 10px;
margin-bottom: 10px;
}
.margin-top-1 {
margin-top: 1em;
}
.margin-top-2 {
margin-top: 2em;
}
.margin-bottom-1 {
margin-bottom: 1em;
}
.margin-bottom-2 {
margin-bottom: 2em;
}
/* Editor */
#editor_area {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.428571429;
height: 400px!important;
padding: 6px 9px;
color: #555;
border: 1px solid #ccc;
}
.markItUpHeader ul li {
padding: 5px;
}
.markItUpHeader ul .markItUpSeparator {
display: none;
}
.modal-header {
border-bottom: 1px solid #f3f3f3;
}
.modal-header .close {
font-size: 26px;
}
.modal-footer {
border-top: 1px solid #f3f3f3;
}
.drop-file-here {
margin-left: 4px;
padding: 5px 40px;
color: #ccc;
border: 3px dashed #d5d5d5;
background: #ccc;
background: #f7f7f7;
}
.modal-backdrop {
background-color: #000;
}
.modal-backdrop.in {
opacity: 0.8;
}
.modal-content {
border: none;
box-shadow: none;
}
#readme .modal-dialog {
width: 70%;
}
#readme .modal-body {
padding-top: 0px;
}
#Choco_container_via {
display: none;
}
/*************************************
3. MEDIA QUERIES
*************************************/
@media (max-width: 480px) {
/* MarkItUp */
.markItUpButton11,
.markItUpButton12,
.markItUpButton13,
.markItUpButton14,
.markItUpButton15,
.markItUpButton16,
.markItUpButton17,
.markItUpButton18 {
display: none;
}
.markItUpSeparator {
display: none;
}
/* Dashboard */
.dashboard-well .col-xs-6 {
width: 100%;
}
.dashboard-well .col-xs-6 .pull-right {
float: left!important;
}
.btn-phone {
width: 100%;
}
.row-phone {
display: block!important;
width: 100%!important;
text-align: left!important;
}
/* Users */
.users-btns > div {
display: block;
width: 100%;
margin-top: 10px;
text-align: left;
}
.users-btns > div:nth-child(2) {
margin-top: 15px;
}
.page-users .btn-cancel {
margin-bottom: 20px;
}
}
@media (max-width: 768px) {
.nav > li > a {
padding: 15px 9px!important;
}
}
@media (max-width: 320px) {
.mobile-nav-tabs .nav-tabs > li {
width: 100%;
height: 46px;
margin: 0px;
}
.mobile-nav-tabs .nav-tabs > li > a {
border: 0;
background: #fff;
}
.mobile-nav-tabs .nav-tabs > li.active > a,
.mobile-nav-tabs .nav-tabs > li.active > a:hover,
.mobile-nav-tabs .nav-tabs > li.active > a:focus {
color: #fff;
border: 0;
background-color: #428bca;
}
.mobile-nav-tabs .nav-tabs {
margin-top: 10px;
margin-bottom: 10px;
border: 0;
}
.mobile-nav-tabs .tab-pane > table {
border-top: 1px solid #ddd!important;
}
}

View File

@@ -1,164 +0,0 @@
<?php if ( ! defined('MONSTRA_ACCESS')) exit('No direct script access allowed'); ?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-dns-prefetch-control" content="on">
<link rel="dns-prefetch" href="<?php echo Site::url(); ?>" />
<link rel="dns-prefetch" href="//www.google-analytics.com" />
<link rel="dns-prefetch" href="//www.gravatar.com" />
<title>Monstra :: <?php echo __('Administration', 'system'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Monstra Admin Area" />
<link rel="icon" href="<?php echo Option::get('siteurl'); ?>/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo Option::get('siteurl'); ?>/favicon.ico" type="image/x-icon" />
<!-- Styles -->
<link rel="stylesheet" href="<?php echo Site::url(); ?>/public/assets/css/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="<?php echo Site::url(); ?>/public/assets/css/messenger.css" type="text/css" />
<link rel="stylesheet" href="<?php echo Site::url(); ?>/public/assets/css/messenger-theme-flat.css" type="text/css" />
<?php Stylesheet::add('public/assets/css/chocolat.css', 'backend', 2); ?>
<?php Stylesheet::add('public/assets/css/bootstrap-fileupload.css', 'backend', 3); ?>
<?php Stylesheet::add('public/assets/css/icheck-blue.css', 'backend', 4); ?>
<?php Stylesheet::add('admin/themes/default/css/default.css', 'backend', 5); ?>
<?php Stylesheet::load(); ?>
<!-- JavaScripts -->
<script src="<?php echo Site::url(); ?>/public/assets/js/jquery.min.js"></script>
<script src="<?php echo Site::url(); ?>/public/assets/js/bootstrap.min.js"></script>
<script src="<?php echo Site::url(); ?>/public/assets/js/messenger.min.js"></script>
<script src="<?php echo Site::url(); ?>/public/assets/js/icheck.min.js"></script>
<?php Javascript::add('public/assets/js/jquery.chocolat.js', 'backend', 3); ?>
<?php Javascript::add('public/assets/js/bootstrap-fileupload.js', 'backend', 4); ?>
<?php Javascript::add('admin/themes/default/js/default.js', 'backend', 5); ?>
<?php Javascript::load(); ?>
<?php Action::run('admin_header'); ?>
<script>
$(document).ready(function() {
$('.chocolat').Chocolat({
overlayColor : '#000',
leftImg : "<?php echo Option::get('siteurl'); ?>/public/assets/img/chocolat/left.gif",
rightImg : "<?php echo Option::get('siteurl'); ?>/public/assets/img/chocolat/right.gif",
closeImg : "<?php echo Option::get('siteurl'); ?>/public/assets/img/chocolat/close.gif",
loadingImg : "<?php echo Option::get('siteurl'); ?>/public/assets/img/chocolat/loading.gif"
});
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%'
});
});
</script>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7/html5shiv.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js"></script>
<![endif]-->
</head>
<body class="page-<?php echo Request::get('id'); ?>">
<nav class="navbar navbar-default navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo Site::url(); ?>/admin/index.php?id=dashboard">MONSTRA</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li<?php if (Request::get('id') == 'dashboard') { ?> class="active"<?php } ?>><a href="<?php echo Site::url(); ?>/admin/index.php?id=dashboard"><?php echo __('Dashboard', 'dashboard'); ?></a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo __('Content', 'pages'); ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php Navigation::draw('content'); ?>
</ul>
</li>
<?php if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo __('Extends', 'system'); ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php Navigation::draw('extends'); ?>
</ul>
</li>
<?php } ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo __('System', 'system'); ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php Navigation::draw('system'); ?>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo __('Help', 'system'); ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://monstra.org/documentation" target="_blank"><?php echo __('Documentation', 'system'); ?></a></li>
<?php if (Option::get('language') == 'ru') { ?>
<li><a href="http://ru.forum.monstra.org" target="_blank"><?php echo __('Official Support Forum', 'system'); ?></a></li>
<?php } else { ?>
<li><a href="http://forum.monstra.org" target="_blank"><?php echo __('Official Support Forum', 'system'); ?></a></li>
<?php } ?>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="<?php echo Site::url(); ?>" target="_blank"><?php echo __('View Site', 'system'); ?></a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo Session::get('user_login'); ?> <img src="<?php echo Users::getGravatarURL(Session::get('user_email'), 28); ?>" alt=""> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="<?php echo Site::url(); ?>/admin/index.php?id=users&action=edit&user_id=<?php echo Session::get('user_id'); ?>"><?php echo __('Profile', 'users')?></a></li>
<li><a href="<?php echo Site::url(); ?>/admin/?logout=do"><?php echo __('Log Out', 'users'); ?></a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<?php
// Monstra Notifications
Notification::get('success') AND Alert::success(Notification::get('success'));
Notification::get('warning') AND Alert::warning(Notification::get('warning'));
Notification::get('error') AND Alert::error(Notification::get('error'));
?>
<div id="update-monstra"></div>
<div><?php Action::run('admin_pre_template'); ?></div>
<div>
<?php
if ($plugin_admin_area) {
if (is_callable(ucfirst(Plugin::$plugins[$area]['id']).'Admin::main')) {
call_user_func(ucfirst(Plugin::$plugins[$area]['id']).'Admin::main');
} else {
echo '<div class="message-error">'.__('Plugin main admin function does not exist', 'system').'</div>';
}
} else {
echo '<div class="message-error">'.__('Plugin does not exist', 'system').'</div>';
}
?>
</div>
<div><?php Action::run('admin_post_template'); ?></div>
</div>
<div class="margin-top-1 margin-bottom-1 hidden-md"></div>
<footer class="container visible-md visible-lg">
<p class="pull-right">
<span>
<a href="http://monstra.org" target="_blank">Monstra</a> was made by <a href="http://awilum.github.io" target="_blank" class="highlight">Sergey Romanenko</a> and is maintained by <a href="https://github.com/monstra-cms/monstra/network/members" target="_blank" class="highlight">Monstra Community</a> / © 2012 - 2016 <a href="http://monstra.org/about/license" target="_blank">Monstra</a> <?php echo __('Version', 'system'); ?> <?php echo Monstra::VERSION; ?>
</span>
</p>
</footer>
</body>
</html>

View File

@@ -1,23 +0,0 @@
/**
* Monstra JS module
*
* This source file is part of the Monstra Engine. More information,
* documentation and tutorials can be found at http://monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Confirm delete */
function confirmDelete(msg){var data=confirm(msg+" ?"); return data;}
/* Messanger */
Messenger.options = {
extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right',
theme: 'flat'
}

View File

@@ -1,135 +0,0 @@
<?php if ( ! defined('MONSTRA_ACCESS')) exit('No direct script access allowed'); ?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monstra :: <?php echo __('Administration', 'system'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Monstra Admin Area">
<link rel="icon" href="<?php echo Option::get('siteurl'); ?>/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo Option::get('siteurl'); ?>/favicon.ico" type="image/x-icon" />
<!-- Styles -->
<link rel="stylesheet" href="<?php echo Site::url(); ?>/public/assets/css/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="<?php echo Site::url(); ?>/public/assets/css/messenger.css" type="text/css" />
<link rel="stylesheet" href="<?php echo Site::url(); ?>/public/assets/css/messenger-theme-flat.css" type="text/css" />
<?php Stylesheet::add('public/assets/css/bootstrap-lightbox.css', 'backend', 2); ?>
<?php Stylesheet::add('public/assets/css/bootstrap-fileupload.css', 'backend', 3); ?>
<?php Stylesheet::add('admin/themes/default/css/default.css', 'backend', 5); ?>
<?php Stylesheet::load(); ?>
<!-- JavaScripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="<?php echo Site::url(); ?>/public/assets/js/bootstrap.min.js"></script>
<script src="<?php echo Site::url(); ?>/public/assets/js/messenger.min.js"></script>
<script src="<?php echo Site::url(); ?>/public/assets/js/messenger-theme-flat.js"></script>
<?php Javascript::add('public/assets/js/bootstrap-lightbox.js', 'backend', 3); ?>
<?php Javascript::add('public/assets/js/bootstrap-fileupload.js', 'backend', 4); ?>
<?php Javascript::add('admin/themes/default/js/default.js', 'backend', 5); ?>
<?php Javascript::load(); ?>
<script type="text/javascript">
$().ready(function () {
<?php if (Notification::get('reset_password') == 'reset_password') { ?>
$('.reset-password-area, .administration-btn').show();
$('.administration-area, .reset-password-btn').hide();
<?php } else { ?>
$('.reset-password-area, .administration-btn').hide();
$('.administration-area, .reset-password-btn').show();
<?php } ?>
$('.reset-password-btn').click(function() {
$('.reset-password-area, .administration-btn').show();
$('.administration-area, .reset-password-btn').hide();
});
$('.administration-btn').click(function() {
$('.reset-password-area, .administration-btn').hide();
$('.administration-area, .reset-password-btn').show();
});
});
</script>
<?php Action::run('admin_header'); ?>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7/html5shiv.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js"></script>
<![endif]-->
</head>
<body class="login-body">
<?php
// Monstra Notifications
Notification::get('success') AND Alert::success(Notification::get('success'));
Notification::get('warning') AND Alert::warning(Notification::get('warning'));
Notification::get('error') AND Alert::error(Notification::get('error'));
?>
<div class="container form-signin">
<div class="text-center"><a class="brand" href="<?php echo Option::get('siteurl'); ?>/admin"><img src="<?php echo Option::get('siteurl'); ?>/public/assets/img/monstra-logo-256px.png" alt="monstra" /></a></div>
<div class="administration-area well">
<div>
<form method="post">
<div class="form-group">
<label><?php echo __('Username', 'users'); ?></label>
<input class="form-control" name="login" type="text" />
</div>
<div class="form-group">
<label><?php echo __('Password', 'users'); ?></label>
<input class="form-control" name="password" type="password" />
</div>
<div class="form-group">
<input type="submit" name="login_submit" class="btn btn-primary" value="<?php echo __('Log In', 'users'); ?>" />
</div>
</form>
</div>
</div>
<div class="reset-password-area well">
<div>
<form method="post">
<div class="form-group">
<label><?php echo __('Username', 'users'); ?></label>
<input name="login" class="form-control" type="text" value="<?php echo $user_login; ?>" />
</div>
<?php if (Option::get('captcha_installed') == 'true') { ?>
<div class="form-group">
<label><?php echo __('Captcha', 'users'); ?></label>
<input type="text" name="answer" class="form-control">
<br>
<?php CryptCaptcha::draw(); ?>
</div>
<?php } ?>
<br>
<?php
if (count($errors) > 0) {
foreach ($errors as $error) {
Alert::error($error);
}
}
?>
<div class="form-group">
<input type="submit" name="reset_password_submit" class="btn btn-primary" value="<?php echo __('Send New Password', 'users')?>" />
</div>
</form>
</div>
</div>
</div>
<div class="login-footer">
<div class="text-center">
<a href="<?php echo Option::get('siteurl'); ?>"><?php echo __('Back to Website', 'system');?></a> -
<a class="reset-password-btn" href="javascript:;"><?php echo __('Forgot your password ?', 'system');?></a>
<a class="administration-btn" href="javascript:;"><?php echo __('Log In', 'users');?></a>
</div>
<div class="text-center">
© 2012 - 2016 <a href="http://monstra.org/about/license" target="_blank">Monstra</a> <?php echo __('Version', 'system'); ?> <?php echo Monstra::VERSION; ?>
</div>
</div>
</body>
</html>

View File

View File

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

View File

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

View File

@@ -1,101 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Alert
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Show success message
*
* <code>
* Alert::success('Message here...');
* </code>
*
* @param string $message Message
* @param integer $seconds Seconds
*/
public static function success($message, $seconds = 3)
{
// Redefine vars
$message = (string) $message;
$seconds = (int) $seconds;
echo '<script type="text/javascript">
Messenger().post({
type: "success",
message : "'.$message.'",
hideAfter: '.$seconds.'
});
</script>';
}
/**
* Show warning message
*
* <code>
* Alert::warning('Message here...');
* </code>
*
* @param string $message Message
* @param integer $seconds Seconds
*/
public static function warning($message, $seconds = 3)
{
// Redefine vars
$message = (string) $message;
$seconds = (int) $seconds;
echo '<script type="text/javascript">
Messenger().post({
type: "info",
message : "'.$message.'",
hideAfter: '.$seconds.'
});
</script>';
}
/**
* Show error message
*
* <code>
* Alert::error('Message here...');
* </code>
*
* @param string $message Message
* @param integer $seconds Seconds
*/
public static function error($message, $seconds = 3)
{
// Redefine vars
$message = (string) $message;
$seconds = (int) $seconds;
echo '<script type="text/javascript">
Messenger().post({
type: "error",
message : "'.$message.'",
hideAfter: '.$seconds.'
});
</script>';
}
}

View File

@@ -1,340 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Monstra
{
/**
* An instance of the Monstra class
*
* @var core
*/
protected static $instance = null;
/**
* Common environment type constants for consistency and convenience
*/
const PRODUCTION = 1;
const STAGING = 2;
const TESTING = 3;
const DEVELOPMENT = 4;
/**
* The version of Monstra
*/
const VERSION = '3.0.4';
/**
* Monstra environment
*
* @var string
*/
public static $environment = Monstra::PRODUCTION;
/**
* Monstra environment names
*
* @var array
*/
public static $environment_names = array(
Monstra::PRODUCTION => 'production',
Monstra::STAGING => 'staging',
Monstra::TESTING => 'testing',
Monstra::DEVELOPMENT => 'development',
);
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Protected Construct
*/
protected function __construct()
{
/**
* Load core defines
*/
Monstra::loadDefines();
/**
* Compress HTML with gzip
*/
if (MONSTRA_GZIP) {
if (! ob_start("ob_gzhandler")) {
ob_start();
}
} else {
ob_start();
}
/**
* Send default header and set internal encoding
*/
header('Content-Type: text/html; charset=UTF-8');
function_exists('mb_language') and mb_language('uni');
function_exists('mb_regex_encoding') and mb_regex_encoding('UTF-8');
function_exists('mb_internal_encoding') and mb_internal_encoding('UTF-8');
/**
* Gets the current configuration setting of magic_quotes_gpc
* and kill magic quotes
*/
if (get_magic_quotes_gpc()) {
function stripslashesGPC(&$value)
{
$value = stripslashes($value);
}
array_walk_recursive($_GET, 'stripslashesGPC');
array_walk_recursive($_POST, 'stripslashesGPC');
array_walk_recursive($_COOKIE, 'stripslashesGPC');
array_walk_recursive($_REQUEST, 'stripslashesGPC');
}
/**
* Set Gelato Display Errors to False for Production environment.
*/
if (Monstra::$environment == Monstra::PRODUCTION) {
define('GELATO_DEVELOPMENT', false);
}
/**
* Define Monstra Folder for Gelato Logs
*/
define('GELATO_LOGS_PATH', LOGS);
/**
* Include Gelato Library
*/
include ROOT . DS . 'libraries'. DS .'Gelato'. DS .'Gelato.php';
/**
* Map Monstra Engine Directory
*/
ClassLoader::directory(ROOT . DS . 'engine' . DS);
/**
* Map all Monstra Classes
*/
ClassLoader::mapClasses(array(
// Site Modules
'Security' => ROOT . DS .'engine'. DS .'Security.php',
'Uri' => ROOT . DS .'engine'. DS .'Uri.php',
'Site' => ROOT . DS .'engine'. DS .'Site.php',
'Alert' => ROOT . DS .'engine'. DS .'Alert.php',
// XMLDB API
'XML' => ROOT . DS .'engine'. DS .'Xmldb'. DS .'XML.php',
'DB' => ROOT . DS .'engine'. DS .'Xmldb'. DS .'DB.php',
'Table' => ROOT . DS .'engine'. DS .'Xmldb'. DS .'Table.php',
// Plugin API
'Plugin' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Plugin.php',
'Frontend' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Frontend.php',
'Backend' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Backend.php',
'Action' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Action.php',
'Filter' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Filter.php',
'View' => ROOT . DS .'engine'. DS .'Plugin'. DS .'View.php',
'I18n' => ROOT . DS .'engine'. DS .'Plugin'. DS .'I18n.php',
'Stylesheet' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Stylesheet.php',
'Javascript' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Javascript.php',
'Navigation' => ROOT . DS .'engine'. DS .'Plugin'. DS .'Navigation.php',
// Option API
'Option' => ROOT . DS .'engine'. DS .'Option.php',
// Shortcode API
'Shortcode' => ROOT . DS .'engine'. DS .'Shortcode.php',
// Idiorm
'ORM' => ROOT . DS .'libraries'. DS . 'Idiorm'. DS .'ORM.php',
// PHPMailer
'PHPMailer' => ROOT . DS .'libraries'. DS . 'PHPMailer'. DS .'PHPMailer.php',
));
/**
* Start session
*/
Session::start();
/**
* Init Idiorm
*/
if (defined('MONSTRA_DB_DSN')) {
ORM::configure(MONSTRA_DB_DSN);
ORM::configure('username', MONSTRA_DB_USER);
ORM::configure('password', MONSTRA_DB_PASSWORD);
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
/**
* Auto cleanup if DEVELOPMENT environment
*/
if (Monstra::$environment == Monstra::DEVELOPMENT) {
Monstra::cleanTmp();
}
/**
* Set Cache dir
*/
Cache::configure('cache_dir', CACHE);
/**
* 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 default
*/
Monstra::loadPluggable();
/**
* Init I18n
*/
I18n::init(Option::get('language'));
/**
* Init Plugins API
*/
Plugin::init();
/**
* Init Notification service
*/
Notification::init();
/**
* Init site module
*/
if (! BACKEND) {
Site::init();
}
}
/**
* Load Defines
*/
protected static function loadDefines()
{
$root_defines = ROOT . DS . 'boot' . DS . 'defines.php';
$environment_defines = ROOT . DS . 'boot' . DS . Monstra::$environment_names[Monstra::$environment] . DS . 'defines.php';
$monstra_defines = ROOT . DS . 'engine' . DS . 'boot' . DS . 'defines.php';
if (file_exists($root_defines)) {
include $root_defines;
} elseif (file_exists($environment_defines)) {
include $environment_defines;
} elseif (file_exists($monstra_defines)) {
include $monstra_defines;
} else {
throw new RuntimeException("The defines file does not exist.");
}
}
/**
* Load Pluggable
*/
protected static function loadPluggable()
{
$root_pluggable = ROOT . DS . 'boot';
$environment_pluggable = ROOT . DS . 'boot' . DS . Monstra::$environment_names[Monstra::$environment];
$monstra_pluggable = ROOT . DS . 'engine' . DS . 'boot';
if (file_exists($root_pluggable . DS . 'filters.php')) {
include $root_pluggable . DS . 'filters.php';
} elseif (file_exists($environment_pluggable . DS . 'filters.php')) {
include $environment_pluggable . DS . 'filters.php';
} elseif (file_exists($monstra_pluggable . DS . 'filters.php')) {
include $monstra_pluggable . DS . 'filters.php';
} else {
throw new RuntimeException("The pluggable filters.php file does not exist.");
}
if (file_exists($root_pluggable . DS . 'actions.php')) {
include $root_pluggable . DS . 'actions.php';
} elseif (file_exists($environment_pluggable . DS . 'actions.php')) {
include $environment_pluggable . DS . 'actions.php';
} elseif (file_exists($monstra_pluggable . DS . 'actions.php')) {
include $monstra_pluggable . DS . 'actions.php';
} else {
throw new RuntimeException("The pluggable actions.php file does not exist.");
}
if (file_exists($root_pluggable . DS . 'shortcodes.php')) {
include $root_pluggable . DS . 'shortcodes.php';
} elseif (file_exists($environment_pluggable . DS . 'shortcodes.php')) {
include $environment_pluggable . DS . 'shortcodes.php';
} elseif (file_exists($monstra_pluggable . DS . 'shortcodes.php')) {
include $monstra_pluggable . DS . 'shortcodes.php';
} else {
throw new RuntimeException("The pluggable shortcodes.php file does not exist.");
}
}
/**
* Clean Monstra TMP folder.
*/
public static function cleanTmp()
{
// Cleanup minify
if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) {
foreach ($files as $file) {
File::delete(MINIFY . DS . $file);
}
}
// Cleanup cache
if (count($namespaces = Dir::scan(CACHE)) > 0) {
foreach ($namespaces as $namespace) {
Dir::delete(CACHE . DS . $namespace);
}
}
}
/**
* Initialize Monstra Engine
*
* @return Monstra
*/
public static function init()
{
if (! isset(self::$instance)) {
self::$instance = new Monstra();
}
return self::$instance;
}
}

View File

@@ -1,178 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Option
{
/**
* Options
*
* @var array
*/
protected static $options = null;
/**
* An instance of the Option class
*
* @var option
*/
protected static $instance = null;
/**
* Initializing options
*
* @param string $name Options file
*/
public static function init()
{
if (! isset(self::$instance)) {
self::$instance = new Option();
}
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Construct
*/
protected function __construct()
{
Option::$options = new Table('options');
}
/**
* Add a new option
*
* <code>
* Option::add('pages_limit', 10);
* Option::add(array('pages_count' => 10, 'pages_default' => 'home'));
* </code>
*
* @param mixed $option Name of option to add.
* @param mixed $value Option value.
* @return boolean
*/
public static function add($option, $value = null)
{
if (is_array($option)) {
foreach ($option as $k => $v) {
$_option = Option::$options->select('[name="'.$k.'"]', null);
if (count($_option) == 0) {
Option::$options->insert(array('name' => $k, 'value' => $v));
}
}
} else {
$_option = Option::$options->select('[name="'.$option.'"]', null);
if (count($_option) == 0) {
return Option::$options->insert(array('name' => $option, 'value' => $value));
}
}
}
/**
* Update option value
*
* <code>
* Option::update('pages_limit', 12);
* Option::update(array('pages_count' => 10, 'pages_default' => 'home'));
* </code>
*
* @param mixed $option Name of option to update.
* @param mixed $value Option value.
* @return boolean
*/
public static function update($option, $value = null)
{
if (is_array($option)) {
foreach ($option as $k => $v) {
Option::$options->updateWhere('[name="'.$k.'"]', array('value' => $v));
}
} else {
return Option::$options->updateWhere('[name="'.$option.'"]', array('value' => $value));
}
}
/**
* Get option value
*
* <code>
* $pages_limit = Option::get('pages_limit');
* if ($pages_limit == '10') {
* // do something...
* }
* </code>
*
* @param string $option Name of option to get.
* @return string
*/
public static function get($option)
{
// Redefine vars
$option = (string) $option;
// Select specific option
$option_name = Option::$options->select('[name="'.$option.'"]', null);
// Return specific option value
return isset($option_name['value']) ? $option_name['value'] : '';
}
/**
* Delete option
*
* <code>
* Option::delete('pages_limit');
* </code>
*
* @param string $option Name of option to delete.
* @return boolean
*/
public static function delete($option)
{
// Redefine vars
$option = (string) $option;
// Delete specific option
return Option::$options->deleteWhere('[name="'.$option.'"]');
}
/**
* Check if option exist
*
* <code>
* if (Option::exists('pages_limit')) {
* // do something...
* }
* </code>
*
* @param string $option Name of option to check.
* @return boolean
*/
public static function exists($option)
{
// Redefine vars
$option = (string) $option;
// Check if option exists
return (count(Option::$options->select('[name="'.$option.'"]', null)) > 0) ? true : false;
}
}

View File

@@ -1,113 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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.
*
* <code>
* // Hooks a function "newLink" on to a "footer" action.
* Action::add('footer', 'newLink', 10);
*
* function newLink() {
* echo '<a href="#">My link</a>';
* }
* </code>
*
* @param string $action_name Action name
* @param mixed $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' => $added_function,
'priority' => (int) $priority,
'args' => $args
);
}
/**
* Run functions hooked on a specific action hook.
*
* <code>
* // Run functions hooked on a "footer" action hook.
* Action::run('footer');
* </code>
*
* @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']);
}
}
}
}
}
}
}

View File

@@ -1,19 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Backend
{
public static function main()
{
}
}

View File

@@ -1,120 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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
*
* <code>
* Filter::apply('content', $content);
* </code>
*
* @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
*
* <code>
* Filter::add('content', 'replacer');
*
* function replacer($content) {
* return preg_replace(array('/\[b\](.*?)\[\/b\]/ms'), array('<strong>\1</strong>'), $content);
* }
* </code>
*
* @param string $filter_name The name of the filter to hook the $function_to_add to.
* @param mixed $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 = $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;
}
}

View File

@@ -1,40 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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 '';
}
}

View File

@@ -1,203 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class I18n
{
/**
* Locales array
*
* @var array
*/
public static $locales = array(
'ar' => 'العربية',
'bg' => 'Български',
'ca' => 'Català',
'cs' => 'Česky',
'da' => 'Dansk',
'de' => 'Deutsch',
'el' => 'Ελληνικά',
'en' => 'English',
'es' => 'Español',
'fa' => 'Farsi',
'fi' => 'Suomi',
'fr' => 'Français',
'gl' => 'Galego',
'ka-ge' => 'Georgian',
'hu' => 'Magyar',
'it' => 'Italiano',
'id' => 'Bahasa Indonesia',
'ja' => '日本語',
'lt' => 'Lietuvių',
'nl' => 'Nederlands',
'no' => 'Norsk',
'pl' => 'Polski',
'pt' => 'Português',
'pt-br' => 'Português do Brasil',
'ru' => 'Русский',
'sk' => 'Slovenčina',
'sl' => 'Slovenščina',
'sv' => 'Svenska',
'sr' => 'Srpski',
'tr' => 'Türkçe',
'uk' => 'Українська',
'zh-cn' => '简体中文',
);
/**
* 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.
*
* <code>
* $hello = I18n::find('Hello friends, my name is :name', 'namespace');
* <code>
*
* @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.
*
* <code>
* // Display a translated message
* echo __('Hello, world', 'namespace');
*
* // With parameter replacement
* echo __('Hello, :user', 'namespace', array(':user' => $username));
* </code>
*
* @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);
}

View File

@@ -1,137 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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
*
* <code>
* 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);
* <code>
*
* @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.'.Option::get('javascript_version').'.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');
if (BACKEND) {
// 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'])."\n";
}
}
file_put_contents($backend_site_js_path, $backend_buffer);
$backend_regenerate = false;
}
} else {
// 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'])."\n";
}
}
file_put_contents($frontend_site_js_path, $frontend_buffer);
$frontend_regenerate = false;
}
}
// Render
if (BACKEND) {
echo '<script type="text/javascript" src="'.Option::get('siteurl').'/tmp/minify/backend_site.minify.js?'.Option::get('javascript_version').'"></script>';
} else {
echo '<script type="text/javascript" src="'.Option::get('siteurl').'/tmp/minify/frontend_site.minify.'.Option::get('javascript_version').'.js"></script>'."\n";
}
}
}
/**
* javascriptVersionIncrement
*/
public static function javascriptVersionIncrement()
{
Option::update('javascript_version', (int) Option::get('javascript_version') + 1);
}
}

View File

@@ -1,202 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Navigation
{
/**
* Items
*
* @var array
*/
public static $items = array();
/**
* Navigation types
*/
const LEFT = 1;
const TOP = 2;
/**
* Add new item
*
* <code>
* // 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);
* <code>
*
* @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
*
* <code>
* Navigation::draw('content');
* Navigation::draw('top', Navigation::TOP);
* <code>
*
* @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 '<li><a '.$class.'href="index.php?id='.$item['id'].'">'.$item['name'].'</a></li>';
} else {
echo '<li><a target="_blank" href="'.$item['id'].'">'.$item['name'].'</a></li>';
}
}
}
} elseif ($type == Navigation::TOP) {
// Draw top navigation
foreach ($items as $item) {
if ($item['category'] == $category && $item['type'] == Navigation::TOP) {
if ($item['external'] == false) {
echo '<a class="btn btn-small btn-inverse" href="index.php?id='.$item['id'].'">'.$item['name'].'</a>'.Html::nbsp(2);
} else {
echo '<a target="_blank" class="btn btn-small btn-inverse" href="'.$item['id'].'">'.$item['name'].'</a>'.Html::nbsp(2);
}
}
}
}
}
/**
* Draw items
*
* <code>
* Navigation::draw('content');
* Navigation::draw('top', Navigation::TOP);
* <code>
*
* @param string $category Category
* @param integer $type Type. Default is LEFT
*/
public static function get($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 '<li><a '.$class.'href="index.php?id='.$item['id'].'">'.$item['name'].'</a></li>';
} else {
echo '<li><a target="_blank" href="'.$item['id'].'">'.$item['name'].'</a></li>';
}
}
}
} elseif ($type == Navigation::TOP) {
// Draw top navigation
foreach ($items as $item) {
if ($item['category'] == $category && $item['type'] == Navigation::TOP) {
if ($item['external'] == false) {
echo '<a class="btn btn-small btn-inverse" href="index.php?id='.$item['id'].'">'.$item['name'].'</a>'.Html::nbsp(2);
} else {
echo '<a target="_blank" class="btn btn-small btn-inverse" href="'.$item['id'].'">'.$item['name'].'</a>'.Html::nbsp(2);
}
}
}
}
}
/**
* Draw dropdown items
*
* <code>
* Navigation::getDropdown('content');
* <code>
*
* @param string $category Category
*/
public static function getDropdown($category)
{
// Sort items by priority
$items = Arr::subvalSort(Navigation::$items, 'priority');
// 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 = 'selected = "selected" ';
} 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 '<option '.$class.'rel="index.php?id='.$item['id'].'">'.$item['name'].'</option>';
}
}
}
}
}

View File

@@ -1,185 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Plugin
{
/**
* Plugins
*
* @var array
*/
public static $plugins = array();
/**
* Components
*
* @var array
*/
public static $components = array();
/**
* An instance of the Plugin class
*
* @var plugin
*/
protected static $instance = null;
/**
* Initializing plugins
*
* @return Plugin
*/
public static function init()
{
if (! isset(self::$instance)) {
self::$instance = new Plugin();
}
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Construct
*/
protected function __construct()
{
// Get plugins Table
$plugins = new Table('plugins');
// Select all plugins
$records = $plugins->select(null, 'all', null, array('location', '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
*
* <code>
* // Get admin for Blog plugin
* Plugin::admin('blog');
* </code>
*
* @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
*
* <code>
* // Register plugin
* Plugin::register( __FILE__,
* __('Blog'),
* __('Blog plugin'),
* '1.0.0',
* 'Awilum',
* 'http://example.org/',
* 'blog');
* </code>
*
* @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;
}
}
}

View File

@@ -1,153 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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
*
* <code>
* 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);
* <code>
*
* @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.'.Option::get('styles_version').'.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');
if (BACKEND) {
// 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, MinifyCSS::process($backend_buffer));
$backend_regenerate = false;
}
} else {
// 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, MinifyCSS::process($frontend_buffer));
$frontend_regenerate = false;
}
}
// Render
if (BACKEND) {
echo '<link rel="stylesheet" href="'.Option::get('siteurl').'/tmp/minify/backend_site.minify.css?'.Option::get('styles_version').'" type="text/css" />';
} else {
echo '<link rel="stylesheet" href="'.Option::get('siteurl').'/tmp/minify/frontend_site.minify.'.Option::get('styles_version').'.css" type="text/css" />'."\n";
}
}
}
/**
* 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);
}
/**
* stylesVersionIncrement
*/
public static function stylesVersionIncrement()
{
Option::update('styles_version', (int) Option::get('styles_version') + 1);
}
}

View File

@@ -1,236 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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.
*
* <code>
* // 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;
* </code>
*
* @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
// From current theme folder or from plugin folder
if (File::exists($theme_view_file = THEMES_SITE . DS . Site::theme() . DS . $view . '.view.php') && BACKEND == false) {
$this->view_file = $theme_view_file;
} else {
$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
*
* <code>
* // 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();
* </code>
*
* @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.
*
* <code>
* $view->assign('msg', 'Some message...');
* </code>
*
* @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.
*
* <code>
* // Get view
* $output = $view->render();
*
* // Display output
* echo $output;
* </code>
*
* @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.
*
* <code>
* $view->display();
* </code>
*
*/
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();
}
}

View File

@@ -1,239 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Security
{
/**
* Key name for token storage
*
* @var string
*/
protected static $token_name = 'security_token';
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Generate and store a unique token which can be used to help prevent
* [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
*
* <code>
* $token = Security::token();
* </code>
*
* You can insert this token into your forms as a hidden field:
*
* <code>
* echo Form::hidden('csrf', Security::token());
* </code>
*
* This provides a basic, but effective, method of preventing CSRF attacks.
*
* @param boolean $new force a new token to be generated?. Default is false
* @return string
*/
public static function token($new = false)
{
// Get the current token
$token = Session::get(Security::$token_name);
// Create a new unique token
if ($new === true or ! $token) {
// Generate a new unique token
$token = sha1(uniqid(mt_rand(), true));
// Store the new token
Session::set(Security::$token_name, $token);
}
// Return token
return $token;
}
/**
* Check that the given token matches the currently stored security token.
*
* <code>
* if (Security::check($token)) {
* // Pass
* }
* </code>
*
* @param string $token token to check
* @return boolean
*/
public static function check($token)
{
return Security::token() === $token;
}
/**
* Encrypt password
*
* <code>
* $encrypt_password = Security::encryptPassword('password');
* </code>
*
* @param string $password Password to encrypt
*/
public static function encryptPassword($password)
{
return md5(md5(trim($password) . MONSTRA_PASSWORD_SALT));
}
/**
* Create safe name. Use to create safe username, filename, pagename.
*
* <code>
* $safe_name = Security::safeName('hello world');
* </code>
*
* @param string $str String
* @param mixed $delimiter String delimiter
* @param boolean $lowercase String Lowercase
* @return string
*/
public static function safeName($str, $delimiter = '-', $lowercase = false)
{
// Redefine vars
$str = (string) $str;
$delimiter = $delimiter;
$lowercase = (bool) $lowercase;
$delimiter = $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);
if ($delimiter != null) {
$str = preg_replace("/[\/_|+ -]+/", $delimiter, $str);
$str = trim($str, $delimiter);
}
// Lowercase
if ($lowercase === true) {
$str = Text::lowercase($str);
}
// Return safe name
return $str;
}
/**
* Create safe url.
*
* <code>
* $url = Security::sanitizeURL('http://test.com');
* </code>
*
* @param string $url Url to sanitize
* @return string
*/
public static function sanitizeURL($url)
{
$url = trim($url);
$url = rawurldecode($url);
$url = str_replace(array('--', '&quot;', '!', '@', '#', '$', '%', '^', '*', '(', ')', '+', '{', '}', '|', ':', '"', '<', '>',
'[', ']', '\\', ';', "'", ',', '*', '+', '~', '`', 'laquo', 'raquo', ']>', '&#8216;', '&#8217;', '&#8220;', '&#8221;', '&#8211;', '&#8212;'),
array('-', '-', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''),
$url);
$url = str_replace('--', '-', $url);
$url = rtrim($url, "-");
$url = str_replace('..', '', $url);
$url = str_replace('//', '', $url);
$url = preg_replace('/^\//', '', $url);
$url = preg_replace('/^\./', '', $url);
return $url;
}
/**
* Sanitize URL to prevent XSS - Cross-site scripting
*/
public static function runSanitizeURL()
{
$_GET = array_map('Security::sanitizeURL', $_GET);
}
/**
* That prevents null characters between ascii characters.
*
* @param string $str String
*/
public static function removeInvisibleCharacters($str)
{
// Redefine vars
$str = (string) $str;
// Thanks to ci for this tip :)
$non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/');
do {
$cleaned = $str;
$str = preg_replace($non_displayables, '', $str);
} while ($cleaned != $str);
// Return safe string
return $str;
}
/**
* Sanitize data to prevent XSS - Cross-site scripting
*
* @param string $str String
*/
public static function xssClean($str)
{
// Remove invisible characters
$str = Security::removeInvisibleCharacters($str);
// Convert html to plain text
$str = Html::toText($str);
// Return safe string
return $str;
}
}

View File

@@ -1,164 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Shortcode
{
/**
* Shortcode tags array
*
* @var shortcode_tags
*/
protected static $shortcode_tags = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Add new shortcode
*
* <code>
* function returnSiteUrl() {
* return Option::get('siteurl');
* }
*
* // Add shortcode {siteurl}
* Shortcode::add('siteurl', 'returnSiteUrl');
* </code>
*
* @param string $shortcode Shortcode tag to be searched in content.
* @param string $callback_function The callback function to replace the shortcode with.
*/
public static function add($shortcode, $callback_function)
{
// Redefine vars
$shortcode = (string) $shortcode;
// Add new shortcode
if (is_callable($callback_function)) {
Shortcode::$shortcode_tags[$shortcode] = $callback_function;
}
}
/**
* Remove a specific registered shortcode.
*
* <code>
* Shortcode::delete('shortcode_name');
* </code>
*
* @param string $shortcode Shortcode tag.
*/
public static function delete($shortcode)
{
// Redefine vars
$shortcode = (string) $shortcode;
// Delete shortcode
if (Shortcode::exists($shortcode)) {
unset(Shortcode::$shortcode_tags[$shortcode]);
}
}
/**
* Remove all registered shortcodes.
*
* <code>
* Shortcode::clear();
* </code>
*
*/
public static function clear()
{
Shortcode::$shortcode_tags = array();
}
/**
* Check if a shortcode has been registered.
*
* <code>
* if (Shortcode::exists('shortcode_name')) {
* // do something...
* }
* </code>
*
* @param string $shortcode Shortcode tag.
*/
public static function exists($shortcode)
{
// Redefine vars
$shortcode = (string) $shortcode;
// Check shortcode
return array_key_exists($shortcode, Shortcode::$shortcode_tags);
}
/**
* Parse a string, and replace any registered shortcodes within it with the result of the mapped callback.
*
* <code>
* $content = Shortcode::parse($content);
* </code>
*
* @param string $content Content
* @return string
*/
public static function parse($content)
{
if (! Shortcode::$shortcode_tags) {
return $content;
}
$shortcodes = implode('|', array_map('preg_quote', array_keys(Shortcode::$shortcode_tags)));
$pattern = "/(.?)\{([$shortcodes]+)(.*?)(\/)?\}(?(4)|(?:(.+?)\{\/\s*\\2\s*\}))?(.?)/s";
return preg_replace_callback($pattern, 'Shortcode::_handle', $content);
}
/**
* _handle()
*/
protected static function _handle($matches)
{
$prefix = $matches[1];
$suffix = $matches[6];
$shortcode = $matches[2];
// Allow for escaping shortcodes by enclosing them in {{shortcode}}
if ($prefix == '{' && $suffix == '}') {
return substr($matches[0], 1, -1);
}
$attributes = array(); // Parse attributes into into this array.
if (preg_match_all('/(\w+) *= *(?:([\'"])(.*?)\\2|([^ "\'>]+))/', $matches[3], $match, PREG_SET_ORDER)) {
foreach ($match as $attribute) {
if (! empty($attribute[4])) {
$attributes[strtolower($attribute[1])] = $attribute[4];
} elseif (! empty($attribute[3])) {
$attributes[strtolower($attribute[1])] = $attribute[3];
}
}
}
// Check if this shortcode realy exists then call user function else return empty string
return (isset(Shortcode::$shortcode_tags[$shortcode])) ? $prefix . call_user_func(Shortcode::$shortcode_tags[$shortcode], $attributes, $matches[5], $shortcode) . $suffix : '';
}
}

View File

@@ -1,222 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Site
{
/**
* An instance of the Site class
*
* @var site
*/
protected static $instance = null;
/**
* Initializing site
*
* @return Site
*/
public static function init()
{
if (! isset(self::$instance)) {
self::$instance = new Site();
}
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Construct
*/
protected function __construct()
{
call_user_func(ucfirst(Uri::command()).'::main');
}
/**
* Get site name
*
* <code>
* echo Site::name();
* </code>
*
* @return string
*/
public static function name()
{
return Option::get('sitename');
}
/**
* Get site theme
*
* <code>
* echo Site::theme();
* </code>
*
* @return string
*/
public static function theme()
{
return Option::get('theme_site_name');
}
/**
* Get Page title
*
* <code>
* echo Site::title();
* </code>
*
* @return string
*/
public static function title()
{
return call_user_func(ucfirst(Uri::command()).'::title');
}
/**
* Get page description
*
* <code>
* echo Site::description();
* </code>
*
* @return string
*/
public static function description()
{
return (($description = trim(call_user_func(ucfirst(Uri::command()).'::description'))) == '') ? Html::toText(Option::get('description')) : Html::toText($description);
}
/**
* Get page keywords
*
* <code>
* echo Site::keywords();
* </code>
*
* @return string
*/
public static function keywords()
{
return (($keywords = trim(call_user_func(ucfirst(Uri::command()).'::keywords'))) == '') ? Html::toText(Option::get('keywords')) : Html::toText($keywords);
}
/**
* Get site slogan
*
* <code>
* echo Site::slogan();
* </code>
*
* @return string
*/
public static function slogan()
{
return Option::get('slogan');
}
/**
* Get page content
*
* <code>
* echo Site::content();
* </code>
*
* @return string
*/
public static function content()
{
return Filter::apply('content', call_user_func(ucfirst(Uri::command()).'::content'));
}
/**
* Get compressed template
*
* <code>
* echo Site::template();
* </code>
*
* @param string $theme Theme name
* @return mixed
*/
public static function template($theme = null)
{
// Get specific theme or current theme
$current_theme = ($theme == null) ? Option::get('theme_site_name') : $theme ;
// Get template
$template = call_user_func(ucfirst(Uri::command()).'::template');
// Check whether is there such a template in the current theme
// else return default template: index
// also compress template file :)
if (File::exists(THEMES_SITE . DS . $current_theme . DS . $template . '.template.php')) {
if (! file_exists(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php') or
filemtime(THEMES_SITE . DS . $current_theme . DS . $template .'.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php')) {
$buffer = file_get_contents(THEMES_SITE. DS . $current_theme . DS . $template .'.template.php');
$buffer = MinifyHTML::process($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 = MinifyHTML::process($buffer);
file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php', $buffer);
}
return 'minify.index';
}
}
/**
* Get site url
*
* <code>
* echo Site::url();
* </code>
*
* @return string
*/
public static function url()
{
return Option::get('siteurl');
}
/**
* Get copyright information
*
* <code>
* echo Site::powered();
* </code>
*
* @return string
*/
public static function powered()
{
return __('Powered by', 'system').' <a href="http://monstra.org" target="_blank">Monstra</a> ' . Monstra::VERSION;
}
}

View File

@@ -1,163 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Uri
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Default component
*
* @var string
*/
public static $default_component = 'pages';
/**
* Get uri and explode command/param1/param2
*
* <code>
* $segments = Uri::segments();
* </code>
*
* @return array
*/
public static function segments()
{
// Get request uri and current script path
$request_uri = explode('/', $_SERVER['REQUEST_URI']);
$script_name = explode('/', $_SERVER['SCRIPT_NAME']);
// Delete script name
for ($i = 0; $i < sizeof($script_name); $i++) {
if ($request_uri[$i] == $script_name[$i]) {
unset($request_uri[$i]);
}
}
// Get all the values of an array
$uri = array_values($request_uri);
// Ability to pass parameters
foreach ($uri as $i => $u) {
if (isset($uri[$i])) {
$pos = strrpos($uri[$i], "?");
if ($pos === false) {
$uri[$i] = Security::sanitizeURL($uri[$i]);
} else {
$uri[$i] = Security::sanitizeURL(substr($uri[$i], 0, $pos));
}
}
}
// Return uri segments
return $uri;
}
/**
* Get uri segment
*
* <code>
* $segment = Uri::segment(1);
* </code>
*
* @param integer $segment Segment
* @return mixed
*/
public static function segment($segment)
{
$segments = Uri::segments();
return isset($segments[$segment]) ? $segments[$segment] : null;
}
/**
* Get command/component from registed components
*
* <code>
* $command = Uri::command();
* </code>
*
* @return array
*/
public static function command()
{
// Get uri segments
$uri = Uri::segments();
if (! isset($uri[0])) {
$uri[0] = Uri::$default_component;
} else {
if (! in_array($uri[0], Plugin::$components)) {
$uri[0] = Uri::$default_component;
} else {
$uri[0] = $uri[0];
}
}
return $uri[0];
}
/**
* Get uri parammeters
*
* <code>
* $params = Uri::params();
* </code>
*
* @return array
*/
public static function params()
{
//Init data array
$data = array();
// Get URI
$uri = Uri::segments();
// http://site.com/ and http://site.com/index.php same main home pages
if (! isset($uri[0])) {
$uri[0] = '';
}
// param1/param2
if ($uri[0] !== Uri::$default_component) {
if (isset($uri[1])) {
foreach ($uri as $part) {
$data[] = $part;
}
} else { // default
$data[0] = $uri[0];
}
} else {
// This is good for box plugin Pages
// parent/child
if (isset($uri[2])) {
$data[0] = $uri[1];
$data[1] = $uri[2];
} else { // default
$data[0] = $uri[1];
}
}
return $data;
}
}

View File

@@ -1,92 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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);
}
}

View File

@@ -1,857 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
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 factory.
*
* <code>
* $users = Table::factory('table_name');
* </code>
*
* @param string $table_name Table name
* @return Table
*/
public static function factory($table_name)
{
return new Table($table_name);
}
/**
* Table construct
*
* <code>
* $users = new Table('table_name');
* </code>
*
* @param string $table_name Table name
*/
public 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:
*
* <?xml version="1.0" encoding="UTF-8"?>
* <root>
* <options><autoincrement>0</autoincrement></options>
* <fields>
* <field1/>
* <field2/>
* </fields>
* <record>
* <field1>value</field1>
* <field2>value</field2>
* </record>
* </root>
*
* <code>
* Table::create('table_name', array('field1', 'field2'));
* </code>
*
* @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 = '<fields>';
foreach ($fields as $field) {
$_fields .= "<$field/>";
}
$_fields .= '</fields>';
// Create new table
return file_put_contents(Table::$tables_dir . '/' . $table_name . '.table.xml', '<?xml version="1.0" encoding="UTF-8"?><root><options><autoincrement>0</autoincrement></options>'.$_fields.'</root>', LOCK_EX);
} else {
// Something wrong... return false
return false;
}
}
/**
* Delete table
*
* <code>
* Table::drop('table_name');
* </code>
*
* @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
*
* <code>
* $table = Table::get('table_name');
* </code>
*
* @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
*
* <code>
* var_dump($users->info());
* </code>
*
* @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
*
* <code>
* var_dump($users->fields());
* </code>
*
* @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
*
* <code>
* $users->addField('test');
* </code>
*
* @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
*
* <code>
* $users->deleteField('test');
* </code>
*
* @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
*
* <code>
* $users->updateField('login', 'username');
* </code>
*
* @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.'>',
'<'.$old_name.'/>' => '<'.$new_name.'/>'));
if (file_put_contents(Table::$tables_dir . '/' . $this->name.'.table.xml', $table)) {
return true;
} else {
return false;
}
}
}
/**
* Check if field exist
*
* <code>
* if ($users->existsField('field_name')) {
* // do something...
* }
* </code>
*
* @param string $name Name of field to check.
* @return boolean
*/
public function existsField($name)
{
// Redefine vars
$name = (string) $name;
// Get table
$table = $this->table;
// Select field
$field = Table::_selectOne($this->table, "fields/{$name}");
// Return true or false
return ($field == null) ? false : true;
}
/**
* Add new record
*
* <code>
* $users->insert(array('login'=>'admin', 'password'=>'pass'));
* </code>
*
* @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
*
* <code>
* $records = $users->select('[id=2]');
* $records = $users->select(null, 'all');
* $records = $users->select(null, 'all', null, array('login'));
* $records = $users->select(null, 2, 1);
* </code>
*
* @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"]');
foreach ($tmp as $record) {
$data[] = $record;
}
$_records = $data;
}
// 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;
if ($order_by == 'id') {
$record_array[$count]['sort'] = (int) $record->$order_by;
} else {
$record_array[$count]['sort'] = (string) $record->$order_by;
}
$count++;
}
// Sort records
$records = Table::subvalSort($record_array, 'sort', $order);
// Slice records array
if ($offset === null && is_int($row_count)) {
$records = array_slice($records, -$row_count, $row_count);
} elseif ($offset !== null && is_int($row_count)) {
$records = array_slice($records, $offset, $row_count);
}
}
} 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;
if ($order_by == 'id') {
$records[$count]['sort'] = (int) $vars['id'];
} else {
$records[$count]['sort'] = (string) $vars[$order_by];
}
}
$count++;
}
// Sort records
$records = Table::subvalSort($records, 'sort', $order);
// Slice records array
if ($offset === null && is_int($row_count)) {
$records = array_slice($records, -$row_count, $row_count);
} elseif ($offset !== null && is_int($row_count)) {
$records = array_slice($records, $offset, $row_count);
}
} else {
// Single record
$vars = get_object_vars($_records[0]);
foreach ($vars as $key => $value) {
$records[$key] = (string) $value;
}
}
}
// Return records
return $records;
}
/**
* Delete current record in table
*
* <code>
* $users->delete(2);
* </code>
*
* @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
*
* <code>
* $users->deleteWhere('[id=2]');
* </code>
*
* @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
*
* <code>
* $users->updateWhere('[id=2]', array('login'=>'Admin', 'password'=>'new pass'));
* </code>
*
* @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
*
* <code>
* $users->update(1, array('login'=>'Admin','password'=>'new pass'));
* </code>
*
* @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
*
* <code>
* echo $users->lastId();
* </code>
*
* @return integer
*/
public function lastId()
{
$data = $this->table['xml_object']->xpath("//root/node()[last()]");
return (int) $data[0]->id;
}
/**
* Get count of records
*
* <code>
* echo $users->count();
* </code>
*
* @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);
} elseif ($order == 'DESC') {
arsort($b);
}
foreach ($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
return $a;
}
/**
* _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', 'utf-8');
$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...
}
}
}

View File

@@ -1,94 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class XML
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Create safe xml data. Removes dangerous characters for string.
*
* <code>
* $xml_safe = XML::safe($xml_unsafe);
* </code>
*
* @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
*
* <code>
* $xml_file = XML::loadFile('path/to/file.xml');
* </code>
*
* @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;
}
}
}
}

View File

@@ -1,38 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra requires PHP 5.3.2 or greater
*/
if (version_compare(PHP_VERSION, "5.3.2", "<")) {
exit("Monstra requires PHP 5.3.2 or greater.");
}
/**
* Include Monstra Engine
*/
include ROOT . DS .'engine'. DS .'Monstra.php';
/**
* Set Monstra Environment
*
* Monstra has four predefined environments:
* Monstra::DEVELOPMENT - The development environment.
* Monstra::TESTING - The test environment.
* Monstra::STAGING - The staging environment.
* Monstra::PRODUCTION - The production environment.
*/
Monstra::$environment = Monstra::PRODUCTION;
/**
* Report Errors
*/
if (Monstra::$environment == Monstra::PRODUCTION) {
error_reporting(0);
} else {
error_reporting(-1);
}
/**
* Initialize Monstra
*/
Monstra::init();

View File

@@ -1,10 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Set meta generator
*/
Action::add('theme_meta', 'setMetaGenerator');
function setMetaGenerator()
{
echo '<meta name="generator" content="Powered by Monstra '.Monstra::VERSION.'" />'."\n";
}

View File

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

View File

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

View File

@@ -1,10 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Add new shortcode {siteurl}
*/
Shortcode::add('siteurl', 'returnSiteUrl');
function returnSiteUrl()
{
return Option::get('siteurl');
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1,63 +0,0 @@
<?php
/**
* Monstra
*
* @package Monstra
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @link http://monstra.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(dirname(__FILE__), '\\/'));
define('BACKEND', false);
define('MONSTRA_ACCESS', true);
// First check for installer then go
if (file_exists('install.php')) {
if (isset($_GET['install'])) {
if ($_GET['install'] == 'done') {
// Try to delete install file if not delete manually
@unlink('install.php');
// Redirect to main page
header('location: index.php');
}
} else {
include 'install.php';
}
} else {
// Load Engine init file
require_once ROOT. DS . 'engine'. DS . '_init.php';
// Check for maintenance mod
if ('on' == Option::get('maintenance_status')) {
// Set maintenance mode for all except admin and editor
if ((Session::exists('user_role')) and (Session::get('user_role') == 'admin' or Session::get('user_role') == 'editor')) {
// Monstra show this page :)
} else {
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 600');
die(Text::toHtml(Option::get('maintenance_message')));
}
}
// Frontend pre render
Action::run('frontend_pre_render');
// Load site template
require MINIFY . DS . 'theme.' . Site::theme() . '.' . Site::template() . '.template.php';
// Frontend pre render
Action::run('frontend_post_render');
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,236 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class ClassLoader
{
/**
* Mapping from class names to paths.
*
* @var array
*/
protected static $classes = array();
/**
* PSR-0 directories.
*
* @var array
*/
protected static $directories = array();
/**
* Registered namespaces.
*
* @var array
*/
protected static $namespaces = array();
/**
* Class aliases.
*
* @var array
*/
protected static $aliases = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Add class to mapping.
*
* <code>
* ClassLoader::mapClass('ClassName', 'path/to/class');
* </code>
*
* @access public
* @param string $className Class name
* @param string $classPath Full path to class
*/
public static function mapClass($className, $classPath)
{
ClassLoader::$classes[$className] = $classPath;
}
/**
* Add multiple classes to mapping.
*
* <code>
* ClassLoader::mapClasses(array('ClassName' => 'path/to/class','ClassName' => 'path/to/class'));
* </code>
*
* @access public
* @param array $classes Array of classes to map (key = class name and value = class path)
*/
public static function mapClasses(array $classes)
{
foreach ($classes as $name => $path) {
ClassLoader::$classes[$name] = $path;
}
}
/**
* Adds a PSR-0 directory path.
*
* <code>
* ClassLoader::directory('path/to/classes');
* </code>
*
* @access public
* @param string $path Path to PSR-0 directory
*/
public static function directory($path)
{
ClassLoader::$directories[] = rtrim($path, '/');
}
/**
* Registers a namespace.
*
* <code>
* ClassLoader::registerNamespace('Namespace', '/path/to/namespace/');
* </code>
*
* @access public
* @param string $namespace Namespace
* @param string $path Path
*/
public static function registerNamespace($namespace, $path)
{
ClassLoader::$namespaces[trim($namespace, '\\') . '\\'] = rtrim($path, '/');
}
/**
* Set an alias for a class.
*
* <code>
* ClassLoader::alias('ClassNameAlias', 'ClassName');
* </code>
*
* @access public
* @param string $alias Class alias
* @param string $className Class name
*/
public static function alias($alias, $className)
{
ClassLoader::$aliases[$alias] = $className;
}
/**
* Try to load a PSR-0 compatible class.
*
* @access protected
* @param string $className Class name
* @param string $directory (Optional) Overrides the array of PSR-0 paths
* @return boolean
*/
protected static function loadPSR0($className, $directory = null)
{
$classPath = '';
if (($pos = strripos($className, '\\')) !== false) {
$namespace = substr($className, 0, $pos);
$className = substr($className, $pos + 1);
$classPath = str_replace('\\', '/', $namespace) . '/';
}
$classPath .= str_replace('_', '/', $className) . '.php';
$directories = ($directory === null) ? ClassLoader::$directories : array($directory);
foreach ($directories as $directory) {
if (file_exists($directory . '/' . $classPath)) {
include($directory . '/' . $classPath);
return true;
}
}
return false;
}
/**
* Autoloader.
*
* <code>
* ClassLoader::load();
* </code>
*
* @access public
* @param string $className Class name
* @return boolean
*/
public static function load($className)
{
$className = ltrim($className, '\\');
/**
* Try to autoload an aliased class
*/
if (isset(ClassLoader::$aliases[$className])) {
return class_alias(ClassLoader::$aliases[$className], $className);
}
/**
* Try to load a mapped class
*/
if (isset(ClassLoader::$classes[$className]) && file_exists(ClassLoader::$classes[$className])) {
include ClassLoader::$classes[$className];
return true;
}
/**
* Try to load class from a registered namespace
*/
foreach (ClassLoader::$namespaces as $namespace => $path) {
if (strpos($className, $namespace) === 0) {
if (ClassLoader::loadPSR0(substr($className, strlen($namespace)), $path)) {
return true;
}
}
}
/**
* Try to load a PSR-0 compatible class
* The second call to the loadPSR0 method is used to autoload legacy code
*/
if (ClassLoader::loadPSR0($className) || ClassLoader::loadPSR0(strtolower($className))) {
return true;
}
return false;
}
/**
* Register the Gelato ClassLoader to the SPL autoload stack.
*
* @return void
*/
public static function register()
{
spl_autoload_register('ClassLoader::load', true);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,311 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class ErrorHandler
{
/**
* Error Levels
*/
public static $levels = 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_USER_NOTICE => 'Notice',
E_USER_WARNING => 'Warning',
E_USER_ERROR => 'Error',
/*E_DEPRECATED => 'Deprecated',*/ /* PHP 5.3 only */
/*E_USER_DEPRECATED => 'Deprecated'*/ /* PHP 5.3 only */
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Returns an array of lines from a file.
*
* @access public
* @param string $file File in which you want to highlight a line
* @param int $line Line number to highlight
* @param int $padding (optional) Number of padding lines
* @return array
*/
protected static function highlightCode($file, $line, $padding = 6)
{
if ( ! is_readable($file)) {
return false;
}
$handle = fopen($file, 'r');
$lines = array();
$currentLine = 0;
while ( ! feof($handle)) {
$currentLine++;
$temp = fgets($handle);
if ($currentLine > $line + $padding) {
break; // Exit loop after we have found what we were looking for
}
if ($currentLine >= ($line - $padding) && $currentLine <= ($line + $padding)) {
$lines[] = array
(
'number' => str_pad($currentLine, 4, ' ', STR_PAD_LEFT),
'highlighted' => ($currentLine === $line),
'code' => ErrorHandler::highlightString($temp),
);
}
}
fclose($handle);
return $lines;
}
/**
* 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 error($code, $message, $file, $line)
{
// If isset error_reporting and $code then throw new error exception
if ((error_reporting() & $code) !== 0) {
/**
* Dont thow NOTICE exception for PRODUCTION Environment. Just write to log.
*/
if (GELATO_DEVELOPMENT == false && $code == 8) {
// Get exception info
$error['code'] = $code;
$error['message'] = $message;
$error['file'] = $file;
$error['line'] = $line;
$error['type'] = 'ErrorException: ';
$codes = array (
E_USER_NOTICE => 'Notice',
);
$error['type'] .= in_array($error['code'], array_keys($codes)) ? $codes[$error['code']] : 'Unknown Error';
// Write to log
Log::write("{$error['type']}: {$error['message']} in {$error['file']} at line {$error['line']}");
} else {
throw new ErrorException($message, $code, 0, $file, $line);
}
}
// Don't execute PHP internal error handler
return true;
}
/**
* Highlight string
*
* @param string $string String
* @return string
*/
protected static function highlightString($string)
{
$search = array("\r\n", "\n\r", "\r", "\n", '<code>', '</code>', '<span style="color: #0000BB">&lt;?php&nbsp;', '#$@r4!/*');
$replace = array('', '', '', '', '', '', '<span style="color: #0000BB">', '/*');
return str_replace($search, $replace, highlight_string('<?php ' . str_replace('/*', '#$@r4!/*', $string), true));
}
/**
* Modifies the backtrace array.
*
* @access protected
* @param array $backtrace Array returned by the getTrace() method of an exception object
* @return array
*/
protected static function formatBacktrace($backtrace)
{
if (is_array($backtrace) === false || count($backtrace) === 0) {
return $backtrace;
}
/**
* Remove unnecessary info from backtrace
*/
if ($backtrace[0]['function'] == '{closure}') {
unset($backtrace[0]);
}
/**
* Format backtrace
*/
$trace = array();
foreach ($backtrace as $entry) {
/**
* Function
*/
$function = '';
if (isset($entry['class'])) {
$function .= $entry['class'] . $entry['type'];
}
$function .= $entry['function'] . '()';
/**
* Arguments
*/
$arguments = array();
if (isset($entry['args']) && count($entry['args']) > 0) {
foreach ($entry['args'] as $arg) {
ob_start();
var_dump($arg);
$arg = htmlspecialchars(ob_get_contents());
ob_end_clean();
$arguments[] = $arg;
}
}
/**
* Location
*/
$location = array();
if (isset($entry['file'])) {
$location['file'] = $entry['file'];
$location['line'] = $entry['line'];
$location['code'] = self::highlightCode($entry['file'], $entry['line']);
}
/**
* Compile into array
*/
$trace[] = array
(
'function' => $function,
'arguments' => $arguments,
'location' => $location,
);
}
return $trace;
}
/**
* Convert errors not caught by the error handler to ErrorExceptions.
*/
public static function fatal()
{
$e = error_get_last();
if ($e !== null && (error_reporting() & $e['type']) !== 0) {
ErrorHandler::exception(new ErrorException($e['message'], $e['type'], 0, $e['file'], $e['line']));
exit(1);
}
}
/**
* Handles uncaught exceptions and returns a pretty error screen.
*
* @access public
* @param Exception $exception An exception object
*/
public static function exception($exception)
{
try {
// Empty output buffers
while(ob_get_level() > 0) ob_end_clean();
// Get exception info
$error['code'] = $exception->getCode();
$error['message'] = $exception->getMessage();
$error['file'] = $exception->getFile();
$error['line'] = $exception->getLine();
// Determine error type
if ($exception instanceof ErrorException) {
$error['type'] = 'ErrorException: ';
$error['type'] .= in_array($error['code'], array_keys(ErrorHandler::$levels)) ? ErrorHandler::$levels[$error['code']] : 'Unknown Error';
} else {
$error['type'] = get_class($exception);
}
// Write to log
Log::write("{$error['type']}: {$error['message']} in {$error['file']} at line {$error['line']}");
// Send headers and output
@header('Content-Type: text/html; charset=UTF-8');
if (GELATO_DEVELOPMENT) {
$error['backtrace'] = $exception->getTrace();
if ($exception instanceof ErrorException) {
$error['backtrace'] = array_slice($error['backtrace'], 1); //Remove call to error handler from backtrace
}
$error['backtrace'] = self::formatBacktrace($error['backtrace']);
$error['highlighted'] = self::highlightCode($error['file'], $error['line']);
@header('HTTP/1.1 500 Internal Server Error');
include 'Resources/Views/Errors/exception.php';
} else {
@header('HTTP/1.1 500 Internal Server Error');
include 'Resources/Views/Errors/production.php';
}
} catch (Exception $e) {
// Empty output buffers
while(ob_get_level() > 0) ob_end_clean();
echo $e->getMessage() . ' in ' . $e->getFile() . ' (line ' . $e->getLine() . ').';
}
exit(1);
}
}

View File

@@ -1,306 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<style type="text/css">
body {
background: #F5F5F5;
padding: 0;
margin: 0;
}
#gelato-error {
background:#F5F5F5;
color:0;
width:100%;
font-size:14px;
font-family:Verdana, Arial, Helvetica, "Nimbus Sans", FreeSans, Malayalam, sans-serif;
}
#gelato-error pre {
font-family:"Andale Mono", "Courier New", Courier;
font-size:12px;
margin:0;
padding:0;
}
#gelato-error a {
color:#DC143C;
text-decoration:none;
}
#gelato-error .error {
background:#DC143C;
color:#fff;
font-size:24px;
font-weight:700;
padding:10px;
}
#gelato-error .body {
border:0 solid #ccc;
padding:10px;
}
#gelato-error .code {
background:#fff;
border:1px solid #ccc;
overflow:auto;
}
#gelato-error .heading {
background:#444;
color:#fff;
font-size:18px;
font-weight:700;
padding:10px;
}
#gelato-error .line {
background:#777;
color:#fff;
padding-left:4px;
padding-right:4px;
}
#gelato-error .highlighted {
background:#fceb71;
border-top:1px solid #ccc;
border-bottom:1px solid #ccc;
}
#gelato-error .backtrace {
background:#fff;
margin-bottom:10px;
border:1px solid #ccc;
padding:10px;
}
#gelato-error .backtrace ol {
padding-left:40px;
}
#gelato-error table {
border-spacing:0;
border-collapse:collapse;
border-color:#ddd;
border-style:solid;
border-width:0 0 1px 1px;
}
#gelato-error td {
font-size:14px;
background:#fff;
border-color:#ddd;
border-style:solid;
border-width:1px 1px 0 0;
margin:0;
padding:4px;
}
.pull-right {
float:right;
}
</style>
<body>
<div id="gelato-error">
<div class="error">
<?php echo $error['type']; ?><?php if(isset($error['code'])): ?> <span style="color:#e1e1e1;padding:0px">[<?php echo $error['code']; ?>]</span><?php endif; ?>
<span class="pull-right">Gelato</span>
</div>
<div class="body">
<strong>Message:</strong> <?php echo htmlspecialchars($error['message'], ENT_COMPAT, 'UTF-8', false); ?>
<?php if(!empty($error['file'])): ?>
<br><br>
<strong>Location:</strong> <?php echo $error['file']; ?> (line <?php echo $error['line']; ?>)
<?php endif; ?>
<?php if(!empty($error['highlighted'])): ?>
<br><br>
<div class="code">
<?php foreach($error['highlighted'] as $line): ?>
<pre<?php if($line['highlighted']): ?> class="highlighted"<?php endif; ?>><span class="line"><?php echo $line['number']; ?></span> <?php echo $line['code']; ?></pre>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php if(!empty($error['backtrace'])): ?>
<div class="heading">
Backtrace <a href="#" onclick="return toggle('backtrace', this);" style="float:right">+</a>
</div>
<div class="body" style="display:none;" id="backtrace">
<?php foreach($error['backtrace'] as $trace): ?>
<div class="backtrace">
<p><strong>Function:</strong> <?php echo $trace['function']; ?></p>
<?php if(!empty($trace['arguments'])): $id = md5(uniqid('', true)); ?>
<p><strong>Arguments: [<a href="#" onclick="return toggle('<?php echo $id; ?>', this);">+</a>]</strong></p>
<div style="display:none" id="<?php echo $id; ?>">
<ol>
<?php foreach($trace['arguments'] as $arg): ?>
<li><pre><?php echo $arg; ?></pre></li>
<?php endforeach; ?>
</ol>
</div>
<?php endif; ?>
<?php if(!empty($trace['location'])): $id = md5(uniqid('', true)); ?>
<p><strong>Location:</strong> <?php echo $trace['location']['file']; ?> (<a href="#" onclick="return toggle('<?php echo $id; ?>');">line <?php echo $trace['location']['line']; ?></a>)</p>
<div class="code" style="display:none" id="<?php echo $id; ?>">
<?php foreach($trace['location']['code'] as $line): ?>
<pre<?php if($line['highlighted']): ?> class="highlighted"<?php endif; ?>><span class="line"><?php echo $line['number']; ?></span> <?php echo $line['code']; ?></pre>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="heading">
Superglobals <a href="#" onclick="return toggle('superglobals', this);" style="float:right">+</a>
</div>
<div class="body" style="display:none;" id="superglobals">
<?php if(!empty($_SERVER)): ?>
<p><b>$_SERVER [<a href="#" onclick="return toggle('_server', this);">+</a>]</b></p>
<div id="_server" style="display:none">
<table width="100%">
<?php foreach($_SERVER as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><pre><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></pre></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
<?php if(!empty($_GET)): ?>
<p><b>$_GET [<a href="#" onclick="return toggle('_get', this);">+</a>]</b></p>
<div id="_get" style="display:none">
<table width="100%">
<?php foreach($_GET as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><pre><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></pre></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
<?php if(!empty($_POST)): ?>
<p><b>$_POST [<a href="#" onclick="return toggle('_post', this);">+</a>]</b></p>
<div id="_post" style="display:none">
<table width="100%">
<?php foreach($_POST as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><pre><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></pre></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
<?php if(!empty($_FILES)): ?>
<p><b>$_FILES [<a href="#" onclick="return toggle('_files', this);">+</a>]</b></p>
<div id="_files" style="display:none">
<table width="100%">
<?php foreach($_FILES as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><pre><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></pre></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
<?php if(!empty($_COOKIE)): ?>
<p><b>$_COOKIE [<a href="#" onclick="return toggle('_cookie', this);">+</a>]</b></p>
<div id="_cookie" style="display:none">
<table width="100%">
<?php foreach($_COOKIE as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
<?php if(!empty($_SESSION)): ?>
<p><b>$_SESSION [<a href="#" onclick="return toggle('_session', this);">+</a>]</b></p>
<div id="_session" style="display:none">
<table width="100%">
<?php foreach($_SESSION as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><pre><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></pre></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
<?php if(!empty($_ENV)): ?>
<p><b>$_ENV [<a href="#" onclick="return toggle('_env', this);">+</a>]</b></p>
<div id="_env" style="display:none">
<table width="100%">
<?php foreach($_ENV as $k => $v): ?>
<tr>
<td width="15%"><?php echo htmlspecialchars($k); ?></td>
<td width="85%"><pre><?php ob_start(); var_dump($v); echo htmlspecialchars(ob_get_clean()); ?></pre></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php endif; ?>
</div>
<div class="heading">
Included Files <a href="#" onclick="return toggle('files', this);" style="float:right">+</a>
</div>
<div class="body" style="display:none;" id="files">
<table width="100%">
<?php foreach(get_included_files() as $k => $v): ?>
<tr>
<td width="5%"><?php echo $k + 1; ?></td>
<td width="95%"><?php echo $v; ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div style="padding-top:20px;padding-bottom:20px; padding-left:10px;">
<a href="http://monstra.org">MONSTRA</a>
<a href="http://gelato.monstra.org">GELATO</a>
</div>
</div>
<script type="text/javascript">
function toggle(id, link)
{
var div = document.getElementById(id);
if (div.style.display == "none") {
if (link != null) {
link.innerHTML = '-';
}
div.style.display = "block";
} else {
if (link != null) {
link.innerHTML = '+';
}
div.style.display = "none";
}
return false;
}
</script>
</body>
</html>

View File

@@ -1,51 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<style type="text/css">
body {
height:100%;
background:#eee;
padding:0px;
margin:0px;
height: 100%;
font-size: 100%;
color:#333;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
line-height: 100%;
}
a {
color:#0088cc;
text-decoration:none;
}
a:hover {
color:#005580;
text-decoration:underline;
}
h1 {
font-size: 4em;
}
small {
font-size: 0.7em;
color: #999;
font-weight: normal;
}
hr {
border:0px;
border-bottom:1px #ddd solid;
}
#message {
width: 700px;
margin: 15% auto;
}
</style>
</head>
<body>
<div id="message">
<h1>Error</h1>
<hr>
<p>Aw, snap! An error has occurred while processing your request.</p>
</div>
</body>
</html>

View File

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

View File

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

View File

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

View File

@@ -1,124 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The version of Gelato
*/
define('GELATO_VERSION', '1.0.3');
/**
* Define __DIR__ constant for PHP 5.2.x
*/
if ( ! defined('__DIR__')) {
define('__DIR__', dirname(__FILE__));
}
/**
* Display Gelato Errors or not ?
*/
if ( ! defined('GELATO_DEVELOPMENT')) {
define('GELATO_DEVELOPMENT', true);
}
/**
* Use Gelato Class Loader or not ?
*/
if ( ! defined('GELATO_CLASS_LOADER')) {
define('GELATO_CLASS_LOADER', true);
}
/**
* Load Gelato Logger
*/
require_once __DIR__ . '/Log/Log.php';
/**
* Use Gelato Logger default path or not ?
*/
if ( ! defined('GELATO_LOGS_PATH')) {
define('GELATO_LOGS_PATH', __DIR__. '/_logs');
}
/**
* Configure Gelato Logger
*/
Log::configure('path', GELATO_LOGS_PATH);
/**
* Load Gelato Error Handler
*/
require_once __DIR__ . '/ErrorHandler/ErrorHandler.php';
/**
* Set Error Handler
*/
set_error_handler('ErrorHandler::error');
/**
* Set Fatal Error Handler
*/
register_shutdown_function('ErrorHandler::fatal');
/**
* Set Exception Handler
*/
set_exception_handler('ErrorHandler::exception');
/**
* Gelato Class Loader
*/
require_once __DIR__ . '/ClassLoader/ClassLoader.php';
/**
* Map all Gelato Classes
*/
ClassLoader::mapClasses(array(
'Agent' => __DIR__.'/Agent/Agent.php',
'Arr' => __DIR__.'/Arr/Arr.php',
'Cache' => __DIR__.'/Cache/Cache.php',
'Cookie' => __DIR__.'/Cookie/Cookie.php',
'Curl' => __DIR__.'/Curl/Curl.php',
'Date' => __DIR__.'/Date/Date.php',
'Debug' => __DIR__.'/Debug/Debug.php',
'File' => __DIR__.'/FileSystem/File.php',
'Dir' => __DIR__.'/FileSystem/Dir.php',
'Form' => __DIR__.'/Form/Form.php',
'Html' => __DIR__.'/Html/Html.php',
'Image' => __DIR__.'/Image/Image.php',
'Inflector' => __DIR__.'/Inflector/Inflector.php',
'MinifyCSS' => __DIR__.'/Minify/MinifyCSS.php',
'MinifyHTML' => __DIR__.'/Minify/MinifyHTML.php',
'MinifyJS' => __DIR__.'/Minify/MinifyJS.php',
'Notification' => __DIR__.'/Notification/Notification.php',
'Number' => __DIR__.'/Number/Number.php',
'Registry' => __DIR__.'/Registry/Registry.php',
'Request' => __DIR__.'/Http/Request.php',
'Response' => __DIR__.'/Http/Response.php',
'Token' => __DIR__.'/Security/Token.php',
'Text' => __DIR__.'/Text/Text.php',
'Session' => __DIR__.'/Session/Session.php',
'Url' => __DIR__.'/Url/Url.php',
'Valid' => __DIR__.'/Validation/Valid.php',
'Zip' => __DIR__.'/Zip/Zip.php',
));
/**
* Register Gelato Class Loader
*/
if (GELATO_CLASS_LOADER) {
ClassLoader::register();
}

View File

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

View File

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

View File

@@ -1,112 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Response
{
/**
* HTTP status codes and messages
*
* @var array
*/
public static $messages = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing', // RFC2518
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status', // RFC4918
208 => 'Already Reported', // RFC5842
226 => 'IM Used', // RFC3229
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect', // RFC-reschke-http-status-308-07
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',
418 => 'I\'m a teapot', // RFC2324
422 => 'Unprocessable Entity', // RFC4918
423 => 'Locked', // RFC4918
424 => 'Failed Dependency', // RFC4918
425 => 'Reserved for WebDAV advanced collections expired proposal', // RFC2817
426 => 'Upgrade Required', // RFC2817
428 => 'Precondition Required', // RFC6585
429 => 'Too Many Requests', // RFC6585
431 => 'Request Header Fields Too Large', // RFC6585
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates (Experimental)', // RFC2295
507 => 'Insufficient Storage', // RFC4918
508 => 'Loop Detected', // RFC5842
510 => 'Not Extended', // RFC2774
511 => 'Network Authentication Required', // RFC6585
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Set header status
*
* <code>
* Response::status(404);
* </code>
*
* @param integer $status Status code
*/
public static function status($status)
{
if (array_key_exists($status, Response::$messages)) header('HTTP/1.1 ' . $status . ' ' . Response::$messages[$status]);
}
}

View File

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

View File

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

View File

@@ -1,63 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Log
{
/**
* Path to the logs.
*
* @var string
*/
protected static $path = '';
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Configure Log
*
* @access public
* @param string $setting The setting
* @param string $value The value
*/
public static function configure($setting, $value)
{
if (property_exists("log", $setting)) Log::$$setting = $value;
}
/**
* Writes message to log.
*
* @access public
* @param string $message The message to write to the log
* @return boolean
*/
public static function write($message)
{
return (bool) file_put_contents(rtrim(Log::$path, '/') . '/' . gmdate('Y_m_d') . '.log',
'[' . gmdate('d-M-Y H:i:s') . '] ' . $message . PHP_EOL,
FILE_APPEND);
}
}

View File

@@ -1,241 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @author Stephen Clay <steve@mrclay.org>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class MinifyCSS
{
/**
* @var array
*/
protected $_options = null;
/**
* Are we "in" a hack? I.e. are some browsers targetted until the next comment?
*
* @var bool
*/
protected $_inHack = false;
/**
* Constructor
*
* @param array $options (currently ignored)
*/
private function __construct($options)
{
$this->_options = $options;
}
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options (currently ignored)
*
* @return string
*/
public static function process($css, $options = array())
{
$obj = new MinifyCSS($options);
return $obj->_process($css);
}
/**
* Minify a CSS string
*
* @param string $css
*
* @return string
*/
protected function _process($css)
{
$css = str_replace("\r\n", "\n", $css);
// preserve empty comment after '>'
// http://www.webdevout.net/css-hacks#in_css-selectors
$css = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $css);
// preserve empty comment between property and value
// http://css-discuss.incutio.com/?page=BoxModelHack
$css = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $css);
$css = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $css);
// apply callback to all valid comments (and strip out surrounding ws
$css = preg_replace_callback('@\\s*/\\*([\\s\\S]*?)\\*/\\s*@'
,array($this, '_commentCB'), $css);
// remove ws around { } and last semicolon in declaration block
$css = preg_replace('/\\s*{\\s*/', '{', $css);
$css = preg_replace('/;?\\s*}\\s*/', '}', $css);
// remove ws surrounding semicolons
$css = preg_replace('/\\s*;\\s*/', ';', $css);
// remove ws around urls
$css = preg_replace('/
url\\( # url(
\\s*
([^\\)]+?) # 1 = the URL (really just a bunch of non right parenthesis)
\\s*
\\) # )
/x', 'url($1)', $css);
// remove ws between rules and colons
$css = preg_replace('/
\\s*
([{;]) # 1 = beginning of block or rule separator
\\s*
([\\*_]?[\\w\\-]+) # 2 = property (and maybe IE filter)
\\s*
:
\\s*
(\\b|[#\'"-]) # 3 = first character of a value
/x', '$1$2:$3', $css);
// minimize hex colors
/*$css = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i'
, '$1#$2$3$4$5', $css);*/
// remove spaces between font families
$css = preg_replace_callback('/font-family:([^;}]+)([;}])/'
,array($this, '_fontFamilyCB'), $css);
$css = preg_replace('/@import\\s+url/', '@import url', $css);
// replace any ws involving newlines with a single newline
$css = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $css);
// separate common descendent selectors w/ newlines (to limit line lengths)
$css = preg_replace('/([\\w#\\.\\*]+)\\s+([\\w#\\.\\*]+){/', "$1\n$2{", $css);
// Use newline after 1st numeric value (to limit line lengths).
$css = preg_replace('/
((?:padding|margin|border|outline):\\d+(?:px|em)?) # 1 = prop : 1st numeric value
\\s+
/x'
,"$1\n", $css);
// prevent triggering IE6 bug: http://www.crankygeek.com/ie6pebug/
$css = preg_replace('/:first-l(etter|ine)\\{/', ':first-l$1 {', $css);
return trim($css);
}
/**
* Replace what looks like a set of selectors
*
* @param array $m regex matches
*
* @return string
*/
protected function _selectorsCB($m)
{
// remove ws around the combinators
return preg_replace('/\\s*([,>+~])\\s*/', '$1', $m[0]);
}
/**
* Process a comment and return a replacement
*
* @param array $m regex matches
*
* @return string
*/
protected function _commentCB($m)
{
$hasSurroundingWs = (trim($m[0]) !== $m[1]);
$m = $m[1];
// $m is the comment content w/o the surrounding tokens,
// but the return value will replace the entire comment.
if ($m === 'keep') {
return '/**/';
}
if ($m === '" "') {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*" "*/';
}
if (preg_match('@";\\}\\s*\\}/\\*\\s+@', $m)) {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*";}}/* */';
}
if ($this->_inHack) {
// inversion: feeding only to one browser
if (preg_match('@
^/ # comment started like /*/
\\s*
(\\S[\\s\\S]+?) # has at least some non-ws content
\\s*
/\\* # ends like /*/ or /**/
@x', $m, $n)) {
// end hack mode after this comment, but preserve the hack and comment content
$this->_inHack = false;
return "/*/{$n[1]}/**/";
}
}
if (substr($m, -1) === '\\') { // comment ends like \*/
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*\\*/';
}
if ($m !== '' && $m[0] === '/') { // comment looks like /*/ foo */
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*/*/';
}
if ($this->_inHack) {
// a regular comment ends hack mode but should be preserved
$this->_inHack = false;
return '/**/';
}
// Issue 107: if there's any surrounding whitespace, it may be important, so
// replace the comment with a single space
return $hasSurroundingWs // remove all other comments
? ' '
: '';
}
/**
* Process a font-family listing and return a replacement
*
* @param array $m regex matches
*
* @return string
*/
protected function _fontFamilyCB($m)
{
// Issue 210: must not eliminate WS between words in unquoted families
$pieces = preg_split('/(\'[^\']+\'|"[^"]+")/', $m[1], null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$out = 'font-family:';
while (null !== ($piece = array_shift($pieces))) {
if ($piece[0] !== '"' && $piece[0] !== "'") {
$piece = preg_replace('/\\s+/', ' ', $piece);
$piece = preg_replace('/\\s?,\\s?/', ',', $piece);
}
$out .= $piece;
}
return $out . $m[2];
}
}

View File

@@ -1,47 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class MinifyHTML
{
/**
* Minify html
*
* <code>
* echo MinifyHTML::process($html);
* </code>
*
* @param string $buffer html
* @return string
*/
public static function process($html)
{
// Remove HTML comments (not containing IE conditional comments).
$html = preg_replace_callback('/<!--([\\s\\S]*?)-->/', 'MinifyHTML::_comments', $html);
// Trim each line.
$html = preg_replace('/^\\s+|\\s+$/m', '', $html);
// Return HTML
return $html;
}
protected static function _comments($m)
{
return (0 === strpos($m[1], '[') || false !== strpos($m[1], '<![')) ? $m[0] : '';
}
}

View File

@@ -1,50 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class MinifyJS
{
/**
* Minify js
*
* <code>
* echo MinifyJS::process($js);
* </code>
*
* @param string $buffer html
* @return string
*/
public static function process($js)
{
// newlines > linefeed
$js = str_replace(array("\r\n", "\r", "\n"), "\n", $js);
// empty lines > collapse
$js = preg_replace('/^[ \t]*|[ \t]*$/m', '', $js);
$js = preg_replace('/\n+/m', "\n", $js);
$js = trim($js);
// redundant whitespace > remove
$js = preg_replace('/(?<=[{}\[\]\(\)=><&\|;:,\?!\+-])[ \t]*|[ \t]*(?=[{}\[\]\(\)=><&\|;:,\?!\+-])/i', '', $js);
$js = preg_replace('/[ \t]+/', ' ', $js);
// redundant semicolons (followed by another semicolon or closing curly bracket) > remove
$js = preg_replace('/;\s*(?=[;}])/s', '', $js);
// Return JS
return $js;
}
}

View File

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

View File

@@ -1,227 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Number
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Convert bytes in 'KB','MB','GB','TiB','PiB'
*
* <code>
* echo Number::byteFormat(10000);
* </code>
*
* @param integer $size Data to convert
* @return string
*/
public static function byteFormat($size)
{
// Redefine vars
$size = (int) $size;
$unit = array('B', 'KB', 'MB', 'GB', 'TiB', 'PiB');
return @round($size/pow(1024, ($i=floor(log($size, 1024)))), 2).' '.$unit[($i < 0 ? 0 : $i)];
}
/**
* Convert 'KB','MB','GB' in bytes
*
* <code>
* echo Number::convertToBytes('10MB');
* </code>
*
* @param string $num Number to convert
* @return int
*/
public static function convertToBytes( $num ) {
$num = strtolower( $num );
$bytes = (int) $num;
if ( strpos( $num, 'k' ) !== false )
$bytes = intval( $num ) * 1024;
elseif ( strpos( $num, 'm' ) !== false )
$bytes = intval($num) * 1024 * 1024;
elseif ( strpos( $num, 'g' ) !== false )
$bytes = intval( $num ) * 1024 * 1024 * 1024;
return $bytes;
}
/**
* Converts a number into a more readable human-type number.
*
* <code>
* echo Number::quantity(7000); // 7K
* echo Number::quantity(7500); // 8K
* echo Number::quantity(7500, 1); // 7.5K
* </code>
*
* @param integer $num Num to convert
* @param integer $decimals Decimals
* @return string
*/
public static function quantity($num, $decimals = 0)
{
// Redefine vars
$num = (int) $num;
$decimals = (int) $decimals;
if ($num >= 1000 && $num < 1000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000)).'K';
} elseif ($num >= 1000000 && $num < 1000000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000)).'M';
} elseif ($num >= 1000000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000000)).'B';
}
return $num;
}
/**
* Checks if the value is between the minimum and maximum (min & max included).
*
* <code>
* if (Number::between(2, 10, 5)) {
* // do something...
* }
* </code>
*
* @param float $minimum The minimum.
* @param float $maximum The maximum.
* @param float $value The value to validate.
* @return boolean
*/
public static function between($minimum, $maximum, $value)
{
return ((float) $value >= (float) $minimum && (float) $value <= (float) $maximum);
}
/**
* Checks the value for an even number.
*
* <code>
* if (Number::even(2)) {
* // do something...
* }
* </code>
*
* @param integer $value The value to validate.
* @return boolean
*/
public static function even($value)
{
return (((int) $value % 2) == 0);
}
/**
* Checks if the value is greather than a given minimum.
*
* <code>
* if (Number::greaterThan(2, 10)) {
* // do something...
* }
* </code>
*
* @param float $minimum The minimum as a float.
* @param float $value The value to validate.
* @return boolean
*/
public static function greaterThan($minimum, $value)
{
return ((float) $value > (float) $minimum);
}
/**
* Checks if the value is smaller than a given maximum.
*
* <code>
* if (Number::smallerThan(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $maximum The maximum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function smallerThan($maximum, $value)
{
return ((int) $value < (int) $maximum);
}
/**
* Checks if the value is not greater than or equal a given maximum.
*
* <code>
* if (Number::maximum(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $maximum The maximum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function maximum($maximum, $value)
{
return ((int) $value <= (int) $maximum);
}
/**
* Checks if the value is greater than or equal to a given minimum.
*
* <code>
* if (Number::minimum(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $minimum The minimum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function minimum($minimum, $value)
{
return ((int) $value >= (int) $minimum);
}
/**
* Checks the value for an odd number.
*
* <code>
* if (Number::odd(2)) {
* // do something...
* }
* </code>
*
* @param integer $value The value to validate.
* @return boolean
*/
public static function odd($value)
{
return ! Number::even((int) $value);
}
}

View File

@@ -1,9 +0,0 @@
# Gelato Library
Gelato is a PHP5 library for kickass Web Applications.
## Links
- [Site](http://gelato.monstra.org)
- [Github Repository](https://github.com/MonstrLab/gelato)
Copyright (C) 2013 Romanenko Sergey / Awilum [awilum@msn.com]

View File

@@ -1,91 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Registry
{
/**
* Registry of variables
*
* @var array
*/
private static $registry = array();
/**
* Checks if an object with this name is in the registry.
*
* <code>
* if (Registry::exists('var')) {
* // Do something...
* }
* </code>
*
* @return bool
* @param string $name The name of the registry item to check for existence.
*/
public static function exists($name)
{
return isset(Registry::$registry[(string) $name]);
}
/**
* Registers a given value under a given name.
*
* <code>
* Registry::set('var', 'value');
* </code>
*
* @param string $name The name of the value to store.
* @param mixed[optional] $value The value that needs to be stored.
*/
public static function set($name, $value = null)
{
// redefine name
$name = (string) $name;
// delete item
if ($value === null) {
unset(Registry::$registry[$name]);
} else {
Registry::$registry[$name] = $value;
return Registry::get($name);
}
}
/**
* Fetch an item from the registry.
*
* <code>
* $var = Registry::get('var', 'value');
* </code>
*
* @return mixed
* @param string $name The name of the item to fetch.
*/
public static function get($name)
{
$name = (string) $name;
if ( ! isset(Registry::$registry[$name])) {
throw new RuntimeException('No item "' . $name . '" exists in the registry.');
}
return Registry::$registry[$name];
}
}

View File

@@ -1,92 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Token
{
/**
* Key name for token storage
*
* @var string
*/
protected static $token_name = 'security_token';
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Generate and store a unique token which can be used to help prevent
* [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
*
* <code>
* $token = Token::generate();
* </code>
*
* You can insert this token into your forms as a hidden field:
*
* <code>
* echo Form::hidden('csrf', Token::generate());
* </code>
*
* This provides a basic, but effective, method of preventing CSRF attacks.
*
* @param boolean $new force a new token to be generated?. Default is false
* @return string
*/
public static function generate($new = false)
{
// Get the current token
$token = Session::get(Token::$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(Token::$token_name, $token);
}
// Return token
return $token;
}
/**
* Check that the given token matches the currently stored security token.
*
* <code>
* if (Token::check($token)) {
* // Pass
* }
* </code>
*
* @param string $token token to check
* @return boolean
*/
public static function check($token)
{
return Token::token() === $token;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,679 +0,0 @@
<?php
/**
* Gelato Library
*
* This source file is part of the Gelato Library. More information,
* documentation and tutorials can be found at http://gelato.monstra.org
*
* @package Gelato
*
* @author Romanenko Sergey / Awilum <awilum@msn.com>
* @copyright 2012-2014 Romanenko Sergey / Awilum <awilum@msn.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Zip
{
public $zipdata = '';
public $directory = '';
public $entries = 0;
public $file_num = 0;
public $offset = 0;
public $now;
private $_archive_info = array();
private $_zip_signature = "\x50\x4b\x03\x04";
private $_dir_signature = "\x50\x4b\x01\x02";
private $_central_signature_end = "\x50\x4b\x05\x06";
private $farc = null;
/**
* Constructor
*/
public function __construct()
{
$this->now = time();
}
/**
* Zip factory
*
* <code>
* Zip::factory();
* </code>
*
* @return Zip
*/
public static function factory()
{
return new Zip();
}
/**
* Add Directory
*
* <code>
* Zip::factory()->addDir('test');
* </code>
*
* @param mixed $directory The directory name. Can be string or array
*/
public function addDir($directory)
{
foreach ((array) $directory as $dir) {
if ( ! preg_match("|.+/$|", $dir)) {
$dir .= '/';
}
$dir_time = $this->_get_mod_time($dir);
$this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']);
}
return $this;
}
/**
* Get file/directory modification time
*
* @param string $dir Full path to the dir
* @return array
*/
protected function _get_mod_time($dir)
{
// If this is a newly created file/dir, we will set the time to 'now'
$date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now);
$time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2;
$time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday'];
return $time;
}
/**
* Add Directory
*
* @param string $dir The directory name
* @param integer $file_mtime File mtime
* @param integer $file_mdate File mdate
*/
private function _add_dir($dir, $file_mtime, $file_mdate)
{
$dir = str_replace("\\", "/", $dir);
$this->zipdata .=
"\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', 0) // crc32
.pack('V', 0) // compressed filesize
.pack('V', 0) // uncompressed filesize
.pack('v', strlen($dir)) // length of pathname
.pack('v', 0) // extra field length
.$dir
// below is "data descriptor" segment
.pack('V', 0) // crc32
.pack('V', 0) // compressed filesize
.pack('V', 0); // uncompressed filesize
$this->directory .=
"\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V',0) // crc32
.pack('V',0) // compressed filesize
.pack('V',0) // uncompressed filesize
.pack('v', strlen($dir)) // length of pathname
.pack('v', 0) // extra field length
.pack('v', 0) // file comment length
.pack('v', 0) // disk number start
.pack('v', 0) // internal file attributes
.pack('V', 16) // external file attributes - 'directory' bit set
.pack('V', $this->offset) // relative offset of local header
.$dir;
$this->offset = strlen($this->zipdata);
$this->entries++;
}
/**
* Add Data to Zip
*
* <code>
* Zip::factory()->addData('test.txt', 'Some test text here');
* </code>
*
* Lets you add files to the archive. If the path is included
* in the filename it will be placed within a directory. Make
* sure you use add_dir() first to create the folder.
*
* @param mixed $filepath Full path to the file
* @param string $data Data
*/
public function addData($filepath, $data = null)
{
if (is_array($filepath)) {
foreach ($filepath as $path => $data) {
$file_data = $this->_get_mod_time($path);
$this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
} else {
$file_data = $this->_get_mod_time($filepath);
$this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
return $this;
}
/**
* Add Data to Zip
*
* @param string $filepath Full path to the file
* @param string $data The data to be encoded
* @param integer $file_mtime File mtime
* @param integer $file_mdate File mdate
*/
private function _add_data($filepath, $data, $file_mtime, $file_mdate)
{
$filepath = str_replace("\\", "/", $filepath);
$uncompressed_size = strlen($data);
$crc32 = crc32($data);
$gzdata = gzcompress($data);
$gzdata = substr($gzdata, 2, -4);
$compressed_size = strlen($gzdata);
$this->zipdata .=
"\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', $crc32)
.pack('V', $compressed_size)
.pack('V', $uncompressed_size)
.pack('v', strlen($filepath)) // length of filename
.pack('v', 0) // extra field length
.$filepath
.$gzdata; // "file data" segment
$this->directory .=
"\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', $crc32)
.pack('V', $compressed_size)
.pack('V', $uncompressed_size)
.pack('v', strlen($filepath)) // length of filename
.pack('v', 0) // extra field length
.pack('v', 0) // file comment length
.pack('v', 0) // disk number start
.pack('v', 0) // internal file attributes
.pack('V', 32) // external file attributes - 'archive' bit set
.pack('V', $this->offset) // relative offset of local header
.$filepath;
$this->offset = strlen($this->zipdata);
$this->entries++;
$this->file_num++;
}
/**
* Read the contents of a file and add it to the zip
*
* <code>
* Zip::factory()->readFile('test.txt');
* </code>
*
* @param string $path Path
* @param boolean $preserve_filepath Preserve filepath
* @return mixed
*/
public function readFile($path, $preserve_filepath = false)
{
if ( ! file_exists($path)) {
return false;
}
if (false !== ($data = file_get_contents($path))) {
$name = str_replace("\\", "/", $path);
if ($preserve_filepath === false) {
$name = preg_replace("|.*/(.+)|", "\\1", $name);
}
$this->addData($name, $data);
return $this;
}
return false;
}
/**
* Read a directory and add it to the zip.
*
* <code>
* Zip::factory()->readDir('test/');
* </code>
*
* This function recursively reads a folder and everything it contains (including
* sub-folders) and creates a zip based on it. Whatever directory structure
* is in the original file path will be recreated in the zip file.
*
* @param string $path Path to source
* @param boolean $preserve_filepath Preserve filepath
* @param string $root_path Root path
* @return mixed
*/
public function readDir($path, $preserve_filepath = true, $root_path = null, $exclude_files = array())
{
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) == '.' || in_array($path.$file, $exclude_files)) {
continue;
}
if (@is_dir($path.$file)) {
$this->readDir($path.$file."/", $preserve_filepath, $root_path, $exclude_files);
} else {
if (false !== ($data = file_get_contents($path.$file))) {
$name = str_replace("\\", "/", $path);
if ($preserve_filepath === false) {
$name = str_replace($root_path, '', $name);
}
$this->addData($name.$file, $data);
}
}
}
return $this;
}
/**
* Get the Zip file
*
* <code>
* Zip::factory()->getZip();
* </code>
*
* @return string
*/
public function getZip()
{
// Is there any data to return?
if ($this->entries == 0) {
return false;
}
$zip_data = $this->zipdata;
$zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00";
$zip_data .= pack('v', $this->entries); // total # of entries "on this disk"
$zip_data .= pack('v', $this->entries); // total # of entries overall
$zip_data .= pack('V', strlen($this->directory)); // size of central dir
$zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir
$zip_data .= "\x00\x00"; // .zip file comment length
return $zip_data;
}
/**
* Write File to the specified directory
*
* <code>
* Zip::factory()->readDir('test1/')->readDir('test2/')->archive('test.zip');
* </code>
*
* @param string $filepath The file name
* @return boolean
*/
public function archive($filepath)
{
if ( ! ($fp = @fopen($filepath, "w"))) {
return false;
}
flock($fp, LOCK_EX);
fwrite($fp, $this->getZip());
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
/**
* Initialize Data
*
* <code>
* Zip::factory()->clearData();
* </code>
*
* Lets you clear current zip data. Useful if you need to create
* multiple zips with different data.
*/
public function clearData()
{
$this->zipdata = '';
$this->directory = '';
$this->entries = 0;
$this->file_num = 0;
$this->offset = 0;
}
public function extract($zip_file, $target_dir = null)
{
$chmod = 0777;
$this->_archive_info = array();
$files = $this->_read_archive($zip_file);
if (!$files) {
return false;
}
$file_locations = array();
foreach ($files as $file => $trash) {
$dirname = pathinfo($file, PATHINFO_DIRNAME);
$folders = explode('/', $dirname);
$out_dn = $target_dir . '/' . $dirname;
if ( !is_dir($out_dn)) {
$str = '';
foreach ($folders as $folder) {
$str = $str ? $str . '/' . $folder : $folder;
if ( !is_dir($target_dir . '/' . $str)) {
if ( ! @mkdir($target_dir . '/' . $str)) {
return false;
}
chmod($target_dir . '/' . $str, $chmod);
}
}
}
if (substr($file, -1, 1) == '/') {
continue;
}
$file_locations[] = $file_location = $target_dir . '/' . $file;
$this->_extract_file($file, $file_location);
}
$this->_archive_info = array();
return $file_locations;
}
private function _read_archive($zip_file)
{
if (sizeof($this->_archive_info)) {
return $this->_archive_info;
}
$fh = fopen($zip_file, 'r');
$this->farc = &$fh;
if ( !$fh) {
return false;
}
if ( !$this->_read_file_list_by_eof($fh)) {
if ( !$this->_read_files_by_signatures($fh)) {
return false;
}
}
return $this->_archive_info;
}
private function _read_file_list_by_eof(&$fh)
{
for ($x = 0; $x < 1024; $x++) {
fseek($fh, -22 - $x, SEEK_END);
$signature = fread($fh, 4);
if ($signature == $this->_central_signature_end) {
$eodir['disk_number_this'] = unpack("v", fread($fh, 2));
$eodir['disk_number'] = unpack("v", fread($fh, 2));
$eodir['total_entries_this'] = unpack("v", fread($fh, 2));
$eodir['total_entries'] = unpack("v", fread($fh, 2));
$eodir['size_of_cd'] = unpack("V", fread($fh, 4));
$eodir['offset_start_cd'] = unpack("V", fread($fh, 4));
$zip_comment_lenght = unpack("v", fread($fh, 2));
$eodir['zipfile_comment'] = $zip_comment_lenght[1] ? fread($fh, $zip_comment_lenght[1]) : '';
fseek($fh, $eodir['offset_start_cd'][1]);
$signature = fread($fh, 4);
while ($signature == $this->_dir_signature) {
$dir['version_madeby'] = unpack("v", fread($fh, 2));
$dir['version_needed'] = unpack("v", fread($fh, 2));
$dir['general_bit_flag'] = unpack("v", fread($fh, 2));
$dir['compression_method'] = unpack("v", fread($fh, 2));
$dir['lastmod_time'] = unpack("v", fread($fh, 2));
$dir['lastmod_date'] = unpack("v", fread($fh, 2));
$dir['crc-32'] = fread($fh, 4);
$dir['compressed_size'] = unpack("V", fread($fh, 4));
$dir['uncompressed_size'] = unpack("V", fread($fh, 4));
$zip_file_length = unpack("v", fread($fh, 2));
$extra_field_length = unpack("v", fread($fh, 2));
$fileCommentLength = unpack("v", fread($fh, 2));
$dir['disk_number_start'] = unpack("v", fread($fh, 2));
$dir['internal_attributes'] = unpack("v", fread($fh, 2));
$dir['external_attributes1'] = unpack("v", fread($fh, 2));
$dir['external_attributes2'] = unpack("v", fread($fh, 2));
$dir['relative_offset'] = unpack("V", fread($fh, 4));
$dir['file_name'] = fread($fh, $zip_file_length[1]);
$dir['extra_field'] = $extra_field_length[1] ? fread($fh, $extra_field_length[1]) : '';
$dir['file_comment'] = $fileCommentLength[1] ? fread($fh, $fileCommentLength[1]) : '';
$binary_mod_date = str_pad(decbin($dir['lastmod_date'][1]), 16, '0', STR_PAD_LEFT);
$binary_mod_time = str_pad(decbin($dir['lastmod_time'][1]), 16, '0', STR_PAD_LEFT);
$last_mod_year = bindec(substr($binary_mod_date, 0, 7)) + 1980;
$last_mod_month = bindec(substr($binary_mod_date, 7, 4));
$last_mod_day = bindec(substr($binary_mod_date, 11, 5));
$last_mod_hour = bindec(substr($binary_mod_time, 0, 5));
$last_mod_minute = bindec(substr($binary_mod_time, 5, 6));
$last_mod_second = bindec(substr($binary_mod_time, 11, 5));
$central_dir_list[$dir['file_name']] = array(
'version_madeby' => $dir['version_madeby'][1],
'version_needed' => $dir['version_needed'][1],
'general_bit_flag' => str_pad(decbin($dir['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT),
'compression_method' => $dir['compression_method'][1],
'lastmod_datetime' => mktime($last_mod_hour, $last_mod_minute, $last_mod_second, $last_mod_month, $last_mod_day, $last_mod_year),
'crc-32' => str_pad(dechex(ord($dir['crc-32'][3])), 2, '0', STR_PAD_LEFT) .
str_pad(dechex(ord($dir['crc-32'][2])), 2, '0', STR_PAD_LEFT) .
str_pad(dechex(ord($dir['crc-32'][1])), 2, '0', STR_PAD_LEFT) .
str_pad(dechex(ord($dir['crc-32'][0])), 2, '0', STR_PAD_LEFT),
'compressed_size' => $dir['compressed_size'][1],
'uncompressed_size' => $dir['uncompressed_size'][1],
'disk_number_start' => $dir['disk_number_start'][1],
'internal_attributes' => $dir['internal_attributes'][1],
'external_attributes1' => $dir['external_attributes1'][1],
'external_attributes2' => $dir['external_attributes2'][1],
'relative_offset' => $dir['relative_offset'][1],
'file_name' => $dir['file_name'],
'extra_field' => $dir['extra_field'],
'file_comment' => $dir['file_comment'],
);
$signature = fread($fh, 4);
}
if (isset($central_dir_list)) {
foreach ($central_dir_list as $filename => $details) {
$i = $this->_get_file_header($fh, $details['relative_offset']);
$this->_archive_info[$filename]['file_name'] = $filename;
$this->_archive_info[$filename]['compression_method'] = $details['compression_method'];
$this->_archive_info[$filename]['version_needed'] = $details['version_needed'];
$this->_archive_info[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
$this->_archive_info[$filename]['crc-32'] = $details['crc-32'];
$this->_archive_info[$filename]['compressed_size'] = $details['compressed_size'];
$this->_archive_info[$filename]['uncompressed_size'] = $details['uncompressed_size'];
$this->_archive_info[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
$this->_archive_info[$filename]['extra_field'] = $i['extra_field'];
$this->_archive_info[$filename]['contents_start_offset'] = $i['contents_start_offset'];
}
}
return true;
}
}
return true;
}
private function _read_files_by_signatures(&$fh)
{
fseek($fh, 0);
$return = false;
for (;;) {
$details = $this->_get_file_header($fh);
if ( !$details) {
fseek($fh, 12 - 4, SEEK_CUR);
$details = $this->_get_file_header($fh);
}
if ( !$details) {
break;
}
$filename = $details['file_name'];
$this->_archive_info[$filename] = $details;
$return = true;
}
return $return;
}
private function _get_file_header(&$fh, $start_offset = FALSE)
{
if ($start_offset !== false) {
fseek($fh, $start_offset);
}
$signature = fread($fh, 4);
if ($signature == $this->_zip_signature) {
$file['version_needed'] = unpack("v", fread($fh, 2));
$file['general_bit_flag'] = unpack("v", fread($fh, 2));
$file['compression_method'] = unpack("v", fread($fh, 2));
$file['lastmod_time'] = unpack("v", fread($fh, 2));
$file['lastmod_date'] = unpack("v", fread($fh, 2));
$file['crc-32'] = fread($fh, 4);
$file['compressed_size'] = unpack("V", fread($fh, 4));
$file['uncompressed_size'] = unpack("V", fread($fh, 4));
$zip_file_length = unpack("v", fread($fh, 2));
$extra_field_length = unpack("v", fread($fh, 2));
$file['file_name'] = fread($fh, $zip_file_length[1]);
$file['extra_field'] = $extra_field_length[1] ? fread($fh, $extra_field_length[1]) : '';
$file['contents_start_offset'] = ftell($fh);
fseek($fh, $file['compressed_size'][1], SEEK_CUR);
$binary_mod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT);
$binary_mod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT);
$last_mod_year = bindec(substr($binary_mod_date, 0, 7)) + 1980;
$last_mod_month = bindec(substr($binary_mod_date, 7, 4));
$last_mod_day = bindec(substr($binary_mod_date, 11, 5));
$last_mod_hour = bindec(substr($binary_mod_time, 0, 5));
$last_mod_minute = bindec(substr($binary_mod_time, 5, 6));
$last_mod_second = bindec(substr($binary_mod_time, 11, 5));
return array(
'file_name' => $file['file_name'],
'compression_method' => $file['compression_method'][1],
'version_needed' => $file['version_needed'][1],
'lastmod_datetime' => mktime($last_mod_hour, $last_mod_minute, $last_mod_second, $last_mod_month, $last_mod_day, $last_mod_year),
'crc-32' => str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT) .
str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT) .
str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT) .
str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT),
'compressed_size' => $file['compressed_size'][1],
'uncompressed_size' => $file['uncompressed_size'][1],
'extra_field' => $file['extra_field'],
'general_bit_flag' => str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT),
'contents_start_offset' => $file['contents_start_offset']
);
}
return false;
}
private function _extract_file($compressed_file_name, $target_file_name = false)
{
if ( !sizeof($this->_archive_info)) {
return false;
}
$fdetails = &$this->_archive_info[$compressed_file_name];
if ( ! isset($this->_archive_info[$compressed_file_name])) {
return false;
}
if (substr($compressed_file_name, -1) == '/') {
return false;
}
if ( !$fdetails['uncompressed_size']) {
return $target_file_name ? file_put_contents($target_file_name, '') : '';
}
fseek($this->farc, $fdetails['contents_start_offset']);
$ret = $this->_uncompress(
fread($this->farc, $fdetails['compressed_size']),
$fdetails['compression_method'],
$fdetails['uncompressed_size'],
$target_file_name
);
if ($target_file_name) {
chmod($target_file_name, 0644);
}
return $ret;
}
private function _uncompress($content, $mode, $uncompressed_size, $target_file_name = false)
{
switch ($mode) {
case 0:
return $target_file_name ? file_put_contents($target_file_name, $content) : $content;
case 8:
return $target_file_name
? file_put_contents($target_file_name, gzinflate($content, $uncompressed_size))
: gzinflate($content, $uncompressed_size);
case 12:
return $target_file_name
? file_put_contents($target_file_name, bzdecompress($content)) : bzdecompress($content);
default:
return false;
}
}
}

View File

@@ -1,21 +0,0 @@
Gelato 1.0.3, 2013-04-03
------------------------
- Html Class: obfuscate() method added.
- Html Class: email() method added.
- Html Class: missing $macros var added.
Gelato 1.0.2, 2013-03-17
------------------------
- Added support for PHP 5.2.3
Gelato 1.0.1, 2013-03-05
------------------------
- New constant GELATO_CLASS_LOADER instead of GELATO_AUTOLOADER
- ErrorHanler Class Improvements.
- Log Class Improvements.
- ClassLoader: new method register() added.
- Define __DIR__ constant for PHP 5.2.x
Gelato 1.0.0, 2013-02-26
------------------------
- Initial release

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,40 +0,0 @@
Blog
================
### Usage
#### Get Post
<?php echo Blog::getPost(); ?>
#### Get Posts
<?php echo Blog::getPosts(); ?>
#### Get 5 Posts (could be any amount, 5 or 1 or 25):
<?php echo Blog::getPosts(5); ?>
#### Get related Posts
<?php echo Blog::getRelatedPosts(); ?>
#### Get 4 latest posts from Blog
<?php echo Blog::getPostsBlock(4); ?>
#### Get Tags&Keywords
<?php Blog::getTags(); ?>
#### Get Tags&Keywords for current page
<?php Blog::getTags(Page::slug()); ?>
Get Post Title
<?php echo Blog::getPostTitle(); ?>
### Shortcode for content
#### Divided post into 2 parts (short and full)
{cut}
Example:
<p>Best free themes for Monstra CMS at monstrathemes.com</p>
{cut}
<p>There is going to display your content as blog post =)</p>

View File

@@ -1,399 +0,0 @@
<?php
/**
* Blog plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.7.3
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Blog', 'blog'),
__('Blog plugin for Monstra', 'blog'),
'1.7.3',
'Awilum',
'http://monstra.org/');
// Add action
Action::add('frontend_pre_render', 'Blog::_rss');
/**
* Blog Class
*/
class Blog {
/**
* Parrent page name(slug)
*
* @var string
*/
public static $parent_page_name = 'blog';
/**
* Get tags
*
* <code>
* echo Blog::getTags();
* </code>
*
* @return string
*/
public static function getTags($slug = null) {
// Display view
return View::factory('blog/views/frontend/tags')
->assign('tags', Blog::getTagsArray($slug))
->render();
}
/**
* Get breadcrumbs
*
* <code>
* echo Blog::breadcrumbs();
* </code>
*
* @return string
*/
public static function breadcrumbs() {
$current_page = Pages::$requested_page;
$parent_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('blog/views/frontend/breadcrumbs')
->assign('current_page', $current_page)
->assign('page', $page)
->assign('parent', $parent)
->assign('parent_page', $parent_page)
->display();
}
}
/**
* Get tags array
*
* <code>
* echo Blog::getTagsArray();
* </code>
*
* @return array
*/
public static function getTagsArray($slug = null) {
// Init vars
$tags = array();
$tags_string = '';
if ($slug == null) {
$posts = Pages::$pages->select('[parent="'.Blog::$parent_page_name.'" and status="published"]', 'all');
} else {
$posts = Pages::$pages->select('[parent="'.Blog::$parent_page_name.'" and status="published" and slug="'.$slug.'"]', 'all');
}
foreach($posts as $post) {
if (isset($post['tags'])) {
$tags_string .= $post['tags'].',';
}
}
$tags_string = substr($tags_string, 0, strlen($tags_string)-1);
// Explode tags in tags array
$tags = explode(',', $tags_string);
// Remove empty array elementss
foreach ($tags as $key => $value) {
if ($tags[$key] == '') {
unset($tags[$key]);
}
}
// Trim tags
array_walk($tags, create_function('&$val', '$val = trim($val);'));
// Get unique tags
$tags = array_unique($tags);
// Return tags
return $tags;
}
/**
* Get posts
*
* <code>
* // Get all posts
* echo Blog::getPosts();
*
* // Get last 5 posts
* echo Blog::getPosts(5);
* </code>
*
* @param integer $num Number of posts to show
* @return string
*/
public static function getPosts($nums = 10) {
// Get page param
$page = (Request::get('page')) ? (int)Request::get('page') : 1;
if (Request::get('tag')) {
$query = '[parent="'.Blog::$parent_page_name.'" and status="published" and contains(tags, "'.Request::get('tag').'")]';
Notification::set('tag', Request::get('tag'));
} else {
$query = '[parent="'.Blog::$parent_page_name.'" and status="published"]';
Notification::clean();
}
// Get Elements Count
$elements = count(Pages::$pages->select($query, 'all'));
// Get Pages Count
$pages = ceil($elements/$nums);
if ($page < 1) {
$page = 1;
} elseif ($page > $pages) {
$page = $pages;
}
$start = ($page-1)*$nums;
// If there is no posts
if ($start < 0) $start = 0;
// Get posts and sort by DESC
$posts = Pages::$pages->select($query, $nums, $start, array('slug', 'title', 'author', 'date'), 'date', 'DESC');
// Loop
foreach($posts as $key => $post) {
$post_short = explode("{cut}", Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . $post['id'] . '.page.txt')));
$posts[$key]['content'] = Filter::apply('content', $post_short[0]);
}
// Display view
return View::factory('blog/views/frontend/index')
->assign('posts', $posts)
->render().
View::factory('blog/views/frontend/pager')
->assign('pages', $pages)
->assign('page', $page)
->render();
}
/**
* Get posts block
*
* <code>
* // Get all posts
* echo Blog::getPostsBlock();
*
* // Get last 5 posts
* echo Blog::getPostsBlock(5);
* </code>
*
* @param integer $num Number of posts to show
* @return string
*/
public static function getPostsBlock($nums = 10) {
// XPath Query
$query = '[parent="'.Blog::$parent_page_name.'" and status="published"]';
// Get posts and sort by DESC
$posts = Pages::$pages->select($query, $nums, 0, array('slug', 'title', 'author', 'date'), 'date', 'DESC');
// Loop
foreach($posts as $key => $post) {
$post_short = explode("{cut}", Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . $post['id'] . '.page.txt')));
$posts[$key]['content'] = Filter::apply('content', $post_short[0]);
}
// Display view
return View::factory('blog/views/frontend/block')
->assign('posts', $posts)
->render();
}
/**
* Get related posts
*
* <code>
* echo Blog::getRelatedPosts();
* </code>
*
* @return string
*/
public static function getRelatedPosts($limit = null) {
$related_posts = array();
$tags = Blog::getTagsArray(Page::slug());
foreach($tags as $tag) {
$query = '[parent="'.Blog::$parent_page_name.'" and status="published" and contains(tags, "'.$tag.'") and slug!="'.Page::slug().'"]';
if ($result = Arr::subvalSort(Pages::$pages->select($query, ($limit == null) ? 'all' : (int)$limit), 'date', 'DESC')) {
$related_posts = $result;
}
}
// Display view
return View::factory('blog/views/frontend/related_posts')
->assign('related_posts', $related_posts)
->render();
}
/**
* Get post content
*
* <code>
* echo Blog::getPost();
* </code>
*
* @return string
*/
public static function getPost() {
// Get post
$post = Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . Pages::$page['id'] . '.page.txt'));
// Apply content filter
$post = Filter::apply('content', $post);
// Remove {cut} shortcode
$post = strtr($post, array('{cut}' => ''));
// Return post
return $post;
}
/**
* Get post content before cut
*
* <code>
* echo Blog::getPostBeforeCut('home');
* </code>
*
* @return string
*/
public static function getPostBeforeCut($slug) {
$page = Pages::$pages->select('[slug="'.$slug.'"]', null);
// Get post
$post = explode("{cut}", Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt')));
// Apply content filter
$post_content = Filter::apply('content', $post[0]);
// Return post
return $post_content;
}
/**
* Get post content after cut
*
* <code>
* echo Blog::getPostAfterCut('home');
* </code>
*
* @return string
*/
public static function getPostAfterCut($slug) {
$page = Pages::$pages->select('[slug="'.$slug.'"]', null);
// Get post
$post = explode("{cut}", Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt')));
// Apply content filter
$post_content = Filter::apply('content', $post[1]);
// Return post
return $post_content;
}
/**
* Get Blog Post title
*
* <code>
* echo Blog::getPostTitle();
* </code>
*
* @return string
*/
public static function getPostTitle() {
return Page::title();
}
/**
* Get Blog Post Date
*
* <code>
* echo Blog::getPostDate();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function getPostDate($format = 'Y-m-d') {
return Page::date($format);
}
/**
* Get author of current post
*
* <code>
* echo Blog::getPostAuthor();
* </code>
*
* @return string
*/
public static function getPostAuthor()
{
return Page::author();
}
/**
* _rss
*/
public static function _rss() {
if (Uri::segment(0) == 'rss') {
include PLUGINS . DS . 'blog' . DS . 'rss.php';
Request::shutdown();
}
}
}

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/blog/blog.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>15</plugin_priority>
<plugin_name>Blog</plugin_name>
<plugin_description>Blog plugin for Monstra</plugin_description>
<plugin_version>1.7.3</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -1,12 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Blog',
'Blog plugin for Monstra' => 'Blog plugin for Monstra',
'begin' => 'begin',
'end' => 'end',
'prev' => 'prev',
'next' => 'next',
)
);

View File

@@ -1,12 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Blog',
'Blog plugin for Monstra' => 'Blog plugin for Monstra',
'begin' => 'comienzo',
'end' => 'final',
'prev' => 'anterior',
'next' => 'siguiente',
)
);

View File

@@ -1,12 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Blog',
'Blog plugin for Monstra' => 'Wtyczka Blog dla systemu Monstra',
'begin' => 'początek',
'end' => 'koniec',
'prev' => 'poprzedni',
'next' => 'następny',
)
);

View File

@@ -1,13 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Блог',
'Blog plugin for Monstra' => 'Плагин блога для Monstra',
'begin' => 'начало',
'end' => 'конец',
'prev' => 'назад',
'next' => 'вперед',
'Related posts' => 'Статьи по теме',
)
);

View File

@@ -1,11 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Blog',
'Blog plugin for Monstra' => 'Blog, dodatak za Monstra',
'begin' => 'početak',
'end' => 'kraj',
'prev' => 'predhodna',
'next' => 'sledeća',
)
);

View File

@@ -1,12 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Günce',
'Blog plugin for Monstra' => 'Monstra için günce eklentisi',
'begin' => 'Baş',
'end' => 'Son',
'prev' => 'Önceki',
'next' => 'Sonraki',
)
);

View File

@@ -1,13 +0,0 @@
<?php
return array(
'blog' => array(
'Blog' => 'Блог',
'Blog plugin for Monstra' => 'Плагін блога для Monstra',
'begin' => 'початок',
'end' => 'кінець',
'prev' => 'назад',
'next' => 'вперед',
'Related posts' => 'Статті по темі',
)
);

View File

@@ -1,34 +0,0 @@
<?php
// Get all posts for blog parent page/post
$posts = Pages::$pages->select('[parent="'.Blog::$parent_page_name.'" and status="published"]', 5, 0, array('slug', 'title', 'author', 'date'), 'date', 'DESC');
// Date now
$now = date("D, d M Y H:i:s T");
ob_end_clean();
?>
<?php header('Content-type: text/xml; charset="utf-8"'); ?>
<?php echo'<?xml version="1.0" encoding="utf-8"?>'."\n"; ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>MonstraCMS::BLOG::RSS</title>
<link><?php echo Option::get('siteurl'); ?>/blog</link>
<description>The latest updates for <?php echo Option::get('sitename'); ?>.</description>
<language>en-us</language>
<pubDate><?php echo $now; ?></pubDate>
<lastBuildDate><?php echo $now; ?></lastBuildDate>
<atom:link href="<?php echo Option::get('siteurl'); ?>/rss.php" rel="self" type="application/rss+xml" />
<generator>Monstra</generator>
<?php foreach ($posts as $post) { ?>
<item>
<title><?php echo $post['title']; ?></title>
<link><?php echo Option::get('siteurl').'/blog/'.$post['slug']; ?></link>
<guid><?php echo Option::get('siteurl').'/blog/'.$post['slug']; ?></guid>
<pubDate><?php echo Date::format($post['date'], 'd M Y'); ?></pubDate>
<description><![CDATA[<?php echo Text::toHtml(Text::cut(File::getContent(STORAGE . DS . 'pages' . DS . $post['id'] . '.page.txt'), 300)); ?>]]></description>
<author><?php echo $post['author']; ?></author>
</item>
<?php } ?>
</channel>
</rss>
<?php Response::status(200); ?>

View File

@@ -1,7 +0,0 @@
<?php foreach($posts as $post) { ?>
<h3 class="monstra-blog-title"><a href="<?php echo Option::get('siteurl'); ?>/<?php echo Blog::$parent_page_name; ?>/<?php echo $post['slug'] ?>"><?php echo $post['title']; ?></a></h3>
<small class="monstra-blog-date"><?php echo Date::format($post['date'], 'd M Y'); ?></small>
<div class="monstra-blog-post">
<?php echo $post['content']; ?>
</div>
<?php } ?>

View File

@@ -1,5 +0,0 @@
<?php if ($parent) { ?>
<a href="<?php echo Site::url()."/".$page['parent']; ?><?php if(Notification::get('tag')) { ?>?tag=<?php echo Notification::get('tag'); ?><?php } ?>"><?php echo $parent_page['title']; ?></a>&nbsp;<span>&rarr;</span>&nbsp;<a href="<?php echo Site::url().$page['parent'].'/'.$page['slug']; ?>"><?php echo $page['title']; ?></a>
<?php } else { ?>
<a href="<?php echo Site::url()."/".$page['slug']; ?><?php if(Notification::get('tag')) { ?>?tag=<?php echo Notification::get('tag'); ?><?php } ?>"><?php echo $page['title']; ?></a>
<?php } ?>

View File

@@ -1,7 +0,0 @@
<?php foreach($posts as $post) { ?>
<h3 class="monstra-blog-title"><a href="<?php echo Option::get('siteurl'); ?>/<?php echo Blog::$parent_page_name; ?>/<?php echo $post['slug'] ?>"><?php echo $post['title']; ?></a></h3>
<small class="monstra-blog-date"><?php echo Date::format($post['date'], 'd M Y'); ?> / <?php echo $post['author']; ?></small>
<div class="monstra-blog-post">
<?php echo $post['content']; ?>
</div>
<?php } ?>

View File

@@ -1,29 +0,0 @@
<br><br>
<?php
if (Request::get('tag')) $tag = '&tag='.Request::get('tag'); else $tag = '';
$neighbours = 6;
$left_neighbour = $page - $neighbours;
if ($left_neighbour < 1) $left_neighbour = 1;
$right_neighbour = $page + $neighbours;
if ($right_neighbour > $pages) $right_neighbour = $pages;
if ($page > 1) {
echo ' <a href="?page=1'.$tag.'">'.__('begin', 'blog').'</a> ... <a href="?page=' . ($page-1) . $tag.'"> '.__('prev', 'blog').'</a> ';
}
for ($i=$left_neighbour; $i<=$right_neighbour; $i++) {
if ($i != $page) {
echo ' <a href="?page=' . $i . $tag.'">' . $i . '</a> ';
} else {
echo ' <b>' . $i . '</b> ';
}
}
if ($page < $pages) {
echo ' <a href="?page=' . ($page+1) . $tag.'">'.__('next', 'blog').'</a> ... <a href="?page=' . $pages . $tag.'">'.__('end', 'blog').'</a> ';
}
?>

View File

@@ -1,7 +0,0 @@
<br><br>
<b><?php echo __('Related posts', 'blog'); ?>:</b>
<div>
<?php foreach($related_posts as $related_post) { ?>
<a href="<?php echo Option::get('siteurl'); ?>/<?php echo Blog::$parent_page_name; ?>/<?php echo $related_post['slug']; ?>"><?php echo $related_post['title']; ?></a><br>
<?php } ?>
</div>

View File

@@ -1,3 +0,0 @@
<?php foreach($tags as $tag) { ?>
<a href="<?php echo Option::get('siteurl'); ?>/<?php echo Blog::$parent_page_name; ?>?tag=<?php echo $tag; ?>" class="monstra-blog-tag"><span class="label label-primary"><?php echo $tag; ?></span></a>
<?php } ?>

View File

@@ -1,104 +0,0 @@
<?php
// Add plugin navigation link
Navigation::add(__('Backups', 'backup'), 'system', 'backup', 3);
/**
* Backup Admin Class
*/
class BackupAdmin extends Backend
{
/**
* Backup admin
*/
public static function main()
{
$backups_path = ROOT . DS . 'backups';
// Create backup
// -------------------------------------
if (Request::post('create_backup')) {
if (Security::check(Request::post('csrf'))) {
@set_time_limit(0);
@ini_set("memory_limit", "512M");
$zip = Zip::factory();
// Add storage folder
$zip->readDir(STORAGE . DS, false);
// Add public folder
$zip->readDir(ROOT . DS . 'public' . DS, false);
// Add plugins folder
$zip->readDir(PLUGINS . DS, false, null, array(PLUGINS . DS . 'box'));
if ($zip->archive($backups_path . DS . Date::format(time(), "Y-m-d-H-i-s").'.zip')) {
Notification::set('success', __('Backup was created', 'backup'));
} else {
Notification::set('error', __('Backup was not created', 'backup'));
}
Request::redirect(Option::get('siteurl').'/admin/index.php?id=backup');
} else { die('Request was denied because it contained an invalid security token. Please refresh the page and try again.'); }
}
// Delete backup
// -------------------------------------
if (Request::get('id') == 'backup' && Request::get('delete_file')) {
if (Security::check(Request::get('token'))) {
if (File::delete($backups_path . DS . Request::get('delete_file'))) {
Notification::set('success', __('Backup was deleted', 'backup'));
} else {
Notification::set('error', __('Backup was not deleted', 'backup'));
}
Request::redirect(Option::get('siteurl').'/admin/index.php?id=backup');
} else { die('Request was denied because it contained an invalid security token. Please refresh the page and try again.'); }
}
// Download backup
// -------------------------------------
if (Request::get('download')) {
if (Security::check(Request::get('token'))) {
File::download($backups_path . DS . Request::get('download'));
} else { die('Request was denied because it contained an invalid security token. Please refresh the page and try again.'); }
}
// Restore backup
// -------------------------------------
if (Request::get('restore')) {
if (Security::check(Request::get('token'))) {
$tmp_dir = ROOT . DS . 'tmp' . DS . uniqid('backup_');
if (Dir::create($tmp_dir)) {
$file_locations = Zip::factory()->extract($backups_path . DS . Request::get('restore'), $tmp_dir);
if (!empty($file_locations)) {
Dir::copy($tmp_dir, ROOT . DS);
Notification::set('success', __('Backup was restored', 'backup'));
} else {
Notification::set('error', __('Unzip error', 'backup'));
}
} else {
Notification::set('error', __('Backup was not restored', 'backup'));
}
Request::redirect(Option::get('siteurl').'/admin/index.php?id=backup');
} else { die('Request was denied because it contained an invalid security token. Please refresh the page and try again.'); }
}
// Display view
View::factory('box/backup/views/backend/index')
->assign('backups_list', File::scan($backups_path, '.zip'))
->display();
}
}

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