diff --git a/.htaccess b/.htaccess index 753e230..9685b5a 100644 --- a/.htaccess +++ b/.htaccess @@ -19,7 +19,7 @@ Options -Indexes # Setting rewrite rules. RewriteEngine on - RewriteBase /%siteurlhere%/ + RewriteBase /projects/monstra-cms/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [QSA,L] diff --git a/admin/index.php b/admin/index.php index 0393d77..14a51e8 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,161 +1,159 @@ select("[login='" . trim(Request::post('login')) . "']", null); - if (count($user) !== 0) { - if ($user['login'] == Request::post('login')) { - if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) { - if ($user['role'] == 'admin' || $user['role'] == 'editor') { - Session::set('admin', true); - Session::set('user_id', (int)$user['id']); - Session::set('user_login', (string)$user['login']); - Session::set('user_role', (string)$user['role']); - Request::redirect('index.php'); - } - } else { - $login_error = __('Wrong username or password', 'users'); +// Admin login +if (Request::post('login_submit')) { + + $user = $users->select("[login='" . trim(Request::post('login')) . "']", null); + if (count($user) !== 0) { + if ($user['login'] == Request::post('login')) { + if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) { + if ($user['role'] == 'admin' || $user['role'] == 'editor') { + Session::set('admin', true); + Session::set('user_id', (int) $user['id']); + Session::set('user_login', (string) $user['login']); + Session::set('user_role', (string) $user['role']); + Request::redirect('index.php'); } - } - } else { - $login_error = __('Wrong username or password', 'users'); + } else { + $login_error = __('Wrong username or password', 'users'); + } } - } - - - // Errors - $errors = array(); - - $site_url = Option::get('siteurl'); - $site_name = Option::get('sitename'); - - $user_login = trim(Request::post('login')); - - // Reset Password Form Submit - if (Request::post('reset_password_submit')) { - - if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users'); - if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users'); - if ($user_login != '' && ! $users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users'); - - if (count($errors) == 0) { - - // Get user - $user = $users->select("[login='" . $user_login . "']", null); - - // Generate new hash - $new_hash = Text::random('alnum', 12); - - // Update user hash - $users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash)); - - // Message - $message = View::factory('box/users/views/frontend/reset_password_email') - ->assign('site_url', $site_url) - ->assign('site_name', $site_name) - ->assign('user_id', $user['id']) - ->assign('user_login', $user['login']) - ->assign('new_hash', $new_hash) - ->render(); - - - // Send - @mail($user['email'], __('Your login details for :site_name', 'users', array(':site_name' => $site_name)), $message); - - // Set notification - Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name))); - Notification::set('reset_password', 'reset_password'); - - // Redirect to password-reset page - Request::redirect(Site::url().'admin'); - - } - - Notification::setNow('reset_password', 'reset_password'); - } - - // If admin user is login = true then set is_admin = true - if (Session::exists('admin') && Session::get('admin') == true) { - $is_admin = true; } else { - $is_admin = false; + $login_error = __('Wrong username or password', 'users'); + } +} + +// Errors +$errors = array(); + +$site_url = Option::get('siteurl'); +$site_name = Option::get('sitename'); + +$user_login = trim(Request::post('login')); + +// Reset Password Form Submit +if (Request::post('reset_password_submit')) { + + if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users'); + if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users'); + if ($user_login != '' && ! $users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users'); + + if (count($errors) == 0) { + + // Get user + $user = $users->select("[login='" . $user_login . "']", null); + + // Generate new hash + $new_hash = Text::random('alnum', 12); + + // Update user hash + $users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash)); + + // Message + $message = View::factory('box/users/views/frontend/reset_password_email') + ->assign('site_url', $site_url) + ->assign('site_name', $site_name) + ->assign('user_id', $user['id']) + ->assign('user_login', $user['login']) + ->assign('new_hash', $new_hash) + ->render(); + + // Send + @mail($user['email'], __('Your login details for :site_name', 'users', array(':site_name' => $site_name)), $message); + + // Set notification + Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name))); + Notification::set('reset_password', 'reset_password'); + + // Redirect to password-reset page + Request::redirect(Site::url().'admin'); + } - // Logout user from system - if (Request::get('logout') && Request::get('logout') == 'do') { - Session::destroy(); - } + Notification::setNow('reset_password', 'reset_password'); +} - // If is admin then load admin area - if ($is_admin) { +// If admin user is login = true then set is_admin = true +if (Session::exists('admin') && Session::get('admin') == true) { + $is_admin = true; +} else { + $is_admin = false; +} - // If id is empty then redirect to default plugin PAGES - if (Request::get('id')) { - $area = Request::get('id'); - } else { - Request::redirect('index.php?id=pages'); - } +// Logout user from system +if (Request::get('logout') && Request::get('logout') == 'do') { + Session::destroy(); +} - $plugins_registered = Plugin::$plugins; - foreach ($plugins_registered as $plugin) { - $plugins_registered_areas[] = $plugin['id']; - } - - // Show plugins admin area only for registered plugins - if (in_array($area, $plugins_registered_areas)) { - $plugin_admin_area = true; - } else { - $plugin_admin_area = false; - } - - // Backend pre render - Action::run('admin_pre_render'); - - // Display admin template - require('themes' . DS . Option::get('theme_admin_name') . DS . 'index.template.php'); - - // Backend post render - Action::run('admin_post_render'); +// If is admin then load admin area +if ($is_admin) { + // If id is empty then redirect to default plugin PAGES + if (Request::get('id')) { + $area = Request::get('id'); } else { - - // Display login template - require('themes' . DS . Option::get('theme_admin_name') . DS . 'login.template.php'); - + Request::redirect('index.php?id=pages'); } - - // Flush (send) the output buffer and turn off output buffering - ob_end_flush(); \ No newline at end of file + + $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(); diff --git a/admin/themes/default/index.template.php b/admin/themes/default/index.template.php index 9233f12..738cb7b 100644 --- a/admin/themes/default/index.template.php +++ b/admin/themes/default/index.template.php @@ -2,7 +2,7 @@ - Monstra :: <?php echo __('Administration', 'system'); ?> + Monstra :: <?php echo __('Administration', 'system'); ?> @@ -33,8 +33,8 @@
-
- +
+

@@ -59,19 +59,19 @@

    -
+

    -
+
- +
@@ -80,7 +80,7 @@ if (is_callable(ucfirst(Plugin::$plugins[$area]['id']).'Admin::main')) { call_user_func(ucfirst(Plugin::$plugins[$area]['id']).'Admin::main'); } else { - echo '
'.__('Plugin main admin function does not exist', 'system').'
'; + echo '
'.__('Plugin main admin function does not exist', 'system').'
'; } } else { echo '
'.__('Plugin does not exist', 'system').'
'; @@ -88,8 +88,8 @@ ?>
- -
+ +
@@ -110,4 +110,4 @@ - \ No newline at end of file + diff --git a/admin/themes/default/login.template.php b/admin/themes/default/login.template.php index 9e0da76..b34e634 100644 --- a/admin/themes/default/login.template.php +++ b/admin/themes/default/login.template.php @@ -22,36 +22,35 @@ - - + - +
- +

@@ -89,20 +88,20 @@
0) { - foreach($errors as $error) { + foreach ($errors as $error) { Alert::error($error); } } ?> -
-
- + + +
- - + - ', 'system');?> ', 'system');?>
@@ -110,8 +109,8 @@
- © 2012 Monstra + © 2012 Monstra
- \ No newline at end of file + diff --git a/boot/defines.php b/boot/defines.php index 498a4ee..d349a4b 100644 --- a/boot/defines.php +++ b/boot/defines.php @@ -1,117 +1,93 @@ button then try to install - if (Request::post('install_submit')) { - - if (Request::post('sitename') == '') $errors['sitename'] = __('Field "Site name" is empty', 'system'); - if (Request::post('siteurl') == '') $errors['siteurl'] = __('Field "Site url" is empty', 'system'); - if (Request::post('login') == '') $errors['login'] = __('Field "Username" is empty', 'system'); - if (Request::post('password') == '') $errors['password'] = __('Field "Password" is empty', 'system'); - if (Request::post('email') == '') $errors['email'] = __('Field "Email" is empty', 'system'); - if ( ! Valid::email(Request::post('email'))) $errors['email_valid'] = __('Email not valid', 'system'); - if (trim(Request::post('php') !== '')) $errors['php'] = true; - if (trim(Request::post('simplexml') !== '')) $errors['simplexml'] = true; - if (trim(Request::post('mod_rewrite') !== '')) $errors['mod_rewrite'] = true; - if (trim(Request::post('htaccess') !== '')) $errors['htaccess'] = true; - if (trim(Request::post('sitemap') !== '')) $errors['sitemap'] = true; - if (trim(Request::post('install') !== '')) $errors['install'] = true; - if (trim(Request::post('public') !== '')) $errors['public'] = true; - if (trim(Request::post('storage') !== '')) $errors['storage'] = true; - if (trim(Request::post('backups') !== '')) $errors['backups'] = true; - if (trim(Request::post('tmp') !== '')) $errors['tmp'] = true; - - - - - // If errors is 0 then install cms - if (count($errors) == 0) { - - // Update options - Option::update(array('maintenance_status' => 'off', - 'sitename' => Request::post('sitename'), - 'siteurl' => Request::post('siteurl'), - 'description' => __('Site description', 'system'), - 'keywords' => __('Site keywords', 'system'), - 'slogan' => __('Site slogan', 'system'), - 'defaultpage' => 'home', - 'timezone' => Request::post('timezone'), - 'theme_site_name' => 'default', - 'theme_admin_name' => 'default')); - - - // Get users table - $users = new Table('users'); - - // Insert new user with role = admin - $users->insert(array('login' => Security::safeName(Request::post('login')), - 'password' => Security::encryptPassword(Request::post('password')), - 'email' => Request::post('email'), - 'hash' => Text::random('alnum', 12), - 'date_registered' => time(), - 'role' => 'admin')); - - // Write .htaccess - $htaccess = file_get_contents('.htaccess'); - $save_htaccess_content = str_replace("/%siteurlhere%/", $rewrite_base, $htaccess); - - $handle = fopen ('.htaccess', "w"); - fwrite($handle, $save_htaccess_content); - fclose($handle); - - // Installation done :) - header("location: index.php?install=done"); - } - } -?> - - - - - Monstra :: Install - - - - - - - - - - - - - - -
- - - -
-
-
Monstra
-
-
-
- - - - - - - - - - - - - -
- - -
- - -
- - -
- - - - - -

- -
-
-
-

-
-
    -
  • '.__('PHP 5.2 or greater is required', 'system').'
  • '; - } else { - echo '
  • '.__('PHP Version', 'system').' '.PHP_VERSION.'
  • '; - } - - if (in_array('SimpleXML', $php_modules)) { - echo '
  • '.__('Module SimpleXML is installed', 'system').'
  • '; - } else { - echo '
  • '.__('SimpleXML module is required', 'system').'
  • '; - } - - if (in_array('dom', $php_modules)) { - echo '
  • '.__('Module DOM is installed', 'system').'
  • '; - } else { - echo '
  • '.__('Module DOM is required', 'system').'
  • '; - } - - if (function_exists('apache_get_modules')) { - if ( ! in_array('mod_rewrite',apache_get_modules())) { - echo '
  • '.__('Apache Mod Rewrite is required', 'system').'
  • '; - } else { - echo '
  • '.__('Module Mod Rewrite is installed', 'system').'
  • '; - } - } else { - echo '
  • '.__('Module Mod Rewrite is installed', 'system').'
  • '; - } - - foreach ($dir_array as $dir) { - if (is_writable($dir.'/')) { - echo '
  • '.__('Directory: :dir writable', 'system', array(':dir' => $dir)).'
  • '; - } else { - echo '
  • '.__('Directory: :dir not writable', 'system', array(':dir' => $dir)).'
  • '; - } - } - - if (is_writable(__FILE__)){ - echo '
  • '.__('Install script writable', 'system').'
  • '; - } else { - echo '
  • '.__('Install script not writable', 'system').'
  • '; - } - - if (is_writable('sitemap.xml')){ - echo '
  • '.__('Sitemap file writable', 'system').'
  • '; - } else { - echo '
  • '.__('Sitemap file not writable', 'system').'
  • '; - } - - if (is_writable('.htaccess')){ - echo '
  • '.__('Main .htaccess file writable', 'system').'
  • '; - } else { - echo '
  • '.__('Main .htaccess file not writable', 'system').'
  • '; - } - - if (isset($errors['sitename'])) echo '
  • '.$errors['sitename'].'
  • '; - if (isset($errors['siteurl'])) echo '
  • '.$errors['siteurl'].'
  • '; - if (isset($errors['login'])) echo '
  • '.$errors['login'].'
  • '; - if (isset($errors['password'])) echo '
  • '.$errors['password'].'
  • '; - if (isset($errors['email'])) echo '
  • '.$errors['email'].'
  • '; - if (isset($errors['email_valid'])) echo '
  • '.$errors['email_valid'].'
  • '; - ?> -
-
-
- - - \ No newline at end of file diff --git a/libraries/engine/Core.php b/libraries/engine/Core.php new file mode 100644 index 0000000..869d5cb --- /dev/null +++ b/libraries/engine/Core.php @@ -0,0 +1,489 @@ + 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + + // Cleanup cache + if (count($namespaces = Dir::scan(CACHE)) > 0) foreach ($namespaces as $namespace) Dir::delete(CACHE . DS . $namespace); + } + + // Load URI module + require_once(ROOT . '/libraries/engine/Uri.php'); + + // Load XMLDB API module + require_once(ROOT . '/libraries/engine/Xmldb.php'); + + // Load Options API module + require_once(ROOT . '/libraries/engine/Options.php'); + + // Init Options API module + Option::init(); + + // Set default timezone + @ini_set('date.timezone', Option::get('timezone')); + if (function_exists('date_default_timezone_set')) date_default_timezone_set(Option::get('timezone')); else putenv('TZ='.Option::get('timezone')); + + // Sanitize URL to prevent XSS - Cross-site scripting + Security::runSanitizeURL(); + + // Load Plugins API module + require_once(ROOT . '/libraries/engine/Plugins.php'); + + // Load Shortcodes API module + require_once(ROOT . '/libraries/engine/Shortcodes.php'); + + // Load default + Core::loadPluggable(); + + // Init I18n + I18n::init(Option::get('language')); + + // Init Plugins API + Plugin::init(); + + // Init Notification service + Notification::init(); + + // Load Site module + require_once(ROOT . '/libraries/engine/Site.php'); + + // Init site module + if( ! BACKEND) Site::init(); + + } + + /** + * Autoload helpers + * + * @param string $class_name Class name + */ + /*protected static function autoloadHelpers($class_name) { + if (file_exists($path = HELPERS . DS . strtolower($class_name) . '.php')) include $path; + }*/ + + /** + * Load Defines + */ + protected static function loadDefines() + { + $environments = array(1 => 'production', + 2 => 'staging', + 3 => 'testing', + 4 => 'development'); + + $root_defines = ROOT . DS . 'boot' . DS . 'defines.php'; + $environment_defines = ROOT . DS . 'boot' . DS . $environments[Core::$environment] . DS . 'defines.php'; + $monstra_defines = ROOT . DS . 'libraries/engine' . DS . 'boot' . DS . 'defines.php'; + + if (file_exists($root_defines)) { + include $root_defines; + } elseif (file_exists($environment_defines)) { + include $environment_defines; + } elseif (file_exists($monstra_defines)) { + include $monstra_defines; + } else { + throw new RuntimeException("The defines file does not exist."); + } + } + + /** + * Load Pluggable + */ + protected static function loadPluggable() + { + $environments = array(1 => 'production', + 2 => 'staging', + 3 => 'testing', + 4 => 'development'); + + $root_pluggable = ROOT . DS . 'boot'; + $environment_pluggable = ROOT . DS . 'boot' . DS . $environments[Core::$environment]; + $monstra_pluggable = ROOT . DS . 'libraries/engine' . DS . 'boot'; + + if (file_exists($root_pluggable . DS . 'filters.php')) { + include $root_pluggable . DS . 'filters.php'; + } elseif (file_exists($environment_pluggable . DS . 'filters.php')) { + include $environment_pluggable . DS . 'filters.php'; + } elseif (file_exists($monstra_pluggable . DS . 'filters.php')) { + include $monstra_pluggable . DS . 'filters.php'; + } else { + throw new RuntimeException("The pluggable file does not exist."); + } + + if (file_exists($root_pluggable . DS . 'actions.php')) { + include $root_pluggable . DS . 'actions.php'; + } elseif (file_exists($environment_pluggable . DS . 'actions.php')) { + include $environment_pluggable . DS . 'actions.php'; + } elseif (file_exists($monstra_pluggable . DS . 'actions.php')) { + include $monstra_pluggable . DS . 'actions.php'; + } else { + throw new RuntimeException("The pluggable file does not exist."); + } + + if (file_exists($root_pluggable . DS . 'shortcodes.php')) { + include $root_pluggable . DS . 'shortcodes.php'; + } elseif (file_exists($environment_pluggable . DS . 'shortcodes.php')) { + include $environment_pluggable . DS . 'shortcodes.php'; + } elseif (file_exists($monstra_pluggable . DS . 'shortcodes.php')) { + include $monstra_pluggable . DS . 'shortcodes.php'; + } else { + throw new RuntimeException("The pluggable file does not exist."); + } + + } + + /** + * Exception Handler + * + * @param object $exception An exception object + */ + public static function exceptionHandler($exception) + { + // Empty output buffers + while (ob_get_level() > 0) ob_end_clean(); + + // Send headers and output + @header('Content-Type: text/html; charset=UTF-8'); + @header('HTTP/1.1 500 Internal Server Error'); + + // Get highlighted code + $code = Core::highlightCode($exception->getFile(), $exception->getLine()); + + // Determine error type + if ($exception instanceof ErrorException) { + + $error_type = 'ErrorException: '; + + $codes = array ( + E_ERROR => 'Fatal Error', + E_PARSE => 'Parse Error', + E_COMPILE_ERROR => 'Compile Error', + E_COMPILE_WARNING => 'Compile Warning', + E_STRICT => 'Strict Mode Error', + E_NOTICE => 'Notice', + E_WARNING => 'Warning', + E_RECOVERABLE_ERROR => 'Recoverable Error', + /*E_DEPRECATED => 'Deprecated',*/ /* PHP 5.3 */ + E_USER_NOTICE => 'Notice', + E_USER_WARNING => 'Warning', + E_USER_ERROR => 'Error', + /*E_USER_DEPRECATED => 'Deprecated'*/ /* PHP 5.3 */ + ); + + $error_type .= in_array($exception->getCode(), array_keys($codes)) ? $codes[$exception->getCode()] : 'Unknown Error'; + } else { + $error_type = get_class($exception); + } + + // Show exception if core environment is DEVELOPMENT + if (Core::$environment == Core::DEVELOPMENT) { + + // Development + echo (" + + + + + Monstra + + + +
+

Monstra - ".$error_type."

+

".$exception->getMessage()."

+

Location

+

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

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

Oops!

+

An unexpected error has occurred.

+
+ + + "); + } + + // Writes message to log + @file_put_contents(LOGS . DS . gmdate('Y_m_d') . '.log', + gmdate('Y/m/d H:i:s') . ' --- ' . '['.$error_type.']' . ' --- ' . $exception->getMessage() . ' --- ' . 'Exception thrown on line '.$exception->getLine().' in '.$exception->getFile() . "\n", + FILE_APPEND); + + exit(1); + } + + /** + * Converts errors to ErrorExceptions. + * + * @param integer $code The error code + * @param string $message The error message + * @param string $file The filename where the error occurred + * @param integer $line The line number where the error occurred + * @return boolean + */ + public static function errorHandler($code, $message, $file, $line) + { + // If isset error_reporting and $code then throw new error exception + if ((error_reporting() & $code) !== 0) { + throw new ErrorException($message, $code, 0, $file, $line); + } + + // Don't execute PHP internal error handler + return true; + } + + + + /** + * Returns an array of lines from a file. + * + * @param string $file File in which you want to highlight a line + * @param integer $line Line number to highlight + * @param integer $padding Number of padding lines + * @return array + */ + protected static function highlightCode($file, $line, $padding = 5) + { + // Is file readable ? + if ( ! is_readable($file)) { + return false; + } + + // Init vars + $lines = array(); + $current_line = 0; + + // Open file + $handle = fopen($file, 'r'); + + // Read file + while ( ! feof($handle)) { + + $current_line++; + + $temp = fgets($handle); + + if ($current_line > $line + $padding) { + break; // Exit loop after we have found what we were looking for + } + + if ($current_line >= ($line - $padding) && $current_line <= ($line + $padding)) { + + $lines[] = array ( + 'number' => str_pad($current_line, 4, ' ', STR_PAD_LEFT), + 'highlighted' => ($current_line === $line), + 'code' => Core::highlightString($temp), + ); + } + } + + // Close + fclose($handle); + + // Return lines + return $lines; + } + + + /** + * Highlight string + * + * @param string $string String + * @return string + */ + protected static function highlightString($string) + { + return str_replace(array("\n", '', '', '<?php ', '#$@r4!/*'), + array('', '', '', '', '/*'), + highlight_string(' + * Option::add('pages_limit', 10); + * Option::add(array('pages_count' => 10, 'pages_default' => 'home')); + * + * + * @param mixed $option Name of option to add. + * @param mixed $value Option value. + * @return boolean + */ + public static function add($option, $value = null) + { + if (is_array($option)) { + foreach ($option as $k => $v) { + $_option = Option::$options->select('[name="'.$k.'"]', null); + if (count($_option) == 0) { + Option::$options->insert(array('name' => $k, 'value' => $v)); + } + } + } else { + $_option = Option::$options->select('[name="'.$option.'"]', null); + if (count($_option) == 0) { + return Option::$options->insert(array('name' => $option, 'value' => $value)); + } + } + } + + /** + * Update option value + * + * + * Option::update('pages_limit', 12); + * Option::update(array('pages_count' => 10, 'pages_default' => 'home')); + * + * + * @param mixed $option Name of option to update. + * @param mixed $value Option value. + * @return boolean + */ + public static function update($option, $value = null) + { + if (is_array($option)) { + foreach ($option as $k => $v) { + Option::$options->updateWhere('[name="'.$k.'"]', array('value' => $v)); + } + } else { + return Option::$options->updateWhere('[name="'.$option.'"]', array('value' => $value)); + } + } + + /** + * Get option value + * + * + * $pages_limit = Option::get('pages_limit'); + * if ($pages_limit == '10') { + * // do something... + * } + * + * + * @param string $option Name of option to get. + * @return string + */ + public static function get($option) + { + // Redefine vars + $option = (string) $option; + + // Select specific option + $option_name = Option::$options->select('[name="'.$option.'"]', null); + + // Return specific option value + return isset($option_name['value']) ? $option_name['value'] : ''; + } + + /** + * Delete option + * + * + * Option::delete('pages_limit'); + * + * + * @param string $option Name of option to delete. + * @return boolean + */ + public static function delete($option) + { + // Redefine vars + $option = (string) $option; + + // Delete specific option + return Option::$options->deleteWhere('[name="'.$option.'"]'); + } + + /** + * Check if option exist + * + * + * if (Option::exists('pages_limit')) { + * // do something... + * } + * + * + * @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; + } + +} diff --git a/libraries/engine/Plugins.php b/libraries/engine/Plugins.php new file mode 100644 index 0000000..d195655 --- /dev/null +++ b/libraries/engine/Plugins.php @@ -0,0 +1,1228 @@ +select(null, 'all', null, array('location', 'frontend', 'backend', 'status', 'priority'), 'priority', 'ASC'); + + // Now include plugins from $records plugins array + // If plugin is active then load it to the system. + foreach ($records as $record) { + if ($record['status'] == 'active') { + include_once ROOT . DS . $record['location']; + } + } + } + + /** + * Get plugin admin + * + * + * // Get admin for Blog plugin + * Plugin::admin('blog'); + * + * + * @param string $plug Plugin Name + * @param string $alt_folder Alternative plugin folder + */ + public static function admin($plug, $alt_folder = null) + { + // Redefine arguments + $plug = (string) $plug; + + // Plugin admin extension + $ext = '.admin.php'; + + // Plugin admin can be loaded only in backend + if (BACKEND) { + + // Plugin admin folder + if ( ! empty($alt_folder)) { + $folder = $alt_folder . DS . strtolower($plug); + } else { + $folder = strtolower($plug); + } + + // Path to plugin admin file + $path = PLUGINS . DS . $folder . DS . $plug . $ext; + + // Load plugin admin + if (File::exists($path)) { + include $path; + } + } + } + + /** + * Register new plugin in system + * + * + * // Register plugin + * Plugin::register( __FILE__, + * __('Blog'), + * __('Blog plugin'), + * '1.0.0', + * 'Awilum', + * 'http://example.org/', + * 'blog'); + * + * + * @param string $file Plugin file + * @param string $title Plugin title + * @param string $description Plugin description + * @param string $version Plugin version + * @param string $author Plugin author + * @param string $author_uri Plugin author uri + * @param string $component Plugin as component + * @param boolean $box Plugin as box + */ + public static function register($file, $title, $description = null, $version = null, $author = null, $author_uri = null, $component = null, $box = false) + { + // Redefine arguments + $file = (string) $file; + $title = (string) $title; + $description = ($description === null) ? null : (string) $description; + $version = ($version === null) ? null : (string) $version; + $author = ($author === null) ? null : (string) $author; + $author_uri = ($author_uri === null) ? null : (string) $author_uri; + $component = ($component === null) ? null : (string) $component; + $box = (bool) $box; + + // Get plugin id from name.plugin.php + $id = strtolower(basename($file, '.plugin.php')); + + // Set plugin privilege 'box' if $box is true + if ($box) $privilege = 'box'; else $privilege = ''; + + // Register plugin in global plugins array. + Plugin::$plugins[$id] = array( + 'id' => $id, + 'title' => $title, + 'privilege' => $privilege, + 'version' => $version, + 'description' => $description, + 'author' => $author, + 'author_uri' => $author_uri, + ); + + // Add plugin as a component + // Plugin - component will be available at the link sitename/component_name + // Example: + // www.example.org/guestbook + // www.example.org/news + if ( ! empty($component)) { + Plugin::$components[] = $component; + } + } + +} + +/** + * Frontend class + */ +class Frontend +{ + public static function main() { } + public static function title() { return ''; } + public static function description() { return ''; } + public static function keywords() { return ''; } + public static function template() { return 'index'; } + public static function content() { return ''; } + +} + +/** + * Backend class + */ +class Backend +{ + public static function main() { } + +} + +/** + * View class + */ +class View +{ + /** + * Path to view file. + * + * @var string + */ + protected $view_file; + + /** + * View variables. + * + * @var array + */ + protected $vars = array(); + + /** + * Global view variables. + * + * @var array + */ + protected static $global_vars = array(); + + /** + * The output. + * + * @var string + */ + protected $output; + + /** + * Create a new view object. + * + * + * // Create new view object + * $view = new View('blog/views/backend/index'); + * + * // Assign some new variables + * $view->assign('msg', 'Some message...'); + * + * // Get view + * $output = $view->render(); + * + * // Display view + * echo $output; + * + * + * @param string $view Name of the view file + * @param array $variables Array of view variables + */ + public function __construct($view, array $variables = array()) + { + // Set view file + // 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 + * + * + * // Create new view object, assign some variables + * // and displays the rendered view in the browser. + * View::factory('blog/views/backend/index') + * ->assign('msg', 'Some message...') + * ->display(); + * + * + * @param string $view Name of the view file + * @param array $variables Array of view variables + * @return View + */ + public static function factory($view, array $variables = array()) + { + return new View($view, $variables); + } + + /** + * Assign a view variable. + * + * + * $view->assign('msg', 'Some message...'); + * + * + * @param string $key Variable name + * @param mixed $value Variable value + * @param boolean $global Set variable available in all views + * @return View + */ + public function assign($key, $value, $global = false) + { + // Assign a new view variable (global or locale) + if ($global === false) { + $this->vars[$key] = $value; + } else { + View::$global_vars[$key] = $value; + } + + return $this; + } + + /** + * Include the view file and extracts the view variables before returning the generated output. + * + * + * // Get view + * $output = $view->render(); + * + * // Display output + * echo $output; + * + * + * @param string $filter Callback function used to filter output + * @return string + */ + public function render($filter = null) + { + // Is output empty ? + if (empty($this->output)) { + + // Extract variables as references + extract(array_merge($this->vars, View::$global_vars), EXTR_REFS); + + // Turn on output buffering + ob_start(); + + // Include view file + include($this->view_file); + + // Output... + $this->output = ob_get_clean(); + } + + // Filter output ? + if ($filter !== null) { + $this->output = call_user_func($filter, $this->output); + } + + // Return output + return $this->output; + } + + /** + * Displays the rendered view in the browser. + * + * + * $view->display(); + * + * + */ + public function display() + { + echo $this->render(); + } + + /** + * Magic setter method that assigns a view variable. + * + * @param string $key Variable name + * @param mixed $value Variable value + */ + public function __set($key, $value) + { + $this->vars[$key] = $value; + } + + /** + * Magic getter method that returns a view variable. + * + * @param string $key Variable name + * @return mixed + */ + public function __get($key) + { + if (isset($this->vars[$key])) { + return $this->vars[$key]; + } + } + + /** + * Magic isset method that checks if a view variable is set. + * + * @param string $key Variable name + * @return boolean + */ + public function __isset($key) + { + return isset($this->vars[$key]); + } + + /** + * Magic unset method that unsets a view variable. + * + * @param string $key Variable name + */ + public function __unset($key) + { + unset($this->vars[$key]); + } + + /** + * Method that magically converts the view object into a string. + * + * @return string + */ + public function __toString() + { + return $this->render(); + } +} + +/** + * I18n class + */ +class I18n +{ + /** + * Locales array + * + * @var array + */ + public static $locales = array( + 'ar' => 'العربية', + 'bg' => 'Български', + 'ca' => 'Català', + 'cs' => 'Česky', + 'da' => 'Dansk', + 'de' => 'Deutsch', + 'el' => 'Ελληνικά', + 'en' => 'English', + 'es' => 'Español', + 'fi' => 'Suomi', + 'fr' => 'Français', + 'gl' => 'Galego', + 'hu' => 'Magyar', + 'it' => 'Italiano', + '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', + 'tr' => 'Türkçe', + 'uk' => 'Українська', + 'zh' => '中文', + ); + + /** + * Dictionary + * + * @var array + */ + public static $dictionary = array(); + + /** + * An instance of the I18n class + * + * @var I18n + */ + protected static $instance = null; + + /** + * Initializing I18n + * + * @param string $dir Plugins directory + */ + public static function init($locale) + { + if ( ! isset(self::$instance)) self::$instance = new I18n($locale); + return self::$instance; + } + + /** + * Protected clone method to enforce singleton behavior. + * + * @access protected + */ + protected function __clone() + { + // Nothing here. + } + + /** + * Construct + */ + protected function __construct($locale) + { + // Redefine arguments + $locale = (string) $locale; + + // Get lang table for current locale + $lang_table = Cache::get('i18n', $locale); + + // If lang_table is empty then create new + if (! $lang_table) { + + // Get plugins Table + $plugins = new Table('plugins'); + + // Get all plugins + $records = $plugins->select(null, 'all', null, array('location', 'priority'), 'priority', 'ASC'); + + // Init var + $lang_table = array(); + + // Loop through each installed plugin + foreach ($records as $record) { + + if (is_dir(ROOT . DS . dirname($record['location']) . DS . 'languages')) { + + // Init var + $t = array(); + + // Check lang file + if (file_exists(ROOT . DS . dirname($record['location']) . DS . 'languages' . DS . $locale . '.lang.php')) { + + // Merge the language strings into the sub table + $t = array_merge($t, include ROOT . DS . dirname($record['location']) . DS . 'languages' . DS . $locale . '.lang.php'); + + } + + // Append the sub table, preventing less specific language files from overloading more specific files + $lang_table += $t; + } + } + + // Save lang table for current locale + Cache::put('i18n', $locale, $lang_table); + + // Update dictionary + I18n::$dictionary = $lang_table; + } + + // Update dictionary + I18n::$dictionary = $lang_table; + } + + /** + * Returns translation of a string. If no translation exists, the original + * string will be returned. No parameters are replaced. + * + * + * $hello = I18n::find('Hello friends, my name is :name', 'namespace'); + * + * + * @param string $string Text to translate + * @param string $namespace Namespace + * @return string + */ + public static function find($string, $namespace = null) + { + // Redefine arguments + $string = (string) $string; + + // Return string + if (isset(I18n::$dictionary[$namespace][$string])) return I18n::$dictionary[$namespace][$string]; else return $string; + } + +} + +/** + * Global Translation/internationalization function. + * Accepts an English string and returns its translation + * to the active system language. If the given string is not available in the + * current dictionary the original English string will be returned. + * + * + * // Display a translated message + * echo __('Hello, world', 'namespace'); + * + * // With parameter replacement + * echo __('Hello, :user', 'namespace', array(':user' => $username)); + * + * + * @global array $dictionary Dictionary + * @param string $string String to translate + * @param array $values Values to replace in the translated text + * @param string $namespace Namespace + * @return string + */ +function __($string, $namespace = null, array $values = null) +{ + // Redefine arguments + $string = (string) $string; + + // Find string in dictionary + $string = I18n::find($string, $namespace); + + // Return string + return empty($values) ? $string : strtr($string, $values); +} + +/** + * Action class + */ +class Action +{ + /** + * Actions + * + * @var array + */ + public static $actions = array(); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + /** + * Hooks a function on to a specific action. + * + * + * // Hooks a function "newLink" on to a "footer" action. + * Action::add('footer', 'newLink', 10); + * + * function newLink() { + * echo 'My link'; + * } + * + * + * @param string $action_name Action name + * @param string $added_function Added function + * @param integer $priority Priority. Default is 10 + * @param array $args Arguments + */ + public static function add($action_name, $added_function, $priority = 10, array $args = null) + { + // Hooks a function on to a specific action. + Action::$actions[] = array( + 'action_name' => (string) $action_name, + 'function' => (string) $added_function, + 'priority' => (int) $priority, + 'args' => $args + ); + } + + /** + * Run functions hooked on a specific action hook. + * + * + * // Run functions hooked on a "footer" action hook. + * Action::run('footer'); + * + * + * @param string $action_name Action name + * @param array $args Arguments + * @param boolean $return Return data or not. Default is false + * @return mixed + */ + public static function run($action_name, $args = array(), $return = false) + { + // Redefine arguments + $action_name = (string) $action_name; + $return = (bool) $return; + + // Run action + if (count(Action::$actions) > 0) { + + // Sort actions by priority + $actions = Arr::subvalSort(Action::$actions, 'priority'); + + // Loop through $actions array + foreach ($actions as $action) { + + // Execute specific action + if ($action['action_name'] == $action_name) { + + // isset arguments ? + if (isset($args)) { + + // Return or Render specific action results ? + if ($return) { + return call_user_func_array($action['function'], $args); + } else { + call_user_func_array($action['function'], $args); + } + + } else { + + if ($return) { + return call_user_func_array($action['function'], $action['args']); + } else { + call_user_func_array($action['function'], $action['args']); + } + + } + + } + + } + + } + + } + +} + +/** + * Filter class + */ +class Filter +{ + /** + * Filters + * + * @var array + */ + public static $filters = array(); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + /** + * Apply filters + * + * + * Filter::apply('content', $content); + * + * + * @param string $filter_name The name of the filter hook. + * @param mixed $value The value on which the filters hooked. + * @return mixed + */ + public static function apply($filter_name, $value) + { + // Redefine arguments + $filter_name = (string) $filter_name; + + $args = array_slice(func_get_args(), 2); + + if ( ! isset(Filter::$filters[$filter_name])) { + return $value; + } + + foreach (Filter::$filters[$filter_name] as $priority => $functions) { + if ( ! is_null($functions)) { + foreach ($functions as $function) { + $all_args = array_merge(array($value), $args); + $function_name = $function['function']; + $accepted_args = $function['accepted_args']; + if ($accepted_args == 1) { + $the_args = array($value); + } elseif ($accepted_args > 1) { + $the_args = array_slice($all_args, 0, $accepted_args); + } elseif ($accepted_args == 0) { + $the_args = null; + } else { + $the_args = $all_args; + } + $value = call_user_func_array($function_name, $the_args); + } + } + } + + return $value; + } + + /** + * Add filter + * + * + * Filter::add('content', 'replacer'); + * + * function replacer($content) { + * return preg_replace(array('/\[b\](.*?)\[\/b\]/ms'), array('\1'), $content); + * } + * + * + * @param string $filter_name The name of the filter to hook the $function_to_add to. + * @param string $function_to_add The name of the function to be called when the filter is applied. + * @param integer $priority Function to add priority - default is 10. + * @param integer $accepted_args The number of arguments the function accept default is 1. + * @return boolean + */ + public static function add($filter_name, $function_to_add, $priority = 10, $accepted_args = 1) + { + // Redefine arguments + $filter_name = (string) $filter_name; + $function_to_add = (string) $function_to_add; + $priority = (int) $priority; + $accepted_args = (int) $accepted_args; + + // Check that we don't already have the same filter at the same priority. Thanks to WP :) + if (isset(Filter::$filters[$filter_name]["$priority"])) { + foreach (Filter::$filters[$filter_name]["$priority"] as $filter) { + if ($filter['function'] == $function_to_add) { + return true; + } + } + } + + Filter::$filters[$filter_name]["$priority"][] = array('function' => $function_to_add, 'accepted_args' => $accepted_args); + + // Sort + ksort(Filter::$filters[$filter_name]["$priority"]); + + return true; + } + +} + + +/** + * Stylesheet class + */ +class Stylesheet +{ + /** + * Stylesheets + * + * @var array + */ + public static $stylesheets = array(); + + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + + /** + * Add stylesheet + * + * + * Stylesheet::add('path/to/my/stylesheet1.css'); + * Stylesheet::add('path/to/my/stylesheet2.css', 'frontend', 11); + * Stylesheet::add('path/to/my/stylesheet3.css', 'backend',12); + * + * + * @param string $file File path + * @param string $load Load stylesheet on frontend, backend or both + * @param integer $priority Priority. Default is 10 + */ + public static function add($file, $load = 'frontend', $priority = 10) + { + Stylesheet::$stylesheets[] = array( + 'file' => (string) $file, + 'load' => (string) $load, + 'priority' => (int) $priority, + ); + } + + + /** + * Minify, combine and load site stylesheet + */ + public static function load() + { + $backend_site_css_path = MINIFY . DS . 'backend_site.minify.css'; + $frontend_site_css_path = MINIFY . DS . 'frontend_site.minify.css'; + + // Load stylesheets + if (count(Stylesheet::$stylesheets) > 0) { + + $backend_buffer = ''; + $backend_regenerate = false; + + $frontend_buffer = ''; + $frontend_regenerate = false; + + + // Sort stylesheets by priority + $stylesheets = Arr::subvalSort(Stylesheet::$stylesheets, 'priority'); + + 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, Minify::css($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, Minify::css($frontend_buffer)); + $frontend_regenerate = false; + } + + } + + // Render + if (BACKEND) { + echo ''; + } else { + echo ''; + } + } + } + + + /** + * CSS Parser + */ + public static function parseVariables($frontend_buffer) + { + return str_replace(array('@site_url', + '@theme_site_url', + '@theme_admin_url'), + array(Option::get('siteurl'), + Option::get('siteurl').'public/themes/'.Option::get('theme_site_name'), + Option::get('siteurl').'admin/themes/'.Option::get('theme_admin_name')), + $frontend_buffer); + } + + +} + + +/** + * Javascript class + */ +class Javascript +{ + /** + * Javascripts + * + * @var array + */ + public static $javascripts = array(); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + + /** + * Add javascript + * + * + * Javascript::add('path/to/my/script1.js'); + * Javascript::add('path/to/my/script2.js', 'frontend', 11); + * Javascript::add('path/to/my/script3.js', 'backend', 12); + * + * + * @param string $file File path + * @param string $load Load script on frontend, backend or both + * @param inteeer $priority Priority default is 10 + */ + public static function add($file, $load = 'frontend', $priority = 10) + { + Javascript::$javascripts[] = array( + 'file' => (string) $file, + 'load' => (string) $load, + 'priority' => (int) $priority, + ); + } + + + /** + * Combine and load site javascript + */ + public static function load() + { + $backend_site_js_path = MINIFY . DS . 'backend_site.minify.js'; + $frontend_site_js_path = MINIFY . DS . 'frontend_site.minify.js'; + + // Load javascripts + if (count(Javascript::$javascripts) > 0) { + + $backend_buffer = ''; + $backend_regenerate = false; + + $frontend_buffer = ''; + $frontend_regenerate = false; + + + // Sort javascripts by priority + $javascripts = Arr::subvalSort(Javascript::$javascripts, 'priority'); + + + 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']); + } + } + 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']); + } + } + file_put_contents($frontend_site_js_path, $frontend_buffer); + $frontend_regenerate = false; + } + + } + + // Render + if (BACKEND) { + echo ''; + } else { + echo ''; + } + } + } + +} + + +/** + * Navigation class + */ +class Navigation +{ + /** + * Items + * + * @var array + */ + public static $items = array(); + + + /** + * Navigation types + */ + const LEFT = 1; + const TOP = 2; + + + /** + * Add new item + * + * + * // Add link for left navigation + * Navigation::add(__('Blog'), 'content', 'blog', 11); + * + * // Add link for top navigation + * Navigation::add(__('View site'), 'top', 'http://site.com/', 11, Navigation::TOP, true); + * + * + * @param string $name Name + * @param string $category Category + * @param stirng $link Link + * @param integer $priority Priority. Default is 10 + * @param integer $type Type. Default is LEFT + * @param bool $external External or not. Default is false + */ + public static function add($name, $category, $id, $priority = 10, $type = Navigation::LEFT, $external = false) + { + Navigation::$items[] = array( + 'name' => (string) $name, + 'category' => (string) $category, + 'id' => (string) $id, + 'priority' => (int) $priority, + 'type' => (int) $type, + 'external' => (bool) $external, + ); + } + + + /** + * Draw items + * + * + * Navigation::draw('content'); + * Navigation::draw('top', Navigation::TOP); + * + * + * @param string $category Category + * @param integer $type Type. Default is LEFT + */ + public static function draw($category, $type = Navigation::LEFT) + { + // Sort items by priority + $items = Arr::subvalSort(Navigation::$items, 'priority'); + + // Draw left navigation + if ($type == Navigation::LEFT) { + + // Loop trough the items + foreach ($items as $item) { + + // If current plugin id == selected item id then set class to current + if (Request::get('id') == $item['id'] && $item['external'] == false) $class = 'class = "current" '; else $class = ''; + + // If current category == item category and navigation type is left them draw this item + if ($item['category'] == $category && $item['type'] == Navigation::LEFT) { + + // Is external item id or not ? + if ($item['external'] == false) { + echo '
  • '.$item['name'].'
  • '; + } else { + echo '
  • '.$item['name'].'
  • '; + } + } + } + } elseif ($type == Navigation::TOP) { + // Draw top navigation + foreach ($items as $item) { + if ($item['category'] == $category && $item['type'] == Navigation::TOP) { + if ($item['external'] == false) { + echo ''.$item['name'].''.Html::nbsp(2); + } else { + echo ''.$item['name'].''.Html::nbsp(2); + } + } + } + } + } + +} diff --git a/libraries/engine/Shortcodes.php b/libraries/engine/Shortcodes.php new file mode 100644 index 0000000..f5580b1 --- /dev/null +++ b/libraries/engine/Shortcodes.php @@ -0,0 +1,180 @@ + + * function returnSiteUrl() { + * return Option::get('siteurl'); + * } + * + * // Add shortcode {siteurl} + * Shortcode::add('siteurl', 'returnSiteUrl'); + *
    + * + * @param string $shortcode Shortcode tag to be searched in content. + * @param string $callback_function The callback function to replace the shortcode with. + */ + public static function add($shortcode, $callback_function) + { + // Redefine vars + $shortcode = (string) $shortcode; + + // Add new shortcode + if (is_callable($callback_function)) Shortcode::$shortcode_tags[$shortcode] = $callback_function; + } + + /** + * Remove a specific registered shortcode. + * + * + * Shortcode::delete('shortcode_name'); + * + * + * @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. + * + * + * Shortcode::clear(); + * + * + */ + public static function clear() + { + Shortcode::$shortcode_tags = array(); + } + + /** + * Check if a shortcode has been registered. + * + * + * if (Shortcode::exists('shortcode_name')) { + * // do something... + * } + * + * + * @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. + * + * + * $content = Shortcode::parse($content); + * + * + * @param string $content Content + * @return string + */ + public static function parse($content) + { + if ( ! Shortcode::$shortcode_tags) return $content; + + $shortcodes = implode('|', array_map('preg_quote', array_keys(Shortcode::$shortcode_tags))); + $pattern = "/(.?)\{([$shortcodes]+)(.*?)(\/)?\}(?(4)|(?:(.+?)\{\/\s*\\2\s*\}))?(.?)/s"; + + return preg_replace_callback($pattern, 'Shortcode::_handle', $content); + } + + /** + * _handle() + */ + protected static function _handle($matches) + { + $prefix = $matches[1]; + $suffix = $matches[6]; + $shortcode = $matches[2]; + + // Allow for escaping shortcodes by enclosing them in {{shortcode}} + if ($prefix == '{' && $suffix == '}') { + return substr($matches[0], 1, -1); + } + + $attributes = array(); // Parse attributes into into this array. + + if (preg_match_all('/(\w+) *= *(?:([\'"])(.*?)\\2|([^ "\'>]+))/', $matches[3], $match, PREG_SET_ORDER)) { + foreach ($match as $attribute) { + if ( ! empty($attribute[4])) { + $attributes[strtolower($attribute[1])] = $attribute[4]; + } elseif ( ! empty($attribute[3])) { + $attributes[strtolower($attribute[1])] = $attribute[3]; + } + } + } + + // 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 : ''; + } + +} diff --git a/libraries/engine/Site.php b/libraries/engine/Site.php new file mode 100644 index 0000000..9a75078 --- /dev/null +++ b/libraries/engine/Site.php @@ -0,0 +1,227 @@ + + * echo Site::name(); + *
    + * + * @return string + */ + public static function name() + { + return Option::get('sitename'); + } + + /** + * Get site theme + * + * + * echo Site::theme(); + * + * + * @return string + */ + public static function theme() + { + return Option::get('theme_site_name'); + } + + /** + * Get Page title + * + * + * echo Site::title(); + * + * + * @return string + */ + public static function title() + { + return call_user_func(ucfirst(Uri::command()).'::title'); + } + + /** + * Get page description + * + * + * echo Site::description(); + * + * + * @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 + * + * + * echo Site::keywords(); + * + * + * @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 + * + * + * echo Site::slogan(); + * + * + * @return string + */ + public static function slogan() + { + return Option::get('slogan'); + } + + /** + * Get page content + * + * + * echo Site::content(); + * + * + * @return string + */ + public static function content() + { + return Filter::apply('content', call_user_func(ucfirst(Uri::command()).'::content')); + } + + /** + * Get compressed template + * + * + * echo Site::template(); + * + * + * @param string $theme Theme name + * @return mixed + */ + public static function template($theme = null) + { + // Get specific theme or current theme + $current_theme = ($theme == null) ? Option::get('theme_site_name') : $theme ; + + // Get template + $template = call_user_func(ucfirst(Uri::command()).'::template'); + + // Check whether is there such a template in the current theme + // else return default template: index + // also compress template file :) + if (File::exists(THEMES_SITE . DS . $current_theme . DS . $template . '.template.php')) { + if ( ! file_exists(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php') or + filemtime(THEMES_SITE . DS . $current_theme . DS . $template .'.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php')) { + $buffer = file_get_contents(THEMES_SITE. DS . $current_theme . DS . $template .'.template.php'); + $buffer = Minify::html($buffer); + file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php', $buffer); + } + + return 'minify.'.$template; + } else { + if ( ! File::exists(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php') or + filemtime(THEMES_SITE . DS . $current_theme . DS . 'index.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php')) { + $buffer = file_get_contents(THEMES_SITE . DS . $current_theme . DS . 'index.template.php'); + $buffer = Minify::html($buffer); + file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php', $buffer); + } + + return 'minify.index'; + } + } + + /** + * Get site url + * + * + * echo Site::url(); + * + * + * @return string + */ + public static function url() + { + return Option::get('siteurl'); + } + + /** + * Get copyright information + * + * + * echo Site::powered(); + * + * + * @return string + */ + public static function powered() + { + return __('Powered by', 'system').' Monstra ' . Core::VERSION; + } + +} diff --git a/libraries/engine/Uri.php b/libraries/engine/Uri.php new file mode 100644 index 0000000..30e78d6 --- /dev/null +++ b/libraries/engine/Uri.php @@ -0,0 +1,163 @@ + + * $segments = Uri::segments(); + *
    + * + * @return array + */ + public static function segments() + { + // Get request uri and current script path + $request_uri = explode('/', $_SERVER['REQUEST_URI']); + $script_name = explode('/', $_SERVER['SCRIPT_NAME']); + + // Delete script name + for ($i = 0; $i < sizeof($script_name); $i++) { + if ($request_uri[$i] == $script_name[$i]) { + unset($request_uri[$i]); + } + } + + // Get all the values of an array + $uri = array_values($request_uri); + + // Ability to pass parameters + foreach ($uri as $i => $u) { + if (isset($uri[$i])) { $pos = strrpos($uri[$i], "?"); if ($pos === false) { $uri[$i] = Security::sanitizeURL($uri[$i]); } else { $uri[$i] = Security::sanitizeURL(substr($uri[$i], 0, $pos)); } } + } + + // Return uri segments + return $uri; + } + + /** + * Get uri segment + * + * + * $segment = Uri::segment(1); + * + * + * @param integer $segment Segment + * @return mixed + */ + public static function segment($segment) + { + $segments = Uri::segments(); + + return isset($segments[$segment]) ? $segments[$segment] : null; + } + + /** + * Get command/component from registed components + * + * + * $command = Uri::command(); + * + * + * @return array + */ + public static function command() + { + // Get uri segments + $uri = Uri::segments(); + + if ( ! isset($uri[0])) { + $uri[0] = Uri::$default_component; + } else { + if ( ! in_array($uri[0], Plugin::$components) ) { + $uri[0] = Uri::$default_component; + } else { + $uri[0] = $uri[0]; + } + } + + return $uri[0]; + } + + /** + * Get uri parammeters + * + * + * $params = Uri::params(); + * + * + * @return array + */ + public static function params() + { + //Init data array + $data = array(); + + // Get URI + $uri = Uri::segments(); + + // http://site.com/ and http://site.com/index.php same main home pages + if ( ! isset($uri[0])) { + $uri[0] = ''; + } + + // param1/param2 + if ($uri[0] !== Uri::$default_component) { + if (isset($uri[1])) { + $data[0] = $uri[0]; + $data[1] = $uri[1]; + // Some more uri parts :) + // site.ru/part1/part2/part3/part4/part5/part6/ + if (isset($uri[2])) $data[2] = $uri[2]; + if (isset($uri[3])) $data[3] = $uri[3]; + if (isset($uri[4])) $data[4] = $uri[4]; + if (isset($uri[5])) $data[5] = $uri[5]; + } else { // default + $data[0] = $uri[0]; + } + } else { + // This is good for box plugin Pages + // parent/child + if (isset($uri[2])) { + $data[0] = $uri[1]; + $data[1] = $uri[2]; + } else { // default + $data[0] = $uri[1]; + } + } + + return $data; + } + +} diff --git a/libraries/engine/Xmldb.php b/libraries/engine/Xmldb.php new file mode 100644 index 0000000..964cfce --- /dev/null +++ b/libraries/engine/Xmldb.php @@ -0,0 +1,1036 @@ + + * $xml_safe = XML::safe($xml_unsafe); + *
    + * + * @param string $str String + * @param boolean $flag Flag + * @return string + */ + public static function safe($str, $flag = true) + { + // Redefine vars + $str = (string) $str; + $flag = (bool) $flag; + + // Remove invisible chars + $non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/'); + do { + $cleaned = $str; + $str = preg_replace($non_displayables, '', $str); + } while ($cleaned != $str); + + // htmlspecialchars + if ($flag) $str = htmlspecialchars($str, ENT_QUOTES, 'utf-8'); + + // Return safe string + return $str; + } + + /** + * Get XML file + * + * + * $xml_file = XML::loadFile('path/to/file.xml'); + * + * + * @param string $file File name + * @param boolean $force Method + * @return array + */ + public static function loadFile($file, $force = false) + { + // Redefine vars + $file = (string) $file; + $force = (bool) $force; + + // For CMS API XML file force method + if ($force) { + $xml = file_get_contents($file); + $data = simplexml_load_string($xml); + + return $data; + } else { + if (file_exists($file) && is_file($file)) { + $xml = file_get_contents($file); + $data = simplexml_load_string($xml); + + return $data; + } else { + return false; + } + } + } + +} + +/** + * DB Class + */ +class DB +{ + /** + * XMLDB directory + * + * @var string + */ + public static $db_dir = STORAGE; + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + /** + * Configure the settings of XMLDB + * + * @param mixed $setting Setting name + * @param mixed $value Setting value + */ + public static function configure($setting, $value) + { + if (property_exists("db", $setting)) DB::$$setting = $value; + } + + /** + * Create new database + * + * @param string $db_name Database name + * @param integer $mode Mode + * @return boolean + */ + public static function create($db_name, $chmod = 0775) + { + // Redefine vars + $db_name = (string) $db_name; + + // Create + if (is_dir(DB::$db_dir . '/' . $db_name)) return false; + return mkdir(DB::$db_dir . '/' . $db_name, $chmod); + } + + /** + * Drop database + * + * @param string $db_name Database name + * @return boolean + */ + public static function drop($db_name) + { + // Redefine vars + $db_name = (string) $db_name; + + // Drop + if (is_dir(DB::$db_dir . '/' . $db_name)){$ob=scandir(DB::$db_dir . '/' . $db_name); foreach ($ob as $o) {if ($o!='.'&&$o!='..') {if(filetype(DB::$db_dir . '/' . $db_name.'/'.$o)=='dir')DB::drop(DB::$db_dir . '/' . $db_name.'/'.$o); else unlink(DB::$db_dir . '/' . $db_name.'/'.$o);}}} + reset($ob); rmdir(DB::$db_dir . '/' . $db_name); + } + +} + +/** + * Table class + */ +class Table +{ + /** + * XMLDB Tables directory + * + * @var string + */ + public static $tables_dir = XMLDB; + + /** + * Table + * + * @var object + */ + private $table; + + /** + * Table name + * + * @var string + */ + private $name; + + /** + * Configure the settings of XMLDB Tables + * + * @param mixed $setting Setting name + * @param mixed $value Setting value + */ + public static function configure($setting, $value) + { + if (property_exists("table", $setting)) Table::$$setting = $value; + } + + /** + * Table factory. + * + * + * $users = Table::factory('table_name'); + * + * + * @param string $table_name Table name + * @return Table + */ + public static function factory($table_name) + { + return new Table($table_name); + } + + /** + * Table construct + * + * + * $users = new Table('table_name'); + * + * + * @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: + * + * + * + * 0 + * + * + * + * + * + * value + * value + * + * + * + * + * Table::create('table_name', array('field1', 'field2')); + * + * + * @param string $table_name Table name + * @param array $fields Fields + * @return boolean + */ + public static function create($table_name, $fields) + { + // Redefine vars + $table_name = (string) $table_name; + + if ( ! file_exists(Table::$tables_dir . '/' . $table_name . '.table.xml') && + is_dir(dirname(Table::$tables_dir)) && + is_writable(dirname(Table::$tables_dir)) && + isset($fields) && + is_array($fields)) { + + // Create table fields + $_fields = ''; + foreach ($fields as $field) $_fields .= "<$field/>"; + $_fields .= ''; + + // Create new table + return file_put_contents(Table::$tables_dir . '/' . $table_name . '.table.xml','0'.$_fields.'', LOCK_EX); + + } else { + + // Something wrong... return false + return false; + } + } + + /** + * Delete table + * + * + * Table::drop('table_name'); + * + * + * @param string $table_name Table name + * @return boolean + */ + public static function drop($table_name) + { + // Redefine vars + $table_name = (string) $table_name; + + // Drop + if ( ! is_dir(Table::$tables_dir . '/' . $table_name . '.table.xml')) { + return unlink(Table::$tables_dir . '/' . $table_name . '.table.xml'); + } + + return false; + } + + /** + * Get table + * + * + * $table = Table::get('table_name'); + * + * + * @param array $table_name Table name + * @return mixed + */ + public static function get($table_name) + { + // Redefine vars + $table_name = (string) $table_name; + + // Load table + if (file_exists(Table::$tables_dir . '/' . $table_name.'.table.xml') && is_file(Table::$tables_dir . '/' . $table_name.'.table.xml')) { + $data = array('xml_object' => XML::loadFile(Table::$tables_dir . '/' . $table_name.'.table.xml'), + 'xml_filename' => Table::$tables_dir . '/' . $table_name.'.table.xml'); + + return $data; + } else { + return false; + } + } + + /** + * Get information about table + * + * + * var_dump($users->info()); + * + * + * @return array + */ + public function info() + { + return array( + 'table_name' => basename($this->table['xml_filename'], '.table.xml'), + 'table_size' => filesize($this->table['xml_filename']), + 'table_last_change' => filemtime($this->table['xml_filename']), + 'table_last_access' => fileatime($this->table['xml_filename']), + 'table_fields' => $this->fields(), + 'records_count' => $this->count(), + 'records_last_id' => $this->lastId() + ); + } + + /** + * Get table fields + * + * + * var_dump($users->fields()); + * + * + * @return array + */ + public function fields() + { + // Select fields + $fields_obj = Table::_selectOne($this->table, "fields"); + + // Create fields array + foreach ($fields_obj as $key => $field) { + $fields[] = $key; + } + + // Return array of fields + return $fields; + } + + /** + * Add new field + * + * + * $users->addField('test'); + * + * + * @param string $name Field name + * @return boolean + */ + public function addField($name) + { + // Redefine vars + $name = (string) $name; + + // Get table + $table = $this->table; + + // Select all fields + $fields = Table::_selectOne($this->table, "fields"); + + // Select current field + $field = Table::_selectOne($this->table, "fields/{$name}"); + + // If field dosnt exists than create new field + if ($field == null) { + + // Create new field + $fields->addChild($name, ''); + + // Save table + return Table::_save($table); + + } else { + return false; + + } + + } + + /** + * Delete field + * + * + * $users->deleteField('test'); + * + * + * @param string $name Field name + * @return boolean + */ + public function deleteField($name) + { + // Redefine vars + $name = (string) $name; + + // Get table + $table = $this->table; + + // Select field + $field = Table::_selectOne($this->table, "fields/{$name}"); + + // If field exist than delete it + if ($field != null) { + + // Delete field + unset($field[0]); + + // Save table + return Table::_save($table); + + } else { + return false; + + } + } + + /** + * Update field + * + * + * $users->updateField('login', 'username'); + * + * + * @param string $old_name Old field name + * @param string $new_name New field name + * @return boolean + */ + public function updateField($old_name, $new_name) + { + if (file_exists(Table::$tables_dir . '/' . $this->name.'.table.xml') && is_file(Table::$tables_dir . '/' . $this->name.'.table.xml')) { + $table = strtr(file_get_contents(Table::$tables_dir . '/' . $this->name.'.table.xml'), array('<'.$old_name.'>' => '<'.$new_name.'>', + '' => '', + '<'.$old_name.'/>' => '<'.$new_name.'/>')); + if (file_put_contents(Table::$tables_dir . '/' . $this->name.'.table.xml', $table)) { + return true; + } else { + return false; + } + } + } + + /** + * Check if field exist + * + * + * if ($users->existsField('field_name')) { + * // do something... + * } + * + * + * @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 + * + * + * $users->insert(array('login'=>'admin', 'password'=>'pass')); + * + * + * @param array $fields Record fields to insert + * @return boolean + */ + public function insert(array $fields = null) + { + // Set save flag to true + $save = true; + + // Foreach fields check is current field alredy exists + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + if (Table::_selectOne($this->table, "fields/{$key}") == null) { + $save = false; + break; + } + } + } + + // Get table fields and create fields names array + $_fields = Table::_selectOne($this->table, "fields"); + foreach ($_fields as $key => $value) { + $field_names[(string) $key] = (string) $key; + } + + // Save record + if ($save) { + + // Find autoincrement option + $inc = Table::_selectOne($this->table, "options/autoincrement"); + + // Increment + $inc_upd = $inc + 1; + + // Add record + $node = $this->table['xml_object']->addChild(XML::safe($this->name)); + + // Update autoincrement + Table::_updateWhere($this->table, "options", array('autoincrement' => $inc_upd)); + + // Add common record fields: id and uid + $node->addChild('id', $inc_upd); + $node->addChild('uid', Table::_generateUID()); + + // If exists fields to insert then insert them + if (count($fields) !== 0) { + + $table_fields = array_diff_key($field_names, $fields); + + // Defined fields + foreach ($table_fields as $table_field) { + $node->addChild($table_field, ''); + } + + // User fields + foreach ($fields as $key => $value) { + $node->addChild($key, XML::safe($value)); + } + } + + // Save table + return Table::_save($this->table); + + } else { + return false; + + } + } + + /** + * Select record(s) in table + * + * + * $records = $users->select('[id=2]'); + * $records = $users->select(null, 'all'); + * $records = $users->select(null, 'all', null, array('login')); + * $records = $users->select(null, 2, 1); + * + * + * @param string $query XPath query + * @param integer $row_count Row count. To select all records write 'all' + * @param integer $offset Offset + * @param array $fields Fields + * @param string $order_by Order by + * @param string $order Order type + * @return array + */ + public function select($query = null, $row_count = 'all', $offset = null, array $fields = null, $order_by = 'id', $order = 'ASC') + { + // Redefine vars + $query = ($query === null) ? null : (string) $query; + $offset = ($offset === null) ? null : (int) $offset; + $order_by = (string) $order_by; + $order = (string) $order; + + // Execute query + if ($query !== null) { + $tmp = $this->table['xml_object']->xpath('//'.$this->name.$query); + } else { + $tmp = $this->table['xml_object']->xpath($this->name); + } + + // Init vars + $data = array(); + $records = array(); + $_records = array(); + + $one_record = false; + + // If row count is null then select only one record + // eg: $users->select('[login="admin"]', null); + if ($row_count == null) { + + if (isset($tmp[0])) { + $_records = $tmp[0]; + $one_record = true; + } + + } else { + + // If row count is 'all' then select all records + // eg: + // $users->select('[status="active"]', 'all'); + // or + // $users->select('[status="active"]'); + 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) $value; + } + } + + $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 + * + * + * $users->delete(2); + * + * + * @param integer $id Record ID + * @return boolean + */ + public function delete($id) + { + // Redefine vars + $id = (int) $id; + + // Find record to delete + $xml_arr = Table::_selectOne($this->table, "//".$this->name."[id='".$id."']"); + + // If its exists then delete it + if (count($xml_arr) !== 0) { + + // Delete + unset($xml_arr[0]); + + } + + // Save table + return Table::_save($this->table); + } + + /** + * Delete with xPath query record in xml file + * + * + * $users->deleteWhere('[id=2]'); + * + * + * @param string $query xPath query + * @return boolean + */ + public function deleteWhere($query) + { + // Redefine vars + $query = (string) $query; + + // Find record to delete + $xml_arr = Table::_selectOne($this->table, '//'.$this->name.$query); + + // If its exists then delete it + if (count($xml_arr) !== 0) { + + // Delete + unset($xml_arr[0]); + + } + + // Save table + return Table::_save($this->table); + } + + /** + * Update record with xPath query in XML file + * + * + * $users->updateWhere('[id=2]', array('login'=>'Admin', 'password'=>'new pass')); + * + * + * @param string $query XPath query + * @param array $fields Record fields to udpate + * @return boolean + */ + public function updateWhere($query, array $fields = null) + { + // Redefine vars + $query = (string) $query; + + // Set save flag to true + $save = true; + + // Foreach fields check is current field alredy exists + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + if (Table::_selectOne($this->table, "fields/{$key}") == null) { + $save = false; + break; + } + } + } + + // Get table fields and create fields names array + $_fields = Table::_selectOne($this->table, "fields"); + foreach ($_fields as $key => $value) { + $field_names[(string) $key] = (string) $key; + } + + // Save record + if ($save) { + + // Find record + $xml_arr = Table::_selectOne($this->table, '//'.$this->name.$query); + + // If its exists then delete it + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + // Else: Strict Mode Error + // Creating default object from empty value + @$xml_arr->$key = XML::safe($value, false); + } + } + + // Save table + return Table::_save($this->table); + + } else { + return false; + + } + } + + /** + * Update current record in table + * + * + * $users->update(1, array('login'=>'Admin','password'=>'new pass')); + * + * + * @param integer $id Record ID + * @param array $fields Record fields to udpate + * @return boolean + */ + public function update($id, array $fields = null) + { + // Redefine vars + $id = (int) $id; + + // Set save flag to true + $save = true; + + // Foreach fields check is current field alredy exists + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + if (Table::_selectOne($this->table, "fields/{$key}") == null) { + $save = false; + break; + } + } + } + + // Get table fields and create fields names array + $_fields = Table::_selectOne($this->table, "fields"); + foreach ($_fields as $key => $value) { + $field_names[(string) $key] = (string) $key; + } + + // Save record + if ($save) { + + // Find record to delete + $xml_arr = Table::_selectOne($this->table, "//".$this->name."[id='".(int) $id."']"); + + // If its exists then update it + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + + // Delete current + unset($xml_arr->$key); + + // And add new one + $xml_arr->addChild($key, XML::safe($value, false)); + + } + } + + // Save table + return Table::_save($this->table); + + } else { + return false; + + } + } + + /** + * Get last record id + * + * + * echo $users->lastId(); + * + * + * @return integer + */ + public function lastId() + { + $data = $this->table['xml_object']->xpath("//root/node()[last()]"); + + return (int) $data[0]->id; + } + + /** + * Get count of records + * + * + * echo $users->count(); + * + * + * @return integer + */ + public function count() + { + return count($this->table['xml_object'])-2; + } + + /** + * Subval sort + * + * @param array $a Array + * @param string $subkey Key + * @param string $order Order type DESC or ASC + * @return array + */ + protected static function subvalSort($a, $subkey, $order = null) + { + if (count($a) != 0 || (!empty($a))) { + foreach ($a as $k=>$v) $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]); + if ($order==null || $order== 'ASC') asort($b); else if ($order == 'DESC') arsort($b); + foreach ($b as $key=>$val) $c[] = $a[$key]; + + return $c; + } + } + + /** + * _selectOne + */ + protected static function _selectOne($table, $query) + { + $tmp = $table['xml_object']->xpath($query); + + return isset($tmp[0])? $tmp[0]: null; + } + + /** + * _updateWhere + */ + protected static function _updateWhere($table, $query, $fields = array()) + { + // Find record to delete + $xml_arr = Table::_selectOne($table, $query); + + // If its exists then delete it + if (count($fields) !== 0) { + foreach ($fields as $key => $value) { + $xml_arr->$key = XML::safe($value, false); + } + } + + // Save table + Table::_save($table); + } + + /** + * _generateUID + */ + protected static function _generateUID() + { + return substr(md5(uniqid(rand(), true)), 0, 10); + } + + /** + * Format XML and save + * + * @param array $table Array of database name and XML object + */ + protected static function _save($table) + { + $dom = new DOMDocument('1.0'); + $dom->preserveWhiteSpace = false; + + // Save new xml data to xml file only if loadXML successful. + // Preventing the destruction of the database by unsafe data. + // note: If loadXML !successful then _save() add&save empty record. + // This record cant be removed by delete[Where]() Problem solved by hand removing... + // Possible solution: modify delete[Where]() or prevent add&saving of such records. + // the result now: database cant be destroyed :) + if ($dom->loadXML($table['xml_object']->asXML())) { + $dom->save($table['xml_filename']); + + return true; + } else { + return false; + // report about errors... + } + } + +} diff --git a/monstra/bootstrap.php b/libraries/engine/_init.php similarity index 89% rename from monstra/bootstrap.php rename to libraries/engine/_init.php index 7ddf9d6..a6555db 100644 --- a/monstra/bootstrap.php +++ b/libraries/engine/_init.php @@ -1,11 +1,10 @@ '; } diff --git a/libraries/engine/boot/defines.php b/libraries/engine/boot/defines.php new file mode 100644 index 0000000..d349a4b --- /dev/null +++ b/libraries/engine/boot/defines.php @@ -0,0 +1,93 @@ + + * if (Agent::isMobile()) { + * // Do something... + * } + *
    + * + * @return boolean + */ + public static function isMobile() + { + return Agent::find(Agent::$mobiles); + } + + /** + * Returns true if the user agent that made the request is identified as a robot/crawler. + * + * + * if (Agent::isRobot()) { + * // Do something... + * } + * + * + * @return boolean + */ + public static function isRobot() + { + return Agent::find(Agent::$robots); + } + + /** + * Returns TRUE if the string you're looking for exists in the user agent string and FALSE if not. + * + * + * if (Agent::is('iphone')) { + * // Do something... + * } + * + * if (Agent::is(array('iphone', 'ipod'))) { + * // Do something... + * } + * + * + * @param mixed $device String or array of strings you're looking for + * @return boolean + */ + public static function is($device) + { + return Agent::find((array) $device); + } + +} diff --git a/libraries/monstra/Alert.php b/libraries/monstra/Alert.php new file mode 100644 index 0000000..c65a49a --- /dev/null +++ b/libraries/monstra/Alert.php @@ -0,0 +1,88 @@ + + * Alert::success('Message here...'); + *
    + * + * @param string $message Message + * @param integer $time Time + */ + public static function success($message, $time = 3000) + { + // Redefine vars + $message = (string) $message; + $time = (int) $time; + + echo '
    '.$message.'
    + '; + } + + /** + * Show warning message + * + * + * Alert::warning('Message here...'); + * + * + * @param string $message Message + * @param integer $time Time + */ + public static function warning($message, $time = 3000) + { + // Redefine vars + $message = (string) $message; + $time = (int) $time; + + echo '
    '.$message.'
    + '; + } + + /** + * Show error message + * + * + * Alert::error('Message here...'); + * + * + * @param string $message Message + * @param integer $time Time + */ + public static function error($message, $time = 3000) + { + // Redefine vars + $message = (string) $message; + $time = (int) $time; + + echo '
    '.$message.'
    + '; + } + +} diff --git a/libraries/monstra/Arr.php b/libraries/monstra/Arr.php new file mode 100644 index 0000000..791f1c6 --- /dev/null +++ b/libraries/monstra/Arr.php @@ -0,0 +1,185 @@ + + * $new_array = Arr::subvalSort($old_array, 'sort'); + *
    + * + * @param array $a Array + * @param string $subkey Key + * @param string $order Order type DESC or ASC + * @return array + */ + public static function subvalSort($a, $subkey, $order = null) + { + if (count($a) != 0 || (!empty($a))) { + foreach ($a as $k => $v) $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]); + if ($order == null || $order == 'ASC') asort($b); else if ($order == 'DESC') arsort($b); + foreach ($b as $key => $val) $c[] = $a[$key]; + + return $c; + } + } + + /** + * Returns value from array using "dot notation". + * If the key does not exist in the array, the default value will be returned instead. + * + * + * $login = Arr::get($_POST, 'login'); + * + * $array = array('foo' => 'bar'); + * $foo = Arr::get($array, 'foo'); + * + * $array = array('test' => array('foo' => 'bar')); + * $foo = Arr::get($array, 'test.foo'); + * + * + * @param array $array Array to extract from + * @param string $path Array path + * @param mixed $default Default value + * @return mixed + */ + public static function get($array, $path, $default = null) + { + // Get segments from path + $segments = explode('.', $path); + + // Loop through segments + foreach ($segments as $segment) { + + // Check + if ( ! is_array($array) || !isset($array[$segment])) { + return $default; + } + + // Write + $array = $array[$segment]; + } + + // Return + return $array; + } + + /** + * Deletes an array value using "dot notation". + * + * + * Arr::delete($array, 'foo.bar'); + * + * + * @access public + * @param array $array Array you want to modify + * @param string $path Array path + * @return boolean + */ + public static function delete(&$array, $path) + { + // Get segments from path + $segments = explode('.', $path); + + // Loop through segments + while (count($segments) > 1) { + + $segment = array_shift($segments); + + if ( ! isset($array[$segment]) || !is_array($array[$segment])) { + return false; + } + + $array =& $array[$segment]; + } + + unset($array[array_shift($segments)]); + + return true; + } + + /** + * Checks if the given dot-notated key exists in the array. + * + * + * if (Arr::keyExists($array, 'foo.bar')) { + * // Do something... + * } + * + * + * @param array $array The search array + * @param mixed $path Array path + * @return boolean + */ + public static function keyExists($array, $path) + { + foreach (explode('.', $path) as $segment) { + + if ( ! is_array($array) or ! array_key_exists($segment, $array)) { + return false; + } + + $array = $array[$segment]; + } + + return true; + } + + /** + * Returns a random value from an array. + * + * + * Arr::random(array('php', 'js', 'css', 'html')); + * + * + * @access public + * @param array $array Array path + * @return mixed + */ + public static function random($array) + { + return $array[array_rand($array)]; + } + + /** + * Returns TRUE if the array is associative and FALSE if not. + * + * + * if (Arr::isAssoc($array)) { + * // Do something... + * } + * + * + * @param array $array Array to check + * @return boolean + */ + public static function isAssoc($array) + { + return (bool) count(array_filter(array_keys($array), 'is_string')); + } + +} diff --git a/libraries/monstra/Cache.php b/libraries/monstra/Cache.php new file mode 100644 index 0000000..3aac59c --- /dev/null +++ b/libraries/monstra/Cache.php @@ -0,0 +1,210 @@ + + * Cache::configure('cache_dir', 'path/to/cache/dir'); + *
    + * + * @param mixed $setting Setting name + * @param mixed $value Setting value + */ + public static function configure($setting, $value) + { + if (property_exists("cache", $setting)) Cache::$$setting = $value; + } + + /** + * Get data from cache + * + * + * $profile = Cache::get('profiles', 'profile'); + * + * + * @param string $namespace Namespace + * @param string $key Cache key + * @return boolean + */ + public static function get($namespace, $key) + { + // Redefine vars + $namespace = (string) $namespace; + + // Get cache file id + $cache_file_id = Cache::getCacheFileID($namespace, $key); + + // Is cache file exists ? + if (file_exists($cache_file_id)) { + + // If cache file has not expired then fetch it + if ((time() - filemtime($cache_file_id)) < Cache::$cache_time) { + + $handle = fopen($cache_file_id, 'r'); + + $cache = ''; + + while ( ! feof($handle)) { + $cache .= fgets($handle); + } + + fclose($handle); + + return unserialize($cache); + + } else { + unlink($cache_file_id); + + return false; + } + } else { + return false; + } + } + + /** + * Create new cache file $key in namescapce $namespace with the given data $data + * + * + * $profile = array('login' => 'Awilum', + * 'email' => 'awilum@msn.com'); + * Cache::put('profiles', 'profile', $profile); + * + * + * @param string $namespace Namespace + * @param string $key Cache key + * @param mixed $data The variable to store + * @return boolean + */ + public static function put($namespace, $key, $data) + { + // Redefine vars + $namespace = (string) $namespace; + + // Is CACHE directory writable ? + if (file_exists(CACHE) === false || is_readable(CACHE) === false || is_writable(CACHE) === false) { + throw new RuntimeException(vsprintf("%s(): Cache directory ('%s') is not writable.", array(__METHOD__, CACHE))); + } + + // Create namespace + if ( ! file_exists(Cache::getNamespaceID($namespace))) { + mkdir(Cache::getNamespaceID($namespace), 0775, true); + } + + // Write cache to specific namespace + return file_put_contents(Cache::getCacheFileID($namespace, $key), serialize($data), LOCK_EX); + } + + /** + * Deletes a cache in specific namespace + * + * + * Cache::delete('profiles', 'profile'); + * + * + * @param string $namespace Namespace + * @param string $key Cache key + * @return boolean + */ + public static function delete($namespace, $key) + { + // Redefine vars + $namespace = (string) $namespace; + + if (file_exists(Cache::getCacheFileID($namespace, $key))) unlink(Cache::getCacheFileID($namespace, $key)); else return false; + } + + /** + * Clean specific cache namespace. + * + * + * Cache::clean('profiles'); + * + * + * @param string $namespace Namespace + * @return null + */ + public static function clean($namespace) + { + // Redefine vars + $namespace = (string) $namespace; + + array_map("unlink", glob(Cache::$cache_dir . DS . md5($namespace) . DS . "*." . Cache::$cache_file_ext)); + } + + /** + * Get cache file ID + * + * @param string $namespace Namespace + * @param string $key Cache key + * @return string + */ + protected static function getCacheFileID($namespace, $key) + { + // Redefine vars + $namespace = (string) $namespace; + + return Cache::$cache_dir . DS . md5($namespace) . DS . md5($key) . '.' . Cache::$cache_file_ext; + } + + /** + * Get namespace ID + * + * @param string $namespace Namespace + * @return string + */ + protected static function getNamespaceID($namespace) + { + // Redefine vars + $namespace = (string) $namespace; + + return Cache::$cache_dir . DS . md5($namespace); + } + +} diff --git a/libraries/monstra/Cookie.php b/libraries/monstra/Cookie.php new file mode 100644 index 0000000..ede37a1 --- /dev/null +++ b/libraries/monstra/Cookie.php @@ -0,0 +1,106 @@ + + * Cookie::set('limit', 10); + *
    + * + * @param string $key A name for the cookie. + * @param mixed $value The value to be stored. Keep in mind that they will be serialized. + * @param integer $expire The number of seconds that this cookie will be available. + * @param string $path The path on the server in which the cookie will be availabe. Use / for the entire domain, /foo if you just want it to be available in /foo. + * @param string $domain The domain that the cookie is available on. Use .example.com to make it available on all subdomains of example.com. + * @param boolean $secure Should the cookie be transmitted over a HTTPS-connection? If true, make sure you use a secure connection, otherwise the cookie won't be set. + * @param boolean $httpOnly Should the cookie only be available through HTTP-protocol? If true, the cookie can't be accessed by Javascript, ... + * @return boolean + */ + public static function set($key, $value, $expire = 86400, $domain = '', $path = '/', $secure = false, $httpOnly = false) + { + // Redefine vars + $key = (string) $key; + $value = serialize($value); + $expire = time() + (int) $expire; + $path = (string) $path; + $domain = (string) $domain; + $secure = (bool) $secure; + $httpOnly = (bool) $httpOnly; + + // Set cookie + return setcookie($key, $value, $expire, $path, $domain, $secure, $httpOnly); + } + + /** + * Get a cookie + * + * + * $limit = Cookie::get('limit'); + * + * + * @param string $key The name of the cookie that should be retrieved. + * @return mixed + */ + public static function get($key) + { + // Redefine key + $key = (string) $key; + + // Cookie doesn't exist + if( ! isset($_COOKIE[$key])) return false; + + // Fetch base value + $value = (get_magic_quotes_gpc()) ? stripslashes($_COOKIE[$key]) : $_COOKIE[$key]; + + // Unserialize + $actual_value = @unserialize($value); + + // If unserialize failed + if($actual_value === false && serialize(false) != $value) return false; + + // Everything is fine + return $actual_value; + + } + + + /** + * Delete a cookie + * + * + * Cookie::delete('limit'); + * + * + * @param string $name The name of the cookie that should be deleted. + */ + public static function delete($key) + { + unset($_COOKIE[$key]); + } + +} diff --git a/libraries/monstra/Curl.php b/libraries/monstra/Curl.php new file mode 100644 index 0000000..1d2ecbd --- /dev/null +++ b/libraries/monstra/Curl.php @@ -0,0 +1,142 @@ + 'Mozilla/5.0 (compatible; Monstra CMS; +http://monstra.org)', + CURLOPT_RETURNTRANSFER => true + ); + + /** + * Information about the last transfer. + * + * @var array + */ + protected static $info; + + /** + * Performs a curl GET request. + * + * + * $res = Curl::get('http://site.com/'); + * + * + * @param string $url The URL to fetch + * @param array $options An array specifying which options to set and their values + * @return string + */ + public static function get($url, array $options = null) + { + // Redefine vars + $url = (string) $url; + + // Check if curl is available + if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__))); + + // Initialize a cURL session + $handle = curl_init($url); + + // Merge options + $options = (array) $options + Curl::$default_options; + + // Set multiple options for a cURL transfer + curl_setopt_array($handle, $options); + + // Perform a cURL session + $response = curl_exec($handle); + + // Set information regarding a specific transfer + Curl::$info = curl_getinfo($handle); + + // Close a cURL session + curl_close($handle); + + // Return response + return $response; + } + + /** + * Performs a curl POST request. + * + * + * $res = Curl::post('http://site.com/login'); + * + * + * @param string $url The URL to fetch + * @param array $data An array with the field name as key and field data as value + * @param boolean $multipart True to send data as multipart/form-data and false to send as application/x-www-form-urlencoded + * @param array $options An array specifying which options to set and their values + * @return string + */ + public static function post($url, array $data = null, $multipart = false, array $options = null) + { + // Redefine vars + $url = (string) $url; + + // Check if curl is available + if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__))); + + // Initialize a cURL session + $handle = curl_init($url); + + // Merge options + $options = (array) $options + Curl::$default_options; + + // Add options + $options[CURLOPT_POST] = true; + $options[CURLOPT_POSTFIELDS] = ($multipart === true) ? (array) $data : http_build_query((array) $data); + + // Set multiple options for a cURL transfer + curl_setopt_array($handle, $options); + + // Perform a cURL session + $response = curl_exec($handle); + + // Set information regarding a specific transfer + Curl::$info = curl_getinfo($handle); + + // Close a cURL session + curl_close($handle); + + // Return response + return $response; + } + + /** + * Gets information about the last transfer. + * + * + * $res = Curl::getInfo(); + * + * + * @param string $value Array key of the array returned by curl_getinfo() + * @return mixed + */ + public static function getInfo($value = null) + { + if (empty(Curl::$info)) { + return false; + } + + return ($value === null) ? Curl::$info : Curl::$info[$value]; + } + +} diff --git a/libraries/monstra/Date.php b/libraries/monstra/Date.php new file mode 100644 index 0000000..ad4486e --- /dev/null +++ b/libraries/monstra/Date.php @@ -0,0 +1,420 @@ + + * echo Date::format($date, 'j.n.Y'); + *
    + * + * @param integer $date Unix timestamp + * @param string $format Date format + * @return integer + */ + public static function format($date, $format = '') + { + // Redefine vars + $format = (string) $format; + $date = (int) $date; + + if ($format != '') { return date($format, $date); } else { return date(MONSTRA_DATE_FORMAT, $date); } + } + + /** + * Get number of seconds in a minute, incrementing by a step. + * + * + * $seconds = Date::seconds(); + * + * + * @param integer $step Amount to increment each step by, 1 to 30 + * @param integer $start Start value + * @param integer $end End value + * @return array + */ + public static function seconds($step = 1, $start = 0, $end = 60) + { + // Redefine vars + $step = (int) $step; + $start = (int) $start; + $end = (int) $end; + + return Date::_range($step, $start, $end); + } + + /** + * Get number of minutes in a hour, incrementing by a step. + * + * + * $minutes = Date::minutes(); + * + * + * @param integer $step Amount to increment each step by, 1 to 30 + * @param integer $start Start value + * @param integer $end End value + * @return array + */ + public static function minutes($step = 5, $start = 0, $end = 60) + { + // Redefine vars + $step = (int) $step; + $start = (int) $start; + $end = (int) $end; + + return Date::_range($step, $start, $end); + } + + /** + * Get number of hours, incrementing by a step. + * + * + * $hours = Date::hours(); + * + * + * @param integer $step Amount to increment each step by, 1 to 30 + * @param integer $long Start value + * @param integer $start End value + * @return array + */ + public static function hours($step = 1, $long = false, $start = null) + { + // Redefine vars + $step = (int) $step; + $long = (bool) $long; + + if ($start === null) $start = ($long === FALSE) ? 1 : 0; + $end = ($long === true) ? 23 : 12; + + return Date::_range($step, $start, $end, true); + } + + /** + * Get number of months. + * + * + * $months = Date::months(); + * + * + * @return array + */ + public static function months() + { + return Date::_range(1, 1, 12, true); + } + + /** + * Get number of days. + * + * + * $months = Date::days(); + * + * + * @return array + */ + public static function days() + { + return Date::_range(1, 1, Date::daysInMonth((int) date('M')), true); + } + + /** + * Returns the number of days in the requested month + * + * + * $days = Date::daysInMonth(1); + * + * + * @param integer $month Month as a number (1-12) + * @param integer $year The year + * @return integer + */ + public static function daysInMonth($month, $year = null) + { + // Redefine vars + $month = (int) $month; + $year = ! empty($year) ? (int) $year : (int) date('Y'); + + if ($month < 1 or $month > 12) { + return false; + } elseif ($month == 2) { + if ($year % 400 == 0 or ($year % 4 == 0 and $year % 100 != 0)) { + return 29; + } + } + + $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); + + return $days_in_month[$month-1]; + } + + /** + * Get number of years. + * + * + * $years = Date::years(); + * + * + * @param integer $long Start value + * @param integer $start End value + * @return array + */ + public static function years($start = 1980, $end = 2024) + { + // Redefine vars + $start = (int) $start; + $end = (int) $end; + + return Date::_range(1, $start, $end, true); + } + + /** + * Get current season name + * + * + * echo Date::season(); + * + * + * @return string + */ + public static function season() + { + $seasons = array("Winter", "Spring", "Summer", "Autumn"); + + return $seasons[(int) ((date("n") %12)/3)]; + } + + /** + * Get today date + * + * + * echo Date::today(); + * + * + * @param string $format Date format + * @return string + */ + public static function today($format = '') + { + // Redefine vars + $format = (string) $format; + + if ($format != '') { return date($format); } else { return date(MONSTRA_DATE_FORMAT); } + } + + /** + * Get yesterday date + * + * + * echo Date::yesterday(); + * + * + * @param string $format Date format + * @return string + */ + public static function yesterday($format = '') + { + // Redefine vars + $format = (string) $format; + + if ($format != '') { return date($format, strtotime("-1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); } + } + + /** + * Get tomorrow date + * + * + * echo Date::tomorrow(); + * + * + * @param string $format Date format + * @return string + */ + public static function tomorrow($format = '') + { + // Redefine vars + $format = (string) $format; + + if ($format != '') { return date($format, strtotime("+1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); } + } + + /** + * Converts a UNIX timestamp to DOS format. + * + * + * $dos = Date::unix2dos($unix); + * + * + * @param integer $timestamp UNIX timestamp + * @return integer + */ + public static function unix2dos($timestamp = 0) + { + $timestamp = ($_timestamp == 0) ? getdate() : getdate($_timestamp); + + if ($timestamp['year'] < 1980) return (1 << 21 | 1 << 16); + + $timestamp['year'] -= 1980; + + return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 | + $timestamp['mday'] << 16 | $timestamp['hours'] << 11 | + $timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1); + } + + /** + * Converts a DOS timestamp to UNIX format. + * + * + * $unix = Date::dos2unix($dos); + * + * + * @param integer $timestamp DOS timestamp + * @return integer + */ + public static function dos2unix($timestamp) + { + $sec = 2 * ($timestamp & 0x1f); + $min = ($timestamp >> 5) & 0x3f; + $hrs = ($timestamp >> 11) & 0x1f; + $day = ($timestamp >> 16) & 0x1f; + $mon = (($timestamp >> 21) & 0x0f); + $year = (($timestamp >> 25) & 0x7f) + 1980; + + return mktime($hrs, $min, $sec, $mon, $day, $year); + } + + /** + * Get Time zones + * + * @return array + */ + public static function timezones() + { + return array('Kwajalein'=>'(GMT-12:00) International Date Line West', + 'Pacific/Samoa'=>'(GMT-11:00) Midway Island, Samoa', + 'Pacific/Honolulu'=>'(GMT-10:00) Hawaii', + 'America/Anchorage'=>'(GMT-09:00) Alaska', + 'America/Los_Angeles'=>'(GMT-08:00) Pacific Time (US & Canada)', + 'America/Tijuana'=>'(GMT-08:00) Tijuana, Baja California', + 'America/Denver'=>'(GMT-07:00) Mountain Time (US & Canada)', + 'America/Chihuahua'=>'(GMT-07:00) Chihuahua, La Paz, Mazatlan', + 'America/Phoenix'=>'(GMT-07:00) Arizona', + 'America/Regina'=>'(GMT-06:00) Saskatchewan', + 'America/Tegucigalpa'=>'(GMT-06:00) Central America', + 'America/Chicago'=>'(GMT-06:00) Central Time (US & Canada)', + 'America/Mexico_City'=>'(GMT-06:00) Guadalajara, Mexico City, Monterrey', + 'America/New_York'=>'(GMT-05:00) Eastern Time (US & Canada)', + 'America/Bogota'=>'(GMT-05:00) Bogota, Lima, Quito, Rio Branco', + 'America/Indiana/Indianapolis'=>'(GMT-05:00) Indiana (East)', + 'America/Caracas'=>'(GMT-04:30) Caracas', + 'America/Halifax'=>'(GMT-04:00) Atlantic Time (Canada)', + 'America/Manaus'=>'(GMT-04:00) Manaus', + 'America/Santiago'=>'(GMT-04:00) Santiago', + 'America/La_Paz'=>'(GMT-04:00) La Paz', + 'America/St_Johns'=>'(GMT-03:30) Newfoundland', + 'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Buenos Aires', + 'America/Sao_Paulo'=>'(GMT-03:00) Brasilia', + 'America/Godthab'=>'(GMT-03:00) Greenland', + 'America/Montevideo'=>'(GMT-03:00) Montevideo', + 'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Georgetown', + 'Atlantic/South_Georgia'=>'(GMT-02:00) Mid-Atlantic', + 'Atlantic/Azores'=>'(GMT-01:00) Azores', + 'Atlantic/Cape_Verde'=>'(GMT-01:00) Cape Verde Is.', + 'Europe/London'=>'(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London', + 'Atlantic/Reykjavik'=>'(GMT) Monrovia, Reykjavik', + 'Africa/Casablanca'=>'(GMT) Casablanca', + 'Europe/Belgrade'=>'(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague', + 'Europe/Sarajevo'=>'(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb', + 'Europe/Brussels'=>'(GMT+01:00) Brussels, Copenhagen, Madrid, Paris', + 'Africa/Algiers'=>'(GMT+01:00) West Central Africa', + 'Europe/Amsterdam'=>'(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna', + 'Africa/Cairo'=>'(GMT+02:00) Cairo', + 'Europe/Helsinki'=>'(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius', + 'Europe/Athens'=>'(GMT+02:00) Athens, Bucharest, Istanbul', + 'Asia/Jerusalem'=>'(GMT+02:00) Jerusalem', + 'Asia/Amman'=>'(GMT+02:00) Amman', + 'Asia/Beirut'=>'(GMT+02:00) Beirut', + 'Africa/Windhoek'=>'(GMT+02:00) Windhoek', + 'Africa/Harare'=>'(GMT+02:00) Harare, Pretoria', + 'Asia/Kuwait'=>'(GMT+03:00) Kuwait, Riyadh', + 'Asia/Baghdad'=>'(GMT+03:00) Baghdad', + 'Europe/Minsk'=>'(GMT+03:00) Minsk', + 'Africa/Nairobi'=>'(GMT+03:00) Nairobi', + 'Asia/Tbilisi'=>'(GMT+03:00) Tbilisi', + 'Asia/Tehran'=>'(GMT+03:30) Tehran', + 'Asia/Muscat'=>'(GMT+04:00) Abu Dhabi, Muscat', + 'Asia/Baku'=>'(GMT+04:00) Baku', + 'Europe/Moscow'=>'(GMT+04:00) Moscow, St. Petersburg, Volgograd', + 'Asia/Yerevan'=>'(GMT+04:00) Yerevan', + 'Asia/Karachi'=>'(GMT+05:00) Islamabad, Karachi', + 'Asia/Tashkent'=>'(GMT+05:00) Tashkent', + 'Asia/Kolkata'=>'(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi', + 'Asia/Colombo'=>'(GMT+05:30) Sri Jayawardenepura', + 'Asia/Katmandu'=>'(GMT+05:45) Kathmandu', + 'Asia/Dhaka'=>'(GMT+06:00) Astana, Dhaka', + 'Asia/Yekaterinburg'=>'(GMT+06:00) Ekaterinburg', + 'Asia/Rangoon'=>'(GMT+06:30) Yangon (Rangoon)', + 'Asia/Novosibirsk'=>'(GMT+07:00) Almaty, Novosibirsk', + 'Asia/Bangkok'=>'(GMT+07:00) Bangkok, Hanoi, Jakarta', + 'Asia/Beijing'=>'(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi', + 'Asia/Ulaanbaatar'=>'(GMT+08:00) Irkutsk, Ulaan Bataar', + 'Asia/Krasnoyarsk'=>'(GMT+08:00) Krasnoyarsk', + 'Asia/Kuala_Lumpur'=>'(GMT+08:00) Kuala Lumpur, Singapore', + 'Asia/Taipei'=>'(GMT+08:00) Taipei', + 'Australia/Perth'=>'(GMT+08:00) Perth', + 'Asia/Seoul'=>'(GMT+09:00) Seoul', + 'Asia/Tokyo'=>'(GMT+09:00) Osaka, Sapporo, Tokyo', + 'Australia/Darwin'=>'(GMT+09:30) Darwin', + 'Australia/Adelaide'=>'(GMT+09:30) Adelaide', + 'Australia/Sydney'=>'(GMT+10:00) Canberra, Melbourne, Sydney', + 'Australia/Brisbane'=>'(GMT+10:00) Brisbane', + 'Australia/Hobart'=>'(GMT+10:00) Hobart', + 'Asia/Yakutsk'=>'(GMT+10:00) Yakutsk', + 'Pacific/Guam'=>'(GMT+10:00) Guam, Port Moresby', + 'Asia/Vladivostok'=>'(GMT+11:00) Vladivostok', + 'Pacific/Fiji'=>'(GMT+12:00) Fiji, Kamchatka, Marshall Is.', + 'Asia/Magadan'=>'(GMT+12:00) Magadan, Solomon Is., New Caledonia', + 'Pacific/Auckland'=>'(GMT+12:00) Auckland, Wellington', + 'Pacific/Tongatapu'=>'(GMT+13:00) Nukualofa' + ); + } + + /** + * _range() + */ + protected static function _range($step, $start, $end, $flag = false) + { + $result = array(); + if ($flag) { + for ($i = $start; $i <= $end; $i += $step) $result[$i] = (string) $i; + } else { + for ($i = $start; $i < $end; $i += $step) $result[$i] = sprintf('%02d', $i); + } + + return $result; + } + +} diff --git a/libraries/monstra/Debug.php b/libraries/monstra/Debug.php new file mode 100644 index 0000000..3125031 --- /dev/null +++ b/libraries/monstra/Debug.php @@ -0,0 +1,116 @@ + + * Debug::elapsedTimeSetPoint('point_name'); + * + * + * @param string $point_name Point name + */ + public static function elapsedTimeSetPoint($point_name) + { + Debug::$time[$point_name] = microtime(true); + } + + /** + * Get elapsed time for current point + * + * + * echo Debug::elapsedTime('point_name'); + * + * + * @param string $point_name Point name + * @return string + */ + public static function elapsedTime($point_name) + { + if (isset(Debug::$time[$point_name])) return sprintf("%01.4f", microtime(true) - Debug::$time[$point_name]); + } + + /** + * Save current memory for current point + * + * + * Debug::memoryUsageSetPoint('point_name'); + * + * + * @param string $point_name Point name + */ + public static function memoryUsageSetPoint($point_name) + { + Debug::$memory[$point_name] = memory_get_usage(); + } + + /** + * Get memory usage for current point + * + * + * echo Debug::memoryUsage('point_name'); + * + * + * @param string $point_name Point name + * @return string + */ + public static function memoryUsage($point_name) + { + if (isset(Debug::$memory[$point_name])) return Number::byteFormat(memory_get_usage() - Debug::$memory[$point_name]); + } + + /** + * Print the variable $data and exit if exit = true + * + * + * Debug::dump($data); + * + * + * @param mixed $data Data + * @param boolean $exit Exit + */ + public static function dump($data, $exit = false) + { + echo "
    dump \n---------------------- \n\n" . print_r($data, true) . "\n----------------------
    "; + if ($exit) exit; + } + +} diff --git a/libraries/monstra/Dir.php b/libraries/monstra/Dir.php new file mode 100644 index 0000000..e5c3713 --- /dev/null +++ b/libraries/monstra/Dir.php @@ -0,0 +1,207 @@ + + * Dir::create('folder1'); + * + * + * @param string $dir Name of directory to create + * @param integer $chmod Chmod + * @return boolean + */ + public static function create($dir, $chmod = 0775) + { + // Redefine vars + $dir = (string) $dir; + + // Create new dir if $dir !exists + return ( ! Dir::exists($dir)) ? @mkdir($dir, $chmod, true) : true; + } + + /** + * Checks if this directory exists. + * + * + * if (Dir::exists('folder1')) { + * // Do something... + * } + * + * + * @param string $dir Full path of the directory to check. + * @return boolean + */ + public static function exists($dir) + { + // Redefine vars + $dir = (string) $dir; + + // Directory exists + if (file_exists($dir) && is_dir($dir)) return true; + + // Doesn't exist + return false; + } + + + /** + * Check dir permission + * + * + * echo Dir::checkPerm('folder1'); + * + * + * @param string $dir Directory to check + * @return string + */ + public static function checkPerm($dir) + { + // Redefine vars + $dir = (string) $dir; + + // Clear stat cache + clearstatcache(); + + // Return perm + return substr(sprintf('%o', fileperms($dir)), -4); + } + + + /** + * Delete directory + * + * + * Dir::delete('folder1'); + * + * + * @param string $dir Name of directory to delete + */ + public static function delete($dir) + { + // Redefine vars + $dir = (string) $dir; + + // Delete dir + if (is_dir($dir)){$ob=scandir($dir);foreach ($ob as $o) {if ($o!='.'&&$o!='..') {if(filetype($dir.'/'.$o)=='dir')Dir::delete($dir.'/'.$o); else unlink($dir.'/'.$o);}}} + reset($ob); rmdir($dir); + } + + + /** + * Get list of directories + * + * + * $dirs = Dir::scan('folders'); + * + * + * @param string $dir Directory + */ + public static function scan($dir) + { + // Redefine vars + $dir = (string) $dir; + + // Scan dir + if (is_dir($dir)&&$dh=opendir($dir)){$f=array();while ($fn=readdir($dh)) {if($fn!='.'&&$fn!='..'&&is_dir($dir.DS.$fn))$f[]=$fn;}return$f;} + } + + + /** + * Check if a directory is writable. + * + * + * if (Dir::writable('folder1')) { + * // Do something... + * } + * + * + * @param string $path The path to check. + * @return booleans + */ + public static function writable($path) + { + // Redefine vars + $path = (string) $path; + + // Create temporary file + $file = tempnam($path, 'writable'); + + // File has been created + if ($file !== false) { + + // Remove temporary file + File::delete($file); + + // Writable + return true; + } + + // Else not writable + return false; + } + + + /** + * Get directory size. + * + * + * echo Dir::size('folder1'); + * + * + * @param string $path The path to directory. + * @return integer + */ + public static function size($path) + { + // Redefine vars + $path = (string) $path; + + $total_size = 0; + $files = scandir($path); + $clean_path = rtrim($path, '/') . '/'; + + foreach ($files as $t) { + if ($t <> "." && $t <> "..") { + $current_file = $clean_path . $t; + if (is_dir($current_file)) { + $total_size += Dir::size($current_file); + } else { + $total_size += filesize($current_file); + } + } + } + + // Return total size + return $total_size; + } + +} diff --git a/libraries/monstra/File.php b/libraries/monstra/File.php new file mode 100644 index 0000000..7746649 --- /dev/null +++ b/libraries/monstra/File.php @@ -0,0 +1,575 @@ + 'audio/aac', + 'atom' => 'application/atom+xml', + 'avi' => 'video/avi', + 'bmp' => 'image/x-ms-bmp', + 'c' => 'text/x-c', + 'class' => 'application/octet-stream', + 'css' => 'text/css', + 'csv' => 'text/csv', + 'deb' => 'application/x-deb', + 'dll' => 'application/x-msdownload', + 'dmg' => 'application/x-apple-diskimage', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'exe' => 'application/octet-stream', + 'flv' => 'video/x-flv', + 'gif' => 'image/gif', + 'gz' => 'application/x-gzip', + 'h' => 'text/x-c', + 'htm' => 'text/html', + 'html' => 'text/html', + 'ini' => 'text/plain', + 'jar' => 'application/java-archive', + 'java' => 'text/x-java', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mka' => 'audio/x-matroska', + 'mkv' => 'video/x-matroska', + 'mp3' => 'audio/mpeg', + 'mp4' => 'application/mp4', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'ogg' => 'audio/ogg', + 'pdf' => 'application/pdf', + 'php' => 'text/x-php', + 'png' => 'image/png', + 'psd' => 'image/vnd.adobe.photoshop', + 'py' => 'application/x-python', + 'ra' => 'audio/vnd.rn-realaudio', + 'ram' => 'audio/vnd.rn-realaudio', + 'rar' => 'application/x-rar-compressed', + 'rss' => 'application/rss+xml', + 'safariextz' => 'application/x-safari-extension', + 'sh' => 'text/x-shellscript', + 'shtml' => 'text/html', + 'swf' => 'application/x-shockwave-flash', + 'tar' => 'application/x-tar', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'torrent' => 'application/x-bittorrent', + 'txt' => 'text/plain', + 'wav' => 'audio/wav', + 'webp' => 'image/webp', + 'wma' => 'audio/x-ms-wma', + 'xls' => 'application/vnd.ms-excel', + 'xml' => 'text/xml', + 'zip' => 'application/zip', + ); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + /** + * Returns true if the File exists. + * + * + * if (File::exists('filename.txt')) { + * // Do something... + * } + * + * + * @param string $filename The file name + * @return boolean + */ + public static function exists($filename) + { + // Redefine vars + $filename = (string) $filename; + + // Return + return (file_exists($filename) && is_file($filename)); + } + + /** + * Delete file + * + * + * File::delete('filename.txt'); + * + * + * @param mixed $filename The file name or array of files + * @return boolean + */ + public static function delete($filename) + { + // Is array + if (is_array($filename)) { + + // Delete each file in $filename array + foreach ($filename as $file) { + @unlink((string) $file); + } + + } else { + // Is string + return @unlink((string) $filename); + } + + } + + /** + * Rename file + * + * + * File::rename('filename1.txt', 'filename2.txt'); + * + * + * @param string $from Original file location + * @param string $to Desitination location of the file + * @return boolean + */ + public static function rename($from, $to) + { + // Redefine vars + $from = (string) $from; + $to = (string) $to; + + // If file exists $to than rename it + if ( ! File::exists($to)) return rename($from, $to); + + // Else return false + return false; + } + + /** + * Copy file + * + * + * File::copy('folder1/filename.txt', 'folder2/filename.txt'); + * + * + * @param string $from Original file location + * @param string $to Desitination location of the file + * @return boolean + */ + public static function copy($from, $to) + { + // Redefine vars + $from = (string) $from; + $to = (string) $to; + + // If file !exists $from and exists $to then return false + if ( ! File::exists($from) || File::exists($to)) return false; + + // Else copy file + return copy($from, $to); + } + + /** + * Get the File extension. + * + * + * echo File::ext('filename.txt'); + * + * + * @param string $filename The file name + * @return string + */ + public static function ext($filename) + { + // Redefine vars + $filename = (string) $filename; + + // Return file extension + return substr(strrchr($filename, '.'), 1); + } + + /** + * Get the File name + * + * + * echo File::name('filename.txt'); + * + * + * @param string $filename The file name + * @return string + */ + public static function name($filename) + { + // Redefine vars + $filename = (string) $filename; + + // Return filename + return basename($filename, '.'.File::ext($filename)); + } + + /** + * Get list of files in directory recursive + * + * + * $files = File::scan('folder'); + * $files = File::scan('folder', 'txt'); + * $files = File::scan('folder', array('txt', 'log')); + * + * + * @param string $folder Folder + * @param mixed $type Files types + * @return array + */ + public static function scan($folder, $type = null) + { + $data = array(); + if (is_dir($folder)) { + $iterator = new RecursiveDirectoryIterator($folder); + foreach (new RecursiveIteratorIterator($iterator) as $file) { + if ($type !== null) { + if (is_array($type)) { + $file_ext = substr(strrchr($file->getFilename(), '.'), 1); + if (in_array($file_ext, $type)) { + if (strpos($file->getFilename(), $file_ext, 1)) { + $data[] = $file->getFilename(); + } + } + } else { + if (strpos($file->getFilename(), $type, 1)) { + $data[] = $file->getFilename(); + } + } + } else { + if ($file->getFilename() !== '.' && $file->getFilename() !== '..') $data[] = $file->getFilename(); + } + } + + return $data; + } else { + return false; + } + } + + /** + * Fetch the content from a file or URL. + * + * + * echo File::getContent('filename.txt'); + * + * + * @param string $filename The file name + * @return boolean + */ + public static function getContent($filename) + { + // Redefine vars + $filename = (string) $filename; + + // If file exists load it + if (File::exists($filename)) { + return file_get_contents($filename); + } + } + + /** + * Writes a string to a file. + * + * @param string $filename The path of the file. + * @param string $content The content that should be written. + * @param boolean $createFile Should the file be created if it doesn't exists? + * @param boolean $append Should the content be appended if the file already exists? + * @param integer $chmod Mode that should be applied on the file. + * @return boolean + */ + public static function setContent($filename, $content, $create_file = true, $append = false, $chmod = 0666) + { + // Redefine vars + $filename = (string) $filename; + $content = (string) $content; + $create_file = (bool) $create_file; + $append = (bool) $append; + + // File may not be created, but it doesn't exist either + if ( ! $create_file && File::exists($filename)) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' doesn't exist", array(__METHOD__))); + + // Create directory recursively if needed + Dir::create(dirname($filename)); + + // Create file & open for writing + $handler = ($append) ? @fopen($filename, 'a') : @fopen($filename, 'w'); + + // Something went wrong + if ($handler === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__))); + + // Store error reporting level + $level = error_reporting(); + + // Disable errors + error_reporting(0); + + // Write to file + $write = fwrite($handler, $content); + + // Validate write + if($write === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__))); + + // Close the file + fclose($handler); + + // Chmod file + chmod($filename, $chmod); + + // Restore error reporting level + error_reporting($level); + + // Return + return true; + } + + /** + * Get time(in Unix timestamp) the file was last changed + * + * + * echo File::lastChange('filename.txt'); + * + * + * @param string $filename The file name + * @return boolean + */ + public static function lastChange($filename) + { + // Redefine vars + $filename = (string) $filename; + + // If file exists return filemtime + if (File::exists($filename)) { + return filemtime($filename); + } + + // Return + return false; + + } + + /** + * Get last access time + * + * + * echo File::lastAccess('filename.txt'); + * + * + * @param string $filename The file name + * @return boolean + */ + public static function lastAccess($filename) + { + // Redefine vars + $filename = (string) $filename; + + // If file exists return fileatime + if (File::exists($filename)) { + return fileatime($filename); + } + + // Return + return false; + } + + /** + * Returns the mime type of a file. Returns false if the mime type is not found. + * + * + * echo File::mime('filename.txt'); + * + * + * @param string $file Full path to the file + * @param boolean $guess Set to false to disable mime type guessing + * @return string + */ + public static function mime($file, $guess = true) + { + // Redefine vars + $file = (string) $file; + $guess = (bool) $guess; + + // Get mime using the file information functions + if (function_exists('finfo_open')) { + + $info = finfo_open(FILEINFO_MIME_TYPE); + + $mime = finfo_file($info, $file); + + finfo_close($info); + + return $mime; + + } else { + + // Just guess mime by using the file extension + if ($guess === true) { + + $mime_types = File::$mime_types; + + $extension = pathinfo($file, PATHINFO_EXTENSION); + + return isset($mime_types[$extension]) ? $mime_types[$extension] : false; + } else { + return false; + } + } + } + + /** + * Forces a file to be downloaded. + * + * + * File::download('filename.txt'); + * + * + * @param string $file Full path to file + * @param string $content_type Content type of the file + * @param string $filename Filename of the download + * @param integer $kbps Max download speed in KiB/s + */ + public static function download($file, $content_type = null, $filename = null, $kbps = 0) + { + // Redefine vars + $file = (string) $file; + $content_type = ($content_type === null) ? null : (string) $content_type; + $filename = ($filename === null) ? null : (string) $filename; + $kbps = (int) $kbps; + + // Check that the file exists and that its readable + if (file_exists($file) === false || is_readable($file) === false) { + throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__))); + } + + // Empty output buffers + while (ob_get_level() > 0) ob_end_clean(); + + // Send headers + if ($content_type === null) $content_type = File::mime($file); + + if ($filename === null) $filename = basename($file); + + header('Content-type: ' . $content_type); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Content-Length: ' . filesize($file)); + + // Read file and write it to the output + @set_time_limit(0); + + if ($kbps === 0) { + + readfile($file); + + } else { + + $handle = fopen($file, 'r'); + + while ( ! feof($handle) && !connection_aborted()) { + + $s = microtime(true); + + echo fread($handle, round($kbps * 1024)); + + if (($wait = 1e6 - (microtime(true) - $s)) > 0) usleep($wait); + + } + + fclose($handle); + } + + exit(); + } + + /** + * Display a file in the browser. + * + * + * File::display('filename.txt'); + * + * + * @param string $file Full path to file + * @param string $content_type Content type of the file + * @param string $filename Filename of the download + */ + public static function display($file, $content_type = null, $filename = null) + { + // Redefine vars + $file = (string) $file; + $content_type = ($content_type === null) ? null : (string) $content_type; + $filename = ($filename === null) ? null : (string) $filename; + + // Check that the file exists and that its readable + if (file_exists($file) === false || is_readable($file) === false) { + throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__))); + } + + // Empty output buffers + while (ob_get_level() > 0) ob_end_clean(); + + // Send headers + if ($content_type === null) $content_type = File::mime($file); + + if($filename === null) $filename = basename($file); + + header('Content-type: ' . $content_type); + header('Content-Disposition: inline; filename="' . $filename . '"'); + header('Content-Length: ' . filesize($file)); + + // Read file and write to output + readfile($file); + + exit(); + } + + /** + * Tests whether a file is writable for anyone. + * + * + * if (File::writable('filename.txt')) { + * // do something... + * } + * + * + * @param string $file File to check + * @return boolean + */ + public static function writable($file) + { + // Redefine vars + $file = (string) $file; + + // Is file exists ? + if ( ! file_exists($file)) throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__))); + + // Gets file permissions + $perms = fileperms($file); + + // Is writable ? + if (is_writable($file) || ($perms & 0x0080) || ($perms & 0x0010) || ($perms & 0x0002)) return true; + } + +} diff --git a/libraries/monstra/Form.php b/libraries/monstra/Form.php new file mode 100644 index 0000000..30acd95 --- /dev/null +++ b/libraries/monstra/Form.php @@ -0,0 +1,409 @@ + + * + * // Registering a Form macro + * Form::macro('my_field', function() { + * return ''; + * }); + * + * // Calling a custom Form macro + * echo Form::my_field(); + * + * + * // Registering a Form macro with parameters + * Form::macro('my_field', function($value = '') { + * return ''; + * }); + * + * // Calling a custom Form macro with parameters + * echo Form::my_field('Monstra'); + * + * + * + * @param string $name Name + * @param Closure $macro Macro + */ + public static function macro($name, $macro) + { + Form::$macros[$name] = $macro; + } + + /** + * Create an opening HTML form tag. + * + * + * // Form will submit back to the current page using POST + * echo Form::open(); + * + * // Form will submit to 'search' using GET + * echo Form::open('search', array('method' => 'get')); + * + * // When "file" inputs are present, you must include the "enctype" + * echo Form::open(null, array('enctype' => 'multipart/form-data')); + * + * + * @param mixed $action Form action, defaults to the current request URI. + * @param array $attributes HTML attributes. + * @uses Url::base + * @uses Html::attributes + * @return string + */ + public static function open($action = null, array $attributes = null) + { + if (! $action) { + + // Submits back to the current url + $action = ''; + + } elseif (strpos($action, '://') === false) { + + // Make the URI absolute + $action = Url::base() . '/' . $action; + } + + // Add the form action to the attributes + $attributes['action'] = $action; + + if ( ! isset($attributes['method'])) { + + // Use POST method + $attributes['method'] = 'post'; + } + + return ''; + } + + /** + * Create a form input. + * Text is default input type. + * + * + * echo Form::input('username', $username); + * + * + * @param string $name Input name + * @param string $value Input value + * @param array $attributes HTML attributes + * @uses Html::attributes + * @return string + */ + public static function input($name, $value = null, array $attributes = null) + { + // Set the input name + $attributes['name'] = $name; + + // Set the input 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 ''; + } + + /** + * Create a hidden form input. + * + * + * echo Form::hidden('user_id', $user_id); + * + * + * @param string $name Input name + * @param string $value Input value + * @param array $attributes HTML attributes + * @uses Form::input + * @return string + */ + public static function hidden($name, $value = null, array $attributes = null) + { + // Set the input type + $attributes['type'] = 'hidden'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a password form input. + * + * + * echo Form::password('password'); + * + * + * @param string $name Input name + * @param string $value Input value + * @param array $attributes HTML attributes + * @uses Form::input + * @return string + */ + public static function password($name, $value = null, array $attributes = null) + { + // Set the input type + $attributes['type'] = 'password'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a file upload form input. + * + * + * echo Form::file('image'); + * + * + * @param string $name Input name + * @param array $attributes HTML attributes + * @uses Form::input + * @return string + */ + public static function file($name, array $attributes = null) + { + // Set the input type + $attributes['type'] = 'file'; + + return Form::input($name, null, $attributes); + } + + /** + * Creates a checkbox form input. + * + * + * echo Form::checkbox('i_am_not_a_robot'); + * + * + * @param string $name Input name + * @param string $input Input value + * @param boolean $checked Checked status + * @param array $attributes HTML attributes + * @uses Form::input + * @return string + */ + public static function checkbox($name, $value = null, $checked = false, array $attributes = null) + { + // Set the input type + $attributes['type'] = 'checkbox'; + + if ($checked === true) { + // Make the checkbox active + $attributes['checked'] = 'checked'; + } + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a radio form input. + * + * + * echo Form::radio('i_am_not_a_robot'); + * + * + * @param string $name Input name + * @param string $value Input value + * @param boolean $checked Checked status + * @param array $attributes HTML attributes + * @uses Form::input + * @return string + */ + public static function radio($name, $value = null, $checked = null, array $attributes = null) + { + // Set the input type + $attributes['type'] = 'radio'; + + if ($checked === true) { + // Make the radio active + $attributes['checked'] = 'checked'; + } + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a textarea form input. + * + * + * echo Form::textarea('text', $text); + * + * + * @param string $name Name + * @param string $body Body + * @param array $attributes HTML attributes + * @uses Html::attributes + * @return string + */ + public static function textarea($name, $body = '', array $attributes = null) + { + // Set the input name + $attributes['name'] = $name; + + // Set the input id + $attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name; + + return ''.$body.''; + } + + /** + * Creates a select form input. + * + * + * echo Form::select('themes', array('default', 'classic', 'modern')); + * + * + * @param string $name Name + * @param array $options Options array + * @param string $selected Selected option + * @param array $attributes HTML attributes + * @uses Html::attributes + * @return string + */ + public static function select($name, array $options = null, $selected = null, array $attributes = null) + { + // Set the input name + $attributes['name'] = $name; + + // 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 .= ''; + } + + return ''.$options_output.''; + } + + /** + * Creates a submit form input. + * + * + * echo Form::submit('save', 'Save'); + * + * + * @param string $name Input name + * @param string $value Input value + * @param array $attributes HTML attributes + * @uses Form::input + * @return string + */ + public static function submit($name, $value, array $attributes = null) + { + // Set the input type + $attributes['type'] = 'submit'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a button form input. + * + * + * echo Form::button('save', 'Save Profile', array('type' => 'submit')); + * + * + * @param string $name Input name + * @param string $value Input value + * @param array $attributes HTML attributes + * @uses Html::attributes + * @return string + */ + public static function button($name, $body, array $attributes = null) + { + // Set the input name + $attributes['name'] = $name; + + return ''.$body.''; + } + + /** + * Creates a form label. + * + * + * echo Form::label('username', 'Username'); + * + * + * @param string $input Target input + * @param string $text Label text + * @param array $attributes HTML attributes + * @uses Html::attributes + * @return string + */ + public static function label($input, $text, array $attributes = null) + { + // Set the label target + $attributes['for'] = $input; + + return ''.$text.''; + } + + /** + * Create closing form tag. + * + * + * echo Form::close(); + * + * + * @return string + */ + public static function close() + { + return ''; + } + + /** + * 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."); + } + +} diff --git a/libraries/monstra/Html.php b/libraries/monstra/Html.php new file mode 100644 index 0000000..cbe6428 --- /dev/null +++ b/libraries/monstra/Html.php @@ -0,0 +1,314 @@ + + * + * // Registering a Htmlk macro + * Html::macro('my_element', function() { + * return ''; + * }); + * + * // Calling a custom Html macro + * echo Html::my_element(); + * + * + * // Registering a Html macro with parameters + * Html::macro('my_element', function(id = '') { + * return ''; + * }); + * + * // Calling a custom Html macro with parameters + * echo Html::my_element('monstra'); + * + * + * + * @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. + * + * + * echo Html::chars($username); + * + * + * @param string $value String to convert + * @param boolean $double_encode Encode existing entities + * @return string + */ + public static function chars($value, $double_encode = true) + { + return htmlspecialchars((string) $value, ENT_QUOTES, 'utf-8', $double_encode); + } + + /** + * Compiles an array of HTML attributes into an attribute string. + * Attributes will be sorted using Html::$attribute_order for consistency. + * + * + * echo ''.$content.''; + * + * + * @param array $attributes Attribute list + * @return string + */ + public static function attributes(array $attributes = null) + { + if (empty($attributes)) return ''; + + // Init var + $sorted = array(); + + foreach (Html::$attribute_order as $key) { + + if (isset($attributes[$key])) { + // Add the attribute to the sorted list + $sorted[$key] = $attributes[$key]; + } + + } + + // Combine the sorted attributes + $attributes = $sorted + $attributes; + + $compiled = ''; + foreach ($attributes as $key => $value) { + + if ($value === NULL) { + // Skip attributes that have NULL values + continue; + } + + if (is_int($key)) { + // Assume non-associative keys are mirrored attributes + $key = $value; + } + + // Add the attribute value + $compiled .= ' '.$key.'="'.Html::chars($value).'"'; + } + + return $compiled; + } + + /** + * Create br tags + * + * + * echo Html::br(2); + * + * + * @param integer $num Count of line break tag + * @return string + */ + public static function br($num = 1) + { + return str_repeat("
    ",(int) $num); + } + + /** + * Create   + * + * + * echo Html::nbsp(2); + * + * + * @param integer $num Count of   + * @return string + */ + public static function nbsp($num = 1) + { + return str_repeat(" ", (int) $num); + } + + /** + * Create an arrow + * + * + * echo Html::arrow('right'); + * + * + * @param string $direction Arrow direction [up,down,left,right] + * @param boolean $render If this option is true then render html object else return it + * @return string + */ + public static function arrow($direction) + { + switch ($direction) { + case "up": $output = ''; break; + case "down": $output = ''; break; + case "left": $output = ''; break; + case "right": $output = ''; break; + } + + return $output; + } + + /** + * Create HTML link anchor. + * + * + * echo Html::anchor('About', 'http://sitename.com/about'); + * + * + * @param string $title Anchor title + * @param string $url Anchor url + * @param array $attributes Anchor attributes + * @uses Html::attributes + * @return string + */ + public static function anchor($title, $url = null, array $attributes = null) + { + // Add link + if ($url !== null) $attributes['href'] = $url; + return ''.$title.''; + } + + /** + * Create HTML tag + * + * + * echo Html::heading('Title', 1); + * + * + * @param string $title Text + * @param integer $h Number [1-6] + * @param array $attributes Heading attributes + * @uses Html::attributes + * @return string + */ + public static function heading($title, $h = 1, array $attributes = null) + { + $output = ''.$title.''; + + return $output; + } + + /** + * Generate document type declarations + * + * + * echo Html::doctype('html5'); + * + * + * @param string $type Doctype to generated + * @return mixed + */ + public static function doctype($type = 'html5') + { + $doctypes = array('xhtml11' => '', + 'xhtml1-strict' => '', + 'xhtml1-trans' => '', + 'xhtml1-frame' => '', + 'html5' => '', + 'html4-strict' => '', + 'html4-trans' => '', + 'html4-frame' => ''); + + if (isset($doctypes[$type])) return $doctypes[$type]; else return false; + + } + + /** + * Create image + * + * + * echo Html::image('data/files/pic1.jpg'); + * + * + * @param array $attributes Image attributes + * @param string $file File + * @uses Url::base + * @return string + */ + public static function image($file, array $attributes = null) + { + if (strpos($file, '://') === FALSE) { + $file = Url::base().'/'.$file; + } + + // Add the image link + $attributes['src'] = $file; + $attributes['alt'] = (isset($attributes['alt'])) ? $attributes['alt'] : pathinfo($file, PATHINFO_FILENAME); + + return ''; + } + + /** + * Convert html to plain text + * + * + * echo Html::toText('test'); + * + * + * @param string $str String + * @return string + */ + public static function toText($str) + { + return htmlspecialchars($str, ENT_QUOTES, 'utf-8'); + } + + /** + * 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."); + } + +} diff --git a/libraries/monstra/Image.php b/libraries/monstra/Image.php new file mode 100644 index 0000000..ffde0d2 --- /dev/null +++ b/libraries/monstra/Image.php @@ -0,0 +1,653 @@ +image_info)) return $this->image_info[$key]; + } + + /** + * Set value for specific key + * + * @param string $key Key + * @param mixed $value Value + */ + public function __set($key, $value) + { + $this->image_info[$key] = $value; + } + + /** + * Image factory. + * + * + * $image = Image::factory('original.png'); + * + * + * @param string $filename Filename + * @return Image + */ + public static function factory($filename) + { + return new Image($filename); + } + + /** + * Construct + * + * @param string $file Filename + */ + public function __construct($file) + { + // Redefine vars + $file = (string) $file; + + // Check if the file exists + if (file_exists($file)) { + + // Extract attributes of the image file + list($this->width, $this->height, $type, $a) = getimagesize($file); + + // Save image type + $this->type = $type; + + // Create a new image + $this->image = $this->createImage($file, $type); + } else { + throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__))); + } + } + + /** + * Create a new image from file. + * + * @param string $file Path to the image file + * @param integer $type Image type + * @return resource + */ + protected function createImage($file, $type) + { + // Create image from file + switch ($type) { + case IMAGETYPE_JPEG: + return imagecreatefromjpeg($file); + break; + case IMAGETYPE_GIF: + return imagecreatefromgif($file); + break; + case IMAGETYPE_PNG: + return imagecreatefrompng($file); + break; + default: + throw new RuntimeException(vsprintf("%s(): Unable to open '%s'. Unsupported image type.", array(__METHOD__, $type))); + } + } + + /** + * Resizes the image to the chosen size. + * + * + * Image::factory('original.png')->resize(800, 600)->save('edited.png'); + * + * + * @param integer $width Width of the image + * @param integer $height Height of the image + * @param integer $aspect_ratio Aspect ratio (Image::AUTO Image::WIDTH Image::HEIGHT) + * @return Image + */ + public function resize($width, $height = null, $aspect_ratio = null) + { + // Redefine vars + $width = (int) $width; + $height = ($height === null) ? null : (int) $height; + $aspect_ratio = ($aspect_ratio === null) ? null : (int) $aspect_ratio; + + // Resizes the image to {$width}% of the original size + if ($height === null) { + + $new_width = round($this->width * ($width / 100)); + $new_height = round($this->height * ($width / 100)); + + } else { + + // Resizes the image to the smalles possible dimension while maintaining aspect ratio + if ($aspect_ratio === Image::AUTO) { + + // Calculate smallest size based on given height and width while maintaining aspect ratio + $percentage = min(($width / $this->width), ($height / $this->height)); + + $new_width = round($this->width * $percentage); + $new_height = round($this->height * $percentage); + + // Resizes the image using the width to maintain aspect ratio + } elseif ($aspect_ratio === Image::WIDTH) { + + // Base new size on given width while maintaining aspect ratio + $new_width = $width; + $new_height = round($this->height * ($width / $this->width)); + + // Resizes the image using the height to maintain aspect ratio + } elseif ($aspect_ratio === Image::HEIGHT) { + + // Base new size on given height while maintaining aspect ratio + $new_width = round($this->width * ($height / $this->height)); + $new_height = $height; + + // Resizes the image to a dimension of {$width}x{$height} pixels while ignoring the aspect ratio + } else { + + $new_width = $width; + $new_height = $height; + } + } + + // Create a new true color image width new width and height + $resized = imagecreatetruecolor($new_width, $new_height); + + // Copy and resize part of an image with resampling + imagecopyresampled($resized, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->width, $this->height); + + // Destroy an image + imagedestroy($this->image); + + // Create a new true color image width new width and height + $this->image = imagecreatetruecolor($new_width, $new_height); + + // Copy and resize part of an image with resampling + imagecopyresampled($this->image, $resized, 0, 0, 0, 0, $new_width, $new_height, $new_width, $new_height); + + // Destroy an image + imagedestroy($resized); + + // Save new width and height + $this->width = $new_width; + $this->height = $new_height; + + return $this; + } + + /** + * Crops the image + * + * + * Image::factory('original.png')->crop(800, 600, 0, 0)->save('edited.png'); + * + * + * @param integer $width Width of the crop + * @param integer $height Height of the crop + * @param integer $x The X coordinate of the cropped region's top left corner + * @param integer $y The Y coordinate of the cropped region's top left corner + * @return Image + */ + public function crop($width, $height, $x, $y) + { + // Redefine vars + $width = (int) $width; + $height = (int) $height; + $x = (int) $x; + $y = (int) $y; + + // Calculate + if ($x + $width > $this->width) $width = $this->width - $x; + if ($y + $height > $this->height) $height = $this->height - $y; + if ($width <= 0 || $height <= 0) return false; + + // Create a new true color image + $crop = imagecreatetruecolor($width, $height); + + // Copy and resize part of an image with resampling + imagecopyresampled($crop, $this->image, 0, 0, $x, $y, $this->width, $this->height, $this->width, $this->height); + + // Destroy an image + imagedestroy($this->image); + + // Create a new true color image + $this->image = imagecreatetruecolor($width, $height); + + // Copy and resize part of an image with resampling + imagecopyresampled($this->image, $crop, 0, 0, 0, 0, $width, $height, $width, $height); + + // Destroy an image + imagedestroy($crop); + + // Save new width and height + $this->width = $width; + $this->height = $height; + + return $this; + } + + /** + * Adds a watermark to the image. + * + * @param string $file Path to the image file + * @param integer $position Position of the watermark + * @param integer $opacity Opacity of the watermark in percent + * @return Image + */ + public function watermark($file, $position = null, $opacity = 100) + { + // Check if the image exists + if ( ! file_exists($file)) { + throw new RuntimeException(vsprintf("%s(): The image file ('%s') does not exist.", array(__METHOD__, $file))); + } + + $watermark = $this->createImage($file, $this->type); + + $watermarkW = imagesx($watermark); + $watermarkH = imagesy($watermark); + + // Make sure that opacity is between 0 and 100 + $opacity = max(min((int) $opacity, 100), 0); + + if ($opacity < 100) { + + if (GD_BUNDLED === 0) { + throw new RuntimeException(vsprintf("%s(): Setting watermark opacity requires the 'imagelayereffect' function which is only available in the bundled version of GD.", array(__METHOD__))); + } + + // Convert alpha to 0-127 + $alpha = min(round(abs(($opacity * 127 / 100) - 127)), 127); + + $transparent = imagecolorallocatealpha($watermark, 0, 0, 0, $alpha); + + imagelayereffect($watermark, IMG_EFFECT_OVERLAY); + + imagefilledrectangle($watermark, 0, 0, $watermarkW, $watermarkH, $transparent); + } + + // Position the watermark. + switch ($position) { + case Image::TOP_RIGHT: + $x = imagesx($this->image) - $watermarkW; + $y = 0; + break; + case Image::BOTTOM_LEFT: + $x = 0; + $y = imagesy($this->image) - $watermarkH; + break; + case Image::BOTTOM_RIGHT: + $x = imagesx($this->image) - $watermarkW; + $y = imagesy($this->image) - $watermarkH; + break; + case Image::CENTER: + $x = (imagesx($this->image) / 2) - ($watermarkW / 2); + $y = (imagesy($this->image) / 2) - ($watermarkH / 2); + break; + default: + $x = 0; + $y = 0; + } + + imagealphablending($this->image, true); + + imagecopy($this->image, $watermark, $x, $y, 0, 0, $watermarkW, $watermarkH); + + imagedestroy($watermark); + + // Return Image + return $this; + } + + /** + * Convert image into grayscale + * + * + * Image::factory('original.png')->grayscale()->save('edited.png'); + * + * + * @return Image + */ + public function grayscale() + { + imagefilter($this->image, IMG_FILTER_GRAYSCALE); + + return $this; + } + + /** + * Convert image into sepia + * + * + * Image::factory('original.png')->sepia()->save('edited.png'); + * + * + * @return Image + */ + public function sepia() + { + imagefilter($this->image, IMG_FILTER_GRAYSCALE); + imagefilter($this->image, IMG_FILTER_COLORIZE, 112, 66, 20); + + return $this; + } + + /** + * Convert image into brightness + * + * + * Image::factory('original.png')->brightness(60)->save('edited.png'); + * + * + * @param integer $level Level. From -255(min) to 255(max) + * @return Image + */ + public function brightness($level = 0) + { + imagefilter($this->image, IMG_FILTER_BRIGHTNESS, (int) $level); + + return $this; + } + + /** + * Convert image into colorize + * + * + * Image::factory('original.png')->colorize(60, 0, 0)->save('edited.png'); + * + * + * @param integer $red Red + * @param integer $green Green + * @param integer $blue Blue + * @return Image + */ + public function colorize($red, $green, $blue) + { + imagefilter($this->image, IMG_FILTER_COLORIZE, (int) $red, (int) $green, (int) $blue); + + return $this; + } + + /** + * Convert image into contrast + * + * + * Image::factory('original.png')->contrast(60)->save('edited.png'); + * + * + * @param integer $level Level. From -100(max) to 100(min) note the direction! + * @return Image + */ + public function contrast($level) + { + imagefilter($this->image, IMG_FILTER_CONTRAST, (int) $level); + + return $this; + } + + /** + * Creates a color based on a hex value. + * + * @param string $hex Hex code of the color + * @param integer $alpha Alpha. Default is 100 + * @param boolean $returnRGB FALSE returns a color identifier, TRUE returns a RGB array + * @return integer + */ + protected function createColor($hex, $alpha = 100, $return_rgb = false) + { + // Redefine vars + $hex = (string) $hex; + $alpha = (int) $alpha; + $return_rgb = (bool) $return_rgb; + + $hex = str_replace('#', '', $hex); + + if (preg_match('/^([a-f0-9]{3}){1,2}$/i', $hex) === 0) { + throw new RuntimeException(vsprintf("%s(): Invalid color code ('%s').", array(__METHOD__, $hex))); + } + + if (strlen($hex) === 3) { + + $r = hexdec(str_repeat(substr($hex, 0, 1), 2)); + $g = hexdec(str_repeat(substr($hex, 1, 1), 2)); + $b = hexdec(str_repeat(substr($hex, 2, 1), 2)); + + } else { + + $r = hexdec(substr($hex, 0, 2)); + $g = hexdec(substr($hex, 2, 2)); + $b = hexdec(substr($hex, 4, 2)); + + } + + if ($return_rgb === true) { + return array('r' => $r, 'g' => $g, 'b' => $b); + + } else { + + // Convert alpha to 0-127 + $alpha = min(round(abs(($alpha * 127 / 100) - 127)), 127); + + return imagecolorallocatealpha($this->image, $r, $g, $b, $alpha); + } + } + + /** + * Rotates the image using the given angle in degrees. + * + * + * Image::factory('original.png')->rotate(90)->save('edited.png'); + * + * + * @param integer $degrees Degrees to rotate the image + * @return Image + */ + public function rotate($degrees) + { + if (GD_BUNDLED === 0) { + throw new RuntimeException(vsprintf("%s(): This method requires the 'imagerotate' function which is only available in the bundled version of GD.", array(__METHOD__))); + } + + // Redefine vars + $degrees = (int) $degrees; + + // Get image width and height + $width = imagesx($this->image); + $height = imagesy($this->image); + + // Allocate a color for an image + $transparent = imagecolorallocatealpha($this->image, 0, 0, 0, 127); + + // Rotate gif image + if ($this->image_info['type'] === IMAGETYPE_GIF) { + + // Create a new true color image + $temp = imagecreatetruecolor($width, $height); + + // Flood fill + imagefill($temp, 0, 0, $transparent); + + // Copy part of an image + imagecopy($temp, $this->image, 0, 0, 0, 0, $width, $height); + + // Destroy an image + imagedestroy($this->image); + + // Save temp image + $this->image = $temp; + } + + // Rotate an image with a given angle + $this->image = imagerotate($this->image, (360 - $degrees), $transparent); + + // Define a color as transparent + imagecolortransparent($this->image, $transparent); + + return $this; + } + + /** + * Adds a border to the image. + * + * + * Image::factory('original.png')->border('#000', 5)->save('edited.png'); + * + * + * @param string $color Hex code for the color + * @param integer $thickness Thickness of the frame in pixels + * @return Image + */ + public function border($color = '#000', $thickness = 5) + { + // Redefine vars + $color = (string) $color; + $thickness = (int) $thickness; + + // Get image width and height + $width = imagesx($this->image); + $height = imagesy($this->image); + + // Creates a color based on a hex value + $color = $this->createColor($color); + + // Create border + for ($i = 0; $i < $thickness; $i++) { + + if ($i < 0) { + + $x = $width + 1; + $y = $hidth + 1; + + } else { + + $x = --$width; + $y = --$height; + + } + + imagerectangle($this->image, $i, $i, $x, $y, $color); + } + + return $this; + } + + /** + * Save image + * + * + * Image::factory('original.png')->save('edited.png'); + * + * + * @param string $dest Desitination location of the file + * @param integer $quality Image quality. Default is 100 + * @return Image + */ + public function save($file, $quality = 100) + { + // Redefine vars + $file = (string) $file; + $quality = (int) $quality; + + $path_info = pathinfo($file); + + if ( ! is_writable($path_info['dirname'])) { + throw new RuntimeException(vsprintf("%s(): '%s' is not writable.", array(__METHOD__, $path_info['dirname']))); + } + + // Make sure that quality is between 0 and 100 + $quality = max(min((int) $quality, 100), 0); + + // Save image + switch ($path_info['extension']) { + case 'jpg': + case 'jpeg': + imagejpeg($this->image, $file, $quality); + break; + case 'gif': + imagegif($this->image, $file); + break; + case 'png': + imagealphablending($this->image, true); + imagesavealpha($this->image, true); + imagepng($this->image, $file, (9 - (round(($quality / 100) * 9)))); + break; + default: + throw new RuntimeException(vsprintf("%s(): Unable to save to '%s'. Unsupported image format.", array(__METHOD__, $path_info['extension']))); + } + + // Return Image + return $this; + } + + /** + * Destructor + */ + public function __destruct() + { + imagedestroy($this->image); + } + +} diff --git a/libraries/monstra/Inflector.php b/libraries/monstra/Inflector.php new file mode 100644 index 0000000..c417691 --- /dev/null +++ b/libraries/monstra/Inflector.php @@ -0,0 +1,224 @@ + '\1\2en', // ox + '/([m|l])ouse$/' => '\1ice', // mouse, louse + '/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index + '/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address + '/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency + '/(hive)$/' => '\1s', // archive, hive + '/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife + '/sis$/' => 'ses', // basis, diagnosis + '/([ti])um$/' => '\1a', // datum, medium + '/(p)erson$/' => '\1eople', // person, salesperson + '/(m)an$/' => '\1en', // man, woman, spokesman + '/(c)hild$/' => '\1hildren', // child + '/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato + '/(bu|campu)s$/' => '\1\2ses', // bus, campus + '/(alias|status|virus)$/' => '\1es', // alias + '/(octop)us$/' => '\1i', // octopus + '/(ax|cris|test)is$/' => '\1es', // axis, crisis + '/s$/' => 's', // no change (compatibility) + '/$/' => 's', + ); + + /** + * Singular rules + * + * @var array + */ + protected static $singular_rules = array( + '/(matr)ices$/' => '\1ix', + '/(vert|ind)ices$/' => '\1ex', + '/^(ox)en/' => '\1', + '/(alias)es$/' => '\1', + '/([octop|vir])i$/' => '\1us', + '/(cris|ax|test)es$/' => '\1is', + '/(shoe)s$/' => '\1', + '/(o)es$/' => '\1', + '/(bus|campus)es$/' => '\1', + '/([m|l])ice$/' => '\1ouse', + '/(x|ch|ss|sh)es$/' => '\1', + '/(m)ovies$/' => '\1\2ovie', + '/(s)eries$/' => '\1\2eries', + '/([^aeiouy]|qu)ies$/' => '\1y', + '/([lr])ves$/' => '\1f', + '/(tive)s$/' => '\1', + '/(hive)s$/' => '\1', + '/([^f])ves$/' => '\1fe', + '/(^analy)ses$/' => '\1sis', + '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis', + '/([ti])a$/' => '\1um', + '/(p)eople$/' => '\1\2erson', + '/(m)en$/' => '\1an', + '/(s)tatuses$/' => '\1\2tatus', + '/(c)hildren$/' => '\1\2hild', + '/(n)ews$/' => '\1\2ews', + '/([^us])s$/' => '\1', + ); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + /** + * Returns a camelized string from a string using underscore syntax. + * + * + * // "some_text_here" becomes "SomeTextHere" + * echo Inflector::camelize('some_text_here'); + * + * + * @param string $string Word to camelize. + * @return string Camelized word. + */ + public static function camelize($string) + { + // Redefine vars + $string = (string) $string; + + return str_replace(' ', '', ucwords(str_replace('_', ' ', $string))); + } + + /** + * Returns a string using underscore syntax from a camelized string. + * + * + * // "SomeTextHere" becomes "some_text_here" + * echo Inflector::underscore('SomeTextHere'); + * + * + * @param string $string CamelCased word + * @return string Underscored version of the $string + */ + public static function underscore($string) + { + // Redefine vars + $string = (string) $string; + + return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string)); + } + + /** + * Returns a humanized string from a string using underscore syntax. + * + * + * // "some_text_here" becomes "Some text here" + * echo Inflector::humanize('some_text_here'); + * + * + * @param string $string String using underscore syntax. + * @return string Humanized version of the $string + */ + public static function humanize($string) + { + // Redefine vars + $string = (string) $string; + + return ucfirst(strtolower(str_replace('_', ' ', $string))); + } + + /** + * Returns ordinalize number. + * + * + * // 1 becomes 1st + * echo Inflector::ordinalize(1); + * + * + * @param integer $number Number to ordinalize + * @return string + */ + public static function ordinalize($number) + { + if ( ! is_numeric($number)) { + return $number; + } + + if (in_array(($number % 100), range(11, 13))) { + return $number . 'th'; + } else { + switch ($number % 10) { + case 1: return $number . 'st'; break; + case 2: return $number . 'nd'; break; + case 3: return $number . 'rd'; break; + default: return $number . 'th'; break; + } + } + } + + /** + * Returns the plural version of the given word + * + * + * echo Inflector::pluralize('cat'); + * + * + * @param string $word Word to pluralize + * @return string + */ + public static function pluralize($word) + { + $result = (string) $word; + + foreach (Inflector::$plural_rules as $rule => $replacement) { + if (preg_match($rule, $result)) { + $result = preg_replace($rule, $replacement, $result); + break; + } + } + + return $result; + } + + /** + * Returns the singular version of the given word + * + * + * echo Inflector::singularize('cats'); + * + * + * @param string $word Word to singularize + * @return string + */ + public static function singularize($word) + { + $result = (string) $word; + + foreach (Inflector::$singular_rules as $rule => $replacement) { + if (preg_match($rule, $result)) { + $result = preg_replace($rule, $replacement, $result); + break; + } + } + + return $result; + } + +} diff --git a/libraries/monstra/Minify.php b/libraries/monstra/Minify.php new file mode 100644 index 0000000..64fbdf9 --- /dev/null +++ b/libraries/monstra/Minify.php @@ -0,0 +1,91 @@ + + * echo Minify::html($buffer); + * + * + * @param string $buffer html + * @return string + */ + public static function html($buffer) + { + return preg_replace('/^\\s+|\\s+$/m', '', $buffer); + } + + /** + * Minify css + * + * + * echo Minify::css($buffer); + * + * + * @param string $buffer css + * @return string + */ + public static function css($buffer) + { + // Remove comments + $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); + + // Remove tabs, spaces, newlines, etc. + $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); + + // Preserve empty comment after '>' http://www.webdevout.net/css-hacks#in_css-selectors + $buffer = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $buffer); + + // Preserve empty comment between property and value + // http://css-discuss.incutio.com/?page=BoxModelHack + $buffer = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $buffer); + $buffer = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $buffer); + + // Remove ws around { } and last semicolon in declaration block + $buffer = preg_replace('/\\s*{\\s*/', '{', $buffer); + $buffer = preg_replace('/;?\\s*}\\s*/', '}', $buffer); + + // Remove ws surrounding semicolons + $buffer = preg_replace('/\\s*;\\s*/', ';', $buffer); + + // Remove ws around urls + $buffer = preg_replace('/url\\(\\s*([^\\)]+?)\\s*\\)/x', 'url($1)', $buffer); + + // Remove ws between rules and colons + $buffer = preg_replace('/\\s*([{;])\\s*([\\*_]?[\\w\\-]+)\\s*:\\s*(\\b|[#\'"])/x', '$1$2:$3', $buffer); + + // Minimize hex colors + $buffer = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $buffer); + + // Replace any ws involving newlines with a single newline + $buffer = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $buffer); + + return $buffer; + } + +} diff --git a/libraries/monstra/Monstra.php b/libraries/monstra/Monstra.php new file mode 100644 index 0000000..456c307 --- /dev/null +++ b/libraries/monstra/Monstra.php @@ -0,0 +1,117 @@ + + * echo Notification::get('success'); + * echo Notification::get('errors'); + * + * + * @param string $key Variable name + * @return mixed + */ + public static function get($key) + { + // Redefine arguments + $key = (string) $key; + + // Return specific variable from the Notifications array + return isset(Notification::$notifications[$key]) ? Notification::$notifications[$key] : null; + } + + /** + * Adds specific variable to the Notifications array. + * + * + * Notification::set('success', 'Data has been saved with success!'); + * Notification::set('errors', 'Data not saved!'); + * + * + * @param string $key Variable name + * @param mixed $value Variable value + */ + public static function set($key, $value) + { + // Redefine arguments + $key = (string) $key; + + // Save specific variable to the Notifications array + $_SESSION[Notification::SESSION_KEY][$key] = $value; + } + + /** + * Adds specific variable to the Notifications array for current page. + * + * + * Notification::setNow('success', 'Success!'); + * + * + * @param string $var Variable name + * @param mixed $value Variable value + */ + public static function setNow($key, $value) + { + // Redefine arguments + $key = (string) $key; + + // Save specific variable for current page only + Notification::$notifications[$key] = $value; + } + + /** + * Clears the Notifications array. + * + * + * Notification::clean(); + * + * + * Data that previous pages stored will not be deleted, just the data that + * this page stored itself. + */ + public static function clean() + { + $_SESSION[Notification::SESSION_KEY] = array(); + } + + /** + * Initializes the Notification service. + * + * + * Notification::init(); + * + * + * This will read notification/flash data from the $_SESSION variable and load it into + * the $this->previous array. + */ + public static function init() + { + // Get notification/flash data... + + if ( ! empty($_SESSION[Notification::SESSION_KEY]) && is_array($_SESSION[Notification::SESSION_KEY])) { + Notification::$notifications = $_SESSION[Notification::SESSION_KEY]; + } + + $_SESSION[Notification::SESSION_KEY] = array(); + + } + +} diff --git a/libraries/monstra/Number.php b/libraries/monstra/Number.php new file mode 100644 index 0000000..2e95130 --- /dev/null +++ b/libraries/monstra/Number.php @@ -0,0 +1,203 @@ + + * echo Number::byteFormat(10000); + * + * + * @param integer $size Data to convert + * @return string + */ + public static function byteFormat($size) + { + // Redefine vars + $size = (int) $size; + + $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb'); + + return @round($size/pow(1024, ($i=floor(log($size, 1024)))), 2).' '.$unit[$i]; + } + + /** + * Converts a number into a more readable human-type number. + * + * + * echo Number::quantity(7000); // 7K + * echo Number::quantity(7500); // 8K + * echo Number::quantity(7500, 1); // 7.5K + * + * + * @param integer $num Num to convert + * @param integer $decimals Decimals + * @return string + */ + public static function quantity($num, $decimals = 0) + { + // Redefine vars + $num = (int) $num; + $decimals = (int) $decimals; + + if ($num >= 1000 && $num < 1000000) { + return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000)).'K'; + } elseif ($num >= 1000000 && $num < 1000000000) { + return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000)).'M'; + } elseif ($num >= 1000000000) { + return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000000)).'B'; + } + + return $num; + } + + /** + * Checks if the value is between the minimum and maximum (min & max included). + * + * + * if (Number::between(2, 10, 5)) { + * // do something... + * } + * + * + * @param float $minimum The minimum. + * @param float $maximum The maximum. + * @param float $value The value to validate. + * @return boolean + */ + public static function between($minimum, $maximum, $value) + { + return ((float) $value >= (float) $minimum && (float) $value <= (float) $maximum); + } + + /** + * Checks the value for an even number. + * + * + * if (Number::even(2)) { + * // do something... + * } + * + * + * @param integer $value The value to validate. + * @return boolean + */ + public static function even($value) + { + return (((int) $value % 2) == 0); + } + + /** + * Checks if the value is greather than a given minimum. + * + * + * if (Number::greaterThan(2, 10)) { + * // do something... + * } + * + * + * @param float $minimum The minimum as a float. + * @param float $value The value to validate. + * @return boolean + */ + public static function greaterThan($minimum, $value) + { + return ((float) $value > (float) $minimum); + } + + /** + * Checks if the value is smaller than a given maximum. + * + * + * if (Number::smallerThan(2, 10)) { + * // do something... + * } + * + * + * @param integer $maximum The maximum. + * @param integer $value The value to validate. + * @return boolean + */ + public static function smallerThan($maximum, $value) + { + return ((int) $value < (int) $maximum); + } + + /** + * Checks if the value is not greater than or equal a given maximum. + * + * + * if (Number::maximum(2, 10)) { + * // do something... + * } + * + * + * @param integer $maximum The maximum. + * @param integer $value The value to validate. + * @return boolean + */ + public static function maximum($maximum, $value) + { + return ((int) $value <= (int) $maximum); + } + + /** + * Checks if the value is greater than or equal to a given minimum. + * + * + * if (Number::minimum(2, 10)) { + * // do something... + * } + * + * + * @param integer $minimum The minimum. + * @param integer $value The value to validate. + * @return boolean + */ + public static function minimum($minimum, $value) + { + return ((int) $value >= (int) $minimum); + } + + /** + * Checks the value for an odd number. + * + * + * if (Number::odd(2)) { + * // do something... + * } + * + * + * @param integer $value The value to validate. + * @return boolean + */ + public static function odd($value) + { + return ! Number::even((int) $value); + } + +} diff --git a/libraries/monstra/Orm.php b/libraries/monstra/Orm.php new file mode 100644 index 0000000..dce1ff3 --- /dev/null +++ b/libraries/monstra/Orm.php @@ -0,0 +1,1266 @@ + 'sqlite::memory:', + 'id_column' => 'id', + 'id_column_overrides' => array(), + 'error_mode' => PDO::ERRMODE_EXCEPTION, + 'username' => null, + 'password' => null, + 'driver_options' => null, + 'identifier_quote_character' => null, // if this is null, will be autodetected + 'logging' => false, + 'caching' => false, + ); + + // Database connection, instance of the PDO class + protected static $_db; + + // Last query run, only populated if logging is enabled + protected static $_last_query; + + // Log of all queries run, only populated if logging is enabled + protected static $_query_log = array(); + + // Query cache, only used if query caching is enabled + protected static $_query_cache = array(); + + // --------------------------- // + // --- INSTANCE PROPERTIES --- // + // --------------------------- // + + // The name of the table the current ORM instance is associated with + protected $_table_name; + + // Alias for the table to be used in SELECT queries + protected $_table_alias = null; + + // Values to be bound to the query + protected $_values = array(); + + // Columns to select in the result + protected $_result_columns = array('*'); + + // Are we using the default result column or have these been manually changed? + protected $_using_default_result_columns = true; + + // Join sources + protected $_join_sources = array(); + + // Should the query include a DISTINCT keyword? + protected $_distinct = false; + + // Is this a raw query? + protected $_is_raw_query = false; + + // The raw query + protected $_raw_query = ''; + + // The raw query parameters + protected $_raw_parameters = array(); + + // Array of WHERE clauses + protected $_where_conditions = array(); + + // LIMIT + protected $_limit = null; + + // OFFSET + protected $_offset = null; + + // ORDER BY + protected $_order_by = array(); + + // GROUP BY + protected $_group_by = array(); + + // The data for a hydrated instance of the class + protected $_data = array(); + + // Fields that have been modified during the + // lifetime of the object + protected $_dirty_fields = array(); + + // Is this a new object (has create() been called)? + protected $_is_new = false; + + // Name of the column to use as the primary key for + // this instance only. Overrides the config settings. + protected $_instance_id_column = null; + + // ---------------------- // + // --- STATIC METHODS --- // + // ---------------------- // + + /** + * Pass configuration settings to the class in the form of + * key/value pairs. As a shortcut, if the second argument + * is omitted, the setting is assumed to be the DSN string + * used by PDO to connect to the database. Often, this + * will be the only configuration required to use Idiorm. + */ + public static function configure($key, $value=null) + { + // Shortcut: If only one argument is passed, + // assume it's a connection string + if (is_null($value)) { + $value = $key; + $key = 'connection_string'; + } + self::$_config[$key] = $value; + } + + /** + * Despite its slightly odd name, this is actually the factory + * method used to acquire instances of the class. It is named + * this way for the sake of a readable interface, ie + * ORM::for_table('table_name')->find_one()-> etc. As such, + * this will normally be the first method called in a chain. + */ + public static function for_table($table_name) + { + self::_setup_db(); + + return new self($table_name); + } + + /** + * Set up the database connection used by the class. + */ + protected static function _setup_db() + { + if (!is_object(self::$_db)) { + $connection_string = self::$_config['connection_string']; + $username = self::$_config['username']; + $password = self::$_config['password']; + $driver_options = self::$_config['driver_options']; + $db = new PDO($connection_string, $username, $password, $driver_options); + $db->setAttribute(PDO::ATTR_ERRMODE, self::$_config['error_mode']); + self::set_db($db); + } + } + + /** + * Set the PDO object used by Idiorm to communicate with the database. + * This is public in case the ORM should use a ready-instantiated + * PDO object as its database connection. + */ + public static function set_db($db) + { + self::$_db = $db; + self::_setup_identifier_quote_character(); + } + + /** + * Detect and initialise the character used to quote identifiers + * (table names, column names etc). If this has been specified + * manually using ORM::configure('identifier_quote_character', 'some-char'), + * this will do nothing. + */ + public static function _setup_identifier_quote_character() + { + if (is_null(self::$_config['identifier_quote_character'])) { + self::$_config['identifier_quote_character'] = self::_detect_identifier_quote_character(); + } + } + + /** + * Return the correct character used to quote identifiers (table + * names, column names etc) by looking at the driver being used by PDO. + */ + protected static function _detect_identifier_quote_character() + { + switch (self::$_db->getAttribute(PDO::ATTR_DRIVER_NAME)) { + case 'pgsql': + case 'sqlsrv': + case 'dblib': + case 'mssql': + case 'sybase': + return '"'; + case 'mysql': + case 'sqlite': + case 'sqlite2': + default: + return '`'; + } + } + + /** + * Returns the PDO instance used by the the ORM to communicate with + * the database. This can be called if any low-level DB access is + * required outside the class. + */ + public static function get_db() + { + self::_setup_db(); // required in case this is called before Idiorm is instantiated + + return self::$_db; + } + + /** + * Add a query to the internal query log. Only works if the + * 'logging' config option is set to true. + * + * This works by manually binding the parameters to the query - the + * query isn't executed like this (PDO normally passes the query and + * parameters to the database which takes care of the binding) but + * doing it this way makes the logged queries more readable. + */ + protected static function _log_query($query, $parameters) + { + // If logging is not enabled, do nothing + if (!self::$_config['logging']) { + return false; + } + + if (count($parameters) > 0) { + // Escape the parameters + $parameters = array_map(array(self::$_db, 'quote'), $parameters); + + // Replace placeholders in the query for vsprintf + $query = str_replace("?", "%s", $query); + + // Replace the question marks in the query with the parameters + $bound_query = vsprintf($query, $parameters); + } else { + $bound_query = $query; + } + + self::$_last_query = $bound_query; + self::$_query_log[] = $bound_query; + + return true; + } + + /** + * Get the last query executed. Only works if the + * 'logging' config option is set to true. Otherwise + * this will return null. + */ + public static function get_last_query() + { + return self::$_last_query; + } + + /** + * Get an array containing all the queries run up to + * now. Only works if the 'logging' config option is + * set to true. Otherwise returned array will be empty. + */ + public static function get_query_log() + { + return self::$_query_log; + } + + // ------------------------ // + // --- INSTANCE METHODS --- // + // ------------------------ // + + /** + * "Private" constructor; shouldn't be called directly. + * Use the ORM::for_table factory method instead. + */ + protected function __construct($table_name, $data=array()) + { + $this->_table_name = $table_name; + $this->_data = $data; + } + + /** + * Create a new, empty instance of the class. Used + * to add a new row to your database. May optionally + * be passed an associative array of data to populate + * the instance. If so, all fields will be flagged as + * dirty so all will be saved to the database when + * save() is called. + */ + public function create($data=null) + { + $this->_is_new = true; + if (!is_null($data)) { + return $this->hydrate($data)->force_all_dirty(); + } + + return $this; + } + + /** + * Specify the ID column to use for this instance or array of instances only. + * This overrides the id_column and id_column_overrides settings. + * + * This is mostly useful for libraries built on top of Idiorm, and will + * not normally be used in manually built queries. If you don't know why + * you would want to use this, you should probably just ignore it. + */ + public function use_id_column($id_column) + { + $this->_instance_id_column = $id_column; + + return $this; + } + + /** + * Create an ORM instance from the given row (an associative + * array of data fetched from the database) + */ + protected function _create_instance_from_row($row) + { + $instance = self::for_table($this->_table_name); + $instance->use_id_column($this->_instance_id_column); + $instance->hydrate($row); + + return $instance; + } + + /** + * Tell the ORM that you are expecting a single result + * back from your query, and execute it. Will return + * a single instance of the ORM class, or false if no + * rows were returned. + * As a shortcut, you may supply an ID as a parameter + * to this method. This will perform a primary key + * lookup on the table. + */ + public function find_one($id=null) + { + if (!is_null($id)) { + $this->where_id_is($id); + } + $this->limit(1); + $rows = $this->_run(); + + if (empty($rows)) { + return false; + } + + return $this->_create_instance_from_row($rows[0]); + } + + /** + * Tell the ORM that you are expecting multiple results + * from your query, and execute it. Will return an array + * of instances of the ORM class, or an empty array if + * no rows were returned. + */ + public function find_many() + { + $rows = $this->_run(); + + return array_map(array($this, '_create_instance_from_row'), $rows); + } + + /** + * Tell the ORM that you wish to execute a COUNT query. + * Will return an integer representing the number of + * rows returned. + */ + public function count() + { + $this->select_expr('COUNT(*)', 'count'); + $result = $this->find_one(); + + return ($result !== false && isset($result->count)) ? (int) $result->count : 0; + } + + /** + * This method can be called to hydrate (populate) this + * instance of the class from an associative array of data. + * This will usually be called only from inside the class, + * but it's public in case you need to call it directly. + */ + public function hydrate($data=array()) + { + $this->_data = $data; + + return $this; + } + + /** + * Force the ORM to flag all the fields in the $data array + * as "dirty" and therefore update them when save() is called. + */ + public function force_all_dirty() + { + $this->_dirty_fields = $this->_data; + + return $this; + } + + /** + * Perform a raw query. The query should contain placeholders, + * in either named or question mark style, and the parameters + * should be an array of values which will be bound to the + * placeholders in the query. If this method is called, all + * other query building methods will be ignored. + */ + public function raw_query($query, $parameters) + { + $this->_is_raw_query = true; + $this->_raw_query = $query; + $this->_raw_parameters = $parameters; + + return $this; + } + + /** + * Add an alias for the main table to be used in SELECT queries + */ + public function table_alias($alias) + { + $this->_table_alias = $alias; + + return $this; + } + + /** + * Internal method to add an unquoted expression to the set + * of columns returned by the SELECT query. The second optional + * argument is the alias to return the expression as. + */ + protected function _add_result_column($expr, $alias=null) + { + if (!is_null($alias)) { + $expr .= " AS " . $this->_quote_identifier($alias); + } + + if ($this->_using_default_result_columns) { + $this->_result_columns = array($expr); + $this->_using_default_result_columns = false; + } else { + $this->_result_columns[] = $expr; + } + + return $this; + } + + /** + * Add a column to the list of columns returned by the SELECT + * query. This defaults to '*'. The second optional argument is + * the alias to return the column as. + */ + public function select($column, $alias=null) + { + $column = $this->_quote_identifier($column); + + return $this->_add_result_column($column, $alias); + } + + /** + * Add an unquoted expression to the list of columns returned + * by the SELECT query. The second optional argument is + * the alias to return the column as. + */ + public function select_expr($expr, $alias=null) + { + return $this->_add_result_column($expr, $alias); + } + + /** + * Add a DISTINCT keyword before the list of columns in the SELECT query + */ + public function distinct() + { + $this->_distinct = true; + + return $this; + } + + /** + * Internal method to add a JOIN source to the query. + * + * The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this + * will be prepended to JOIN. + * + * The table should be the name of the table to join to. + * + * The constraint may be either a string or an array with three elements. If it + * is a string, it will be compiled into the query as-is, with no escaping. The + * recommended way to supply the constraint is as an array with three elements: + * + * first_column, operator, second_column + * + * Example: array('user.id', '=', 'profile.user_id') + * + * will compile to + * + * ON `user`.`id` = `profile`.`user_id` + * + * The final (optional) argument specifies an alias for the joined table. + */ + protected function _add_join_source($join_operator, $table, $constraint, $table_alias=null) + { + $join_operator = trim("{$join_operator} JOIN"); + + $table = $this->_quote_identifier($table); + + // Add table alias if present + if (!is_null($table_alias)) { + $table_alias = $this->_quote_identifier($table_alias); + $table .= " {$table_alias}"; + } + + // Build the constraint + if (is_array($constraint)) { + list($first_column, $operator, $second_column) = $constraint; + $first_column = $this->_quote_identifier($first_column); + $second_column = $this->_quote_identifier($second_column); + $constraint = "{$first_column} {$operator} {$second_column}"; + } + + $this->_join_sources[] = "{$join_operator} {$table} ON {$constraint}"; + + return $this; + } + + /** + * Add a simple JOIN source to the query + */ + public function join($table, $constraint, $table_alias=null) + { + return $this->_add_join_source("", $table, $constraint, $table_alias); + } + + /** + * Add an INNER JOIN souce to the query + */ + public function inner_join($table, $constraint, $table_alias=null) + { + return $this->_add_join_source("INNER", $table, $constraint, $table_alias); + } + + /** + * Add a LEFT OUTER JOIN souce to the query + */ + public function left_outer_join($table, $constraint, $table_alias=null) + { + return $this->_add_join_source("LEFT OUTER", $table, $constraint, $table_alias); + } + + /** + * Add an RIGHT OUTER JOIN souce to the query + */ + public function right_outer_join($table, $constraint, $table_alias=null) + { + return $this->_add_join_source("RIGHT OUTER", $table, $constraint, $table_alias); + } + + /** + * Add an FULL OUTER JOIN souce to the query + */ + public function full_outer_join($table, $constraint, $table_alias=null) + { + return $this->_add_join_source("FULL OUTER", $table, $constraint, $table_alias); + } + + /** + * Internal method to add a WHERE condition to the query + */ + protected function _add_where($fragment, $values=array()) + { + if (!is_array($values)) { + $values = array($values); + } + $this->_where_conditions[] = array( + self::WHERE_FRAGMENT => $fragment, + self::WHERE_VALUES => $values, + ); + + return $this; + } + + /** + * Helper method to compile a simple COLUMN SEPARATOR VALUE + * style WHERE condition into a string and value ready to + * be passed to the _add_where method. Avoids duplication + * of the call to _quote_identifier + */ + protected function _add_simple_where($column_name, $separator, $value) + { + $column_name = $this->_quote_identifier($column_name); + + return $this->_add_where("{$column_name} {$separator} ?", $value); + } + + /** + * Return a string containing the given number of question marks, + * separated by commas. Eg "?, ?, ?" + */ + protected function _create_placeholders($number_of_placeholders) + { + return join(", ", array_fill(0, $number_of_placeholders, "?")); + } + + /** + * Add a WHERE column = value clause to your query. Each time + * this is called in the chain, an additional WHERE will be + * added, and these will be ANDed together when the final query + * is built. + */ + public function where($column_name, $value) + { + return $this->where_equal($column_name, $value); + } + + /** + * More explicitly named version of for the where() method. + * Can be used if preferred. + */ + public function where_equal($column_name, $value) + { + return $this->_add_simple_where($column_name, '=', $value); + } + + /** + * Add a WHERE column != value clause to your query. + */ + public function where_not_equal($column_name, $value) + { + return $this->_add_simple_where($column_name, '!=', $value); + } + + /** + * Special method to query the table by its primary key + */ + public function where_id_is($id) + { + return $this->where($this->_get_id_column_name(), $id); + } + + /** + * Add a WHERE ... LIKE clause to your query. + */ + public function where_like($column_name, $value) + { + return $this->_add_simple_where($column_name, 'LIKE', $value); + } + + /** + * Add where WHERE ... NOT LIKE clause to your query. + */ + public function where_not_like($column_name, $value) + { + return $this->_add_simple_where($column_name, 'NOT LIKE', $value); + } + + /** + * Add a WHERE ... > clause to your query + */ + public function where_gt($column_name, $value) + { + return $this->_add_simple_where($column_name, '>', $value); + } + + /** + * Add a WHERE ... < clause to your query + */ + public function where_lt($column_name, $value) + { + return $this->_add_simple_where($column_name, '<', $value); + } + + /** + * Add a WHERE ... >= clause to your query + */ + public function where_gte($column_name, $value) + { + return $this->_add_simple_where($column_name, '>=', $value); + } + + /** + * Add a WHERE ... <= clause to your query + */ + public function where_lte($column_name, $value) + { + return $this->_add_simple_where($column_name, '<=', $value); + } + + /** + * Add a WHERE ... IN clause to your query + */ + public function where_in($column_name, $values) + { + $column_name = $this->_quote_identifier($column_name); + $placeholders = $this->_create_placeholders(count($values)); + + return $this->_add_where("{$column_name} IN ({$placeholders})", $values); + } + + /** + * Add a WHERE ... NOT IN clause to your query + */ + public function where_not_in($column_name, $values) + { + $column_name = $this->_quote_identifier($column_name); + $placeholders = $this->_create_placeholders(count($values)); + + return $this->_add_where("{$column_name} NOT IN ({$placeholders})", $values); + } + + /** + * Add a WHERE column IS NULL clause to your query + */ + public function where_null($column_name) + { + $column_name = $this->_quote_identifier($column_name); + + return $this->_add_where("{$column_name} IS NULL"); + } + + /** + * Add a WHERE column IS NOT NULL clause to your query + */ + public function where_not_null($column_name) + { + $column_name = $this->_quote_identifier($column_name); + + return $this->_add_where("{$column_name} IS NOT NULL"); + } + + /** + * Add a raw WHERE clause to the query. The clause should + * contain question mark placeholders, which will be bound + * to the parameters supplied in the second argument. + */ + public function where_raw($clause, $parameters=array()) + { + return $this->_add_where($clause, $parameters); + } + + /** + * Add a LIMIT to the query + */ + public function limit($limit) + { + $this->_limit = $limit; + + return $this; + } + + /** + * Add an OFFSET to the query + */ + public function offset($offset) + { + $this->_offset = $offset; + + return $this; + } + + /** + * Add an ORDER BY clause to the query + */ + protected function _add_order_by($column_name, $ordering) + { + $column_name = $this->_quote_identifier($column_name); + $this->_order_by[] = "{$column_name} {$ordering}"; + + return $this; + } + + /** + * Add an ORDER BY column DESC clause + */ + public function order_by_desc($column_name) + { + return $this->_add_order_by($column_name, 'DESC'); + } + + /** + * Add an ORDER BY column ASC clause + */ + public function order_by_asc($column_name) + { + return $this->_add_order_by($column_name, 'ASC'); + } + + /** + * Add a column to the list of columns to GROUP BY + */ + public function group_by($column_name) + { + $column_name = $this->_quote_identifier($column_name); + $this->_group_by[] = $column_name; + + return $this; + } + + /** + * Build a SELECT statement based on the clauses that have + * been passed to this instance by chaining method calls. + */ + protected function _build_select() + { + // If the query is raw, just set the $this->_values to be + // the raw query parameters and return the raw query + if ($this->_is_raw_query) { + $this->_values = $this->_raw_parameters; + + return $this->_raw_query; + } + + // Build and return the full SELECT statement by concatenating + // the results of calling each separate builder method. + return $this->_join_if_not_empty(" ", array( + $this->_build_select_start(), + $this->_build_join(), + $this->_build_where(), + $this->_build_group_by(), + $this->_build_order_by(), + $this->_build_limit(), + $this->_build_offset(), + )); + } + + /** + * Build the start of the SELECT statement + */ + protected function _build_select_start() + { + $result_columns = join(', ', $this->_result_columns); + + if ($this->_distinct) { + $result_columns = 'DISTINCT ' . $result_columns; + } + + $fragment = "SELECT {$result_columns} FROM " . $this->_quote_identifier($this->_table_name); + + if (!is_null($this->_table_alias)) { + $fragment .= " " . $this->_quote_identifier($this->_table_alias); + } + + return $fragment; + } + + /** + * Build the JOIN sources + */ + protected function _build_join() + { + if (count($this->_join_sources) === 0) { + return ''; + } + + return join(" ", $this->_join_sources); + } + + /** + * Build the WHERE clause(s) + */ + protected function _build_where() + { + // If there are no WHERE clauses, return empty string + if (count($this->_where_conditions) === 0) { + return ''; + } + + $where_conditions = array(); + foreach ($this->_where_conditions as $condition) { + $where_conditions[] = $condition[self::WHERE_FRAGMENT]; + $this->_values = array_merge($this->_values, $condition[self::WHERE_VALUES]); + } + + return "WHERE " . join(" AND ", $where_conditions); + } + + /** + * Build GROUP BY + */ + protected function _build_group_by() + { + if (count($this->_group_by) === 0) { + return ''; + } + + return "GROUP BY " . join(", ", $this->_group_by); + } + + /** + * Build ORDER BY + */ + protected function _build_order_by() + { + if (count($this->_order_by) === 0) { + return ''; + } + + return "ORDER BY " . join(", ", $this->_order_by); + } + + /** + * Build LIMIT + */ + protected function _build_limit() + { + if (!is_null($this->_limit)) { + return "LIMIT " . $this->_limit; + } + + return ''; + } + + /** + * Build OFFSET + */ + protected function _build_offset() + { + if (!is_null($this->_offset)) { + return "OFFSET " . $this->_offset; + } + + return ''; + } + + /** + * Wrapper around PHP's join function which + * only adds the pieces if they are not empty. + */ + protected function _join_if_not_empty($glue, $pieces) + { + $filtered_pieces = array(); + foreach ($pieces as $piece) { + if (is_string($piece)) { + $piece = trim($piece); + } + if (!empty($piece)) { + $filtered_pieces[] = $piece; + } + } + + return join($glue, $filtered_pieces); + } + + /** + * Quote a string that is used as an identifier + * (table names, column names etc). This method can + * also deal with dot-separated identifiers eg table.column + */ + protected function _quote_identifier($identifier) + { + $parts = explode('.', $identifier); + $parts = array_map(array($this, '_quote_identifier_part'), $parts); + + return join('.', $parts); + } + + /** + * This method performs the actual quoting of a single + * part of an identifier, using the identifier quote + * character specified in the config (or autodetected). + */ + protected function _quote_identifier_part($part) + { + if ($part === '*') { + return $part; + } + $quote_character = self::$_config['identifier_quote_character']; + + return $quote_character . $part . $quote_character; + } + + /** + * Create a cache key for the given query and parameters. + */ + protected static function _create_cache_key($query, $parameters) + { + $parameter_string = join(',', $parameters); + $key = $query . ':' . $parameter_string; + + return sha1($key); + } + + /** + * Check the query cache for the given cache key. If a value + * is cached for the key, return the value. Otherwise, return false. + */ + protected static function _check_query_cache($cache_key) + { + if (isset(self::$_query_cache[$cache_key])) { + return self::$_query_cache[$cache_key]; + } + + return false; + } + + /** + * Clear the query cache + */ + public static function clear_cache() + { + self::$_query_cache = array(); + } + + /** + * Add the given value to the query cache. + */ + protected static function _cache_query_result($cache_key, $value) + { + self::$_query_cache[$cache_key] = $value; + } + + /** + * Execute the SELECT query that has been built up by chaining methods + * on this class. Return an array of rows as associative arrays. + */ + protected function _run() + { + $query = $this->_build_select(); + $caching_enabled = self::$_config['caching']; + + if ($caching_enabled) { + $cache_key = self::_create_cache_key($query, $this->_values); + $cached_result = self::_check_query_cache($cache_key); + + if ($cached_result !== false) { + return $cached_result; + } + } + + self::_log_query($query, $this->_values); + $statement = self::$_db->prepare($query); + $statement->execute($this->_values); + + $rows = array(); + while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { + $rows[] = $row; + } + + if ($caching_enabled) { + self::_cache_query_result($cache_key, $rows); + } + + return $rows; + } + + /** + * Return the raw data wrapped by this ORM + * instance as an associative array. Column + * names may optionally be supplied as arguments, + * if so, only those keys will be returned. + */ + public function as_array() + { + if (func_num_args() === 0) { + return $this->_data; + } + $args = func_get_args(); + + return array_intersect_key($this->_data, array_flip($args)); + } + + /** + * Return the value of a property of this object (database row) + * or null if not present. + */ + public function get($key) + { + return isset($this->_data[$key]) ? $this->_data[$key] : null; + } + + /** + * Return the name of the column in the database table which contains + * the primary key ID of the row. + */ + protected function _get_id_column_name() + { + if (!is_null($this->_instance_id_column)) { + return $this->_instance_id_column; + } + if (isset(self::$_config['id_column_overrides'][$this->_table_name])) { + return self::$_config['id_column_overrides'][$this->_table_name]; + } else { + return self::$_config['id_column']; + } + } + + /** + * Get the primary key ID of this object. + */ + public function id() + { + return $this->get($this->_get_id_column_name()); + } + + /** + * Set a property to a particular value on this object. + * Flags that property as 'dirty' so it will be saved to the + * database when save() is called. + */ + public function set($key, $value) + { + $this->_data[$key] = $value; + $this->_dirty_fields[$key] = $value; + } + + /** + * Check whether the given field has been changed since this + * object was saved. + */ + public function is_dirty($key) + { + return isset($this->_dirty_fields[$key]); + } + + /** + * Save any fields which have been modified on this object + * to the database. + */ + public function save() + { + $query = array(); + $values = array_values($this->_dirty_fields); + + if (!$this->_is_new) { // UPDATE + // If there are no dirty values, do nothing + if (count($values) == 0) { + return true; + } + $query = $this->_build_update(); + $values[] = $this->id(); + } else { // INSERT + $query = $this->_build_insert(); + } + + self::_log_query($query, $values); + $statement = self::$_db->prepare($query); + $success = $statement->execute($values); + + // If we've just inserted a new record, set the ID of this object + if ($this->_is_new) { + $this->_is_new = false; + if (is_null($this->id())) { + $this->_data[$this->_get_id_column_name()] = self::$_db->lastInsertId(); + } + } + + $this->_dirty_fields = array(); + + return $success; + } + + /** + * Build an UPDATE query + */ + protected function _build_update() + { + $query = array(); + $query[] = "UPDATE {$this->_quote_identifier($this->_table_name)} SET"; + + $field_list = array(); + foreach ($this->_dirty_fields as $key => $value) { + $field_list[] = "{$this->_quote_identifier($key)} = ?"; + } + $query[] = join(", ", $field_list); + $query[] = "WHERE"; + $query[] = $this->_quote_identifier($this->_get_id_column_name()); + $query[] = "= ?"; + + return join(" ", $query); + } + + /** + * Build an INSERT query + */ + protected function _build_insert() + { + $query[] = "INSERT INTO"; + $query[] = $this->_quote_identifier($this->_table_name); + $field_list = array_map(array($this, '_quote_identifier'), array_keys($this->_dirty_fields)); + $query[] = "(" . join(", ", $field_list) . ")"; + $query[] = "VALUES"; + + $placeholders = $this->_create_placeholders(count($this->_dirty_fields)); + $query[] = "({$placeholders})"; + + return join(" ", $query); + } + + /** + * Delete this record from the database + */ + public function delete() + { + $query = join(" ", array( + "DELETE FROM", + $this->_quote_identifier($this->_table_name), + "WHERE", + $this->_quote_identifier($this->_get_id_column_name()), + "= ?", + )); + $params = array($this->id()); + self::_log_query($query, $params); + $statement = self::$_db->prepare($query); + + return $statement->execute($params); + } + + // --------------------- // + // --- MAGIC METHODS --- // + // --------------------- // + public function __get($key) + { + return $this->get($key); + } + + public function __set($key, $value) + { + $this->set($key, $value); + } + + public function __isset($key) + { + return isset($this->_data[$key]); + } +} diff --git a/libraries/monstra/Request.php b/libraries/monstra/Request.php new file mode 100644 index 0000000..d7083d5 --- /dev/null +++ b/libraries/monstra/Request.php @@ -0,0 +1,153 @@ + + * Request::redirect('test'); + * + * + * @param string $url The URL + * @param integer $status Status + * @param integer $delay Delay + */ + public static function redirect($url, $status = 302, $delay = null) + { + // Redefine vars + $url = (string) $url; + $status = (int) $status; + + // Status codes + $messages = array(); + $messages[301] = '301 Moved Permanently'; + $messages[302] = '302 Found'; + + // Is Headers sent ? + if (headers_sent()) { + + echo "\n"; + + } else { + + // Redirect headers + Request::setHeaders('HTTP/1.1 ' . $status . ' ' . Arr::get($messages, $status, 302)); + + // Delay execution + if ($delay !== null) sleep((int) $delay); + + // Redirect + Request::setHeaders("Location: $url"); + + // Shutdown request + Request::shutdown(); + + } + + } + + /** + * Set one or multiple headers. + * + * + * Request::setHeaders('Location: http://site.com/'); + * + * + * @param mixed $headers String or array with headers to send. + */ + public static function setHeaders($headers) + { + // Loop elements + foreach ((array) $headers as $header) { + + // Set header + header((string) $header); + + } + + } + + /** + * Get + * + * + * $action = Request::get('action'); + * + * + * @param string $key Key + * @param mixed + */ + public static function get($key) + { + return Arr::get($_GET, $key); + } + + /** + * Post + * + * + * $login = Request::post('login'); + * + * + * @param string $key Key + * @param mixed + */ + public static function post($key) + { + return Arr::get($_POST, $key); + } + + /** + * Returns whether this is an ajax request or not + * + * + * if (Request::isAjax()) { + * // do something... + * } + * + * + * @return boolean + */ + public static function isAjax() + { + return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'; + } + + /** + * Terminate request + * + * + * Request::shutdown(); + * + * + */ + public static function shutdown() + { + exit(0); + } + +} diff --git a/libraries/monstra/Response.php b/libraries/monstra/Response.php new file mode 100644 index 0000000..9b036b8 --- /dev/null +++ b/libraries/monstra/Response.php @@ -0,0 +1,101 @@ + 'Continue', + 101 => 'Switching Protocols', + + // Success 2xx + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + + // Redirection 3xx + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', // 1.1 + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + // 306 is deprecated but reserved + 307 => 'Temporary Redirect', + + // Client Error 4xx + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + + // Server Error 5xx + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 509 => 'Bandwidth Limit Exceeded' + ); + + /** + * Protected constructor since this is a static class. + * + * @access protected + */ + protected function __construct() + { + // Nothing here + } + + /** + * Set header status + * + * + * Response::status(404); + * + * + * @param integer $status Status code + */ + public static function status($status) + { + if (array_key_exists($status, Response::$messages)) header('HTTP/1.1 ' . $status . ' ' . Response::$messages[$status]); + } + +} diff --git a/libraries/monstra/Security.php b/libraries/monstra/Security.php new file mode 100644 index 0000000..164f6e4 --- /dev/null +++ b/libraries/monstra/Security.php @@ -0,0 +1,237 @@ + + * $token = Security::token(); + * + * + * You can insert this token into your forms as a hidden field: + * + * + * echo Form::hidden('csrf', Security::token()); + * + * + * This provides a basic, but effective, method of preventing CSRF attacks. + * + * @param boolean $new force a new token to be generated?. Default is false + * @return string + */ + public static function token($new = false) + { + // Get the current token + $token = Session::get(Security::$token_name); + + // Create a new unique token + if ($new === true or ! $token) { + + // Generate a new unique token + $token = sha1(uniqid(mt_rand(), true)); + + // Store the new token + Session::set(Security::$token_name, $token); + } + + // Return token + return $token; + } + + /** + * Check that the given token matches the currently stored security token. + * + * + * if (Security::check($token)) { + * // Pass + * } + * + * + * @param string $token token to check + * @return boolean + */ + public static function check($token) + { + return Security::token() === $token; + } + + /** + * Encrypt password + * + * + * $encrypt_password = Security::encryptPassword('password'); + * + * + * @param string $password Password to encrypt + */ + public static function encryptPassword($password) + { + return md5(md5(trim($password) . MONSTRA_PASSWORD_SALT)); + } + + /** + * Create safe name. Use to create safe username, filename, pagename. + * + * + * $safe_name = Security::safeName('hello world'); + * + * + * @param string $str String + * @param string $delimiter String delimiter + * @param boolean $lowercase String Lowercase + * @return string + */ + public static function safeName($str, $delimiter = '-', $lowercase = false) + { + // Redefine vars + $str = (string) $str; + $delimiter = (string) $delimiter; + $lowercase = (bool) $lowercase; + $delimiter = (string) $delimiter; + + // Remove tags + $str = filter_var($str, FILTER_SANITIZE_STRING); + + // Decode all entities to their simpler forms + $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8'); + + // Reserved characters (RFC 3986) + $reserved_characters = array( + '/', '?', ':', '@', '#', '[', ']', + '!', '$', '&', '\'', '(', ')', '*', + '+', ',', ';', '=' + ); + + // Remove reserved characters + $str = str_replace($reserved_characters, ' ', $str); + + // Set locale to en_US.UTF8 + setlocale(LC_ALL, 'en_US.UTF8'); + + // Translit ua,ru => latin + $str = Text::translitIt($str); + + // Convert string + $str = iconv('UTF-8', 'ASCII//TRANSLIT', $str); + + // Remove characters + $str = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str ); + $str = preg_replace("/[\/_|+ -]+/", $delimiter, $str ); + $str = trim($str, $delimiter); + + // Lowercase + if ($lowercase === true) $str = Text::lowercase($str); + + // Return safe name + return $str; + } + + /** + * Create safe url. + * + * + * $url = Security::sanitizeURL('http://test.com'); + * + * + * @param string $url Url to sanitize + * @return string + */ + public static function sanitizeURL($url) + { + $url = trim($url); + $url = rawurldecode($url); + $url = str_replace(array('--','"','!','@','#','$','%','^','*','(',')','+','{','}','|',':','"','<','>', + '[',']','\\',';',"'",',','*','+','~','`','laquo','raquo',']>','‘','’','“','”','–','—'), + array('-','-','','','','','','','','','','','','','','','','','','','','','','','','','','',''), + $url); + $url = str_replace('--', '-', $url); + $url = rtrim($url, "-"); + + $url = str_replace('..', '', $url); + $url = str_replace('//', '', $url); + $url = preg_replace('/^\//', '', $url); + $url = preg_replace('/^\./', '', $url); + + return $url; + } + + /** + * Sanitize URL to prevent XSS - Cross-site scripting + */ + public static function runSanitizeURL() + { + $_GET = array_map('Security::sanitizeURL', $_GET); + } + + /** + * That prevents null characters between ascii characters. + * + * @param string $str String + */ + public static function removeInvisibleCharacters($str) + { + // Redefine vars + $str = (string) $str; + + // Thanks to ci for this tip :) + $non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/'); + + do { + $cleaned = $str; + $str = preg_replace($non_displayables, '', $str); + } while ($cleaned != $str); + + // Return safe string + return $str; + } + + /** + * Sanitize data to prevent XSS - Cross-site scripting + * + * @param string $str String + */ + public static function xssClean($str) + { + // Remove invisible characters + $str = Security::removeInvisibleCharacters($str); + + // Convert html to plain text + $str = Html::toText($str); + + // Return safe string + return $str; + } + +} diff --git a/libraries/monstra/Session.php b/libraries/monstra/Session.php new file mode 100644 index 0000000..27f566c --- /dev/null +++ b/libraries/monstra/Session.php @@ -0,0 +1,187 @@ + + * Session::start(); + * + * + */ + public static function start() + { + // Is session already started? + if ( ! session_id()) { + + // Start the session + return @session_start(); + } + + // If already started + return true; + } + + /** + * Deletes one or more session variables. + * + * + * Session::delete('user'); + * + * + */ + public static function delete() + { + // Loop all arguments + foreach (func_get_args() as $argument) { + + // Array element + if (is_array($argument)) { + + // Loop the keys + foreach ($argument as $key) { + + // Unset session key + unset($_SESSION[(string) $key]); + } + } else { + + // Remove from array + unset($_SESSION[(string) $argument]); + } + } + } + + /** + * Destroys the session. + * + * + * Session::destroy(); + * + * + */ + public static function destroy() + { + // Destroy + if (session_id()) { + session_unset(); + session_destroy(); + $_SESSION = array(); + } + + } + + /** + * Checks if a session variable exists. + * + * + * if (Session::exists('user')) { + * // Do something... + * } + * + * + * @return boolean + */ + public static function exists() + { + // Start session if needed + if ( ! session_id()) Session::start(); + + // Loop all arguments + foreach (func_get_args() as $argument) { + + // Array element + if (is_array($argument)) { + + // Loop the keys + foreach ($argument as $key) { + + // Does NOT exist + if ( ! isset($_SESSION[(string) $key])) return false; + } + } else { + + // Does NOT exist + if ( ! isset($_SESSION[(string) $argument])) return false; + } + } + + return true; + } + + /** + * Gets a variable that was stored in the session. + * + * + * echo Session::get('user'); + * + * + * @param string $key The key of the variable to get. + * @return mixed + */ + public static function get($key) + { + // Start session if needed + if ( ! session_id()) self::start(); + + // Redefine key + $key = (string) $key; + + // Fetch key + if (Session::exists((string) $key)) return $_SESSION[(string) $key]; + + // Key doesn't exist + return null; + } + + + /** + * Returns the sessionID. + * + * + * echo Session::getSessionId(); + * + * + * @return string + */ + public static function getSessionId() + { + if ( ! session_id()) Session::start(); + return session_id(); + } + + + /** + * Stores a variable in the session. + * + * + * Session::set('user', 'Awilum'); + * + * + * @param string $key The key for the variable. + * @param mixed $value The value to store. + */ + public static function set($key, $value) + { + // Start session if needed + if ( ! session_id()) self::start(); + + // Set key + $_SESSION[(string) $key] = $value; + } + +} diff --git a/libraries/monstra/Text.php b/libraries/monstra/Text.php new file mode 100644 index 0000000..d7adf2d --- /dev/null +++ b/libraries/monstra/Text.php @@ -0,0 +1,475 @@ + latin + * + * + * echo Text::translitIt('Привет'); + * + * + * @param string $str [ua,ru] string + * @return string $str + */ + public static function translitIt($str) + { + // Redefine vars + $str = (string) $str; + + $patern = array( + "А" => "A", "Б" => "B", "В" => "V", "Г" => "G", + "Д" => "D", "Е" => "E", "Ж" => "J", "З" => "Z", + "И" => "I", "Й" => "Y", "К" => "K", "Л" => "L", + "М" => "M", "Н" => "N", "О" => "O", "П" => "P", + "Р" => "R", "С" => "S", "Т" => "T", "У" => "U", + "Ф" => "F", "Х" => "H", "Ц" => "TS", "Ч" => "CH", + "Ш" => "SH", "Щ" => "SCH", "Ъ" => "", "Ы" => "YI", + "Ь" => "", "Э" => "E", "Ю" => "YU", "Я" => "YA", + "а" => "a", "б" => "b", "в" => "v", "г" => "g", + "д" => "d", "е" => "e", "ж" => "j", "з" => "z", + "и" => "i", "й" => "y", "к" => "k", "л" => "l", + "м" => "m", "н" => "n", "о" => "o","п" => "p", + "р" => "r", "с" => "s", "т" => "t", "у" => "u", + "ф" => "f", "х" => "h", "ц" => "ts", "ч" => "ch", + "ш" => "sh", "щ" => "sch", "ъ" => "y", "ї" => "i", + "Ї" => "Yi", "є" => "ie", "Є" => "Ye", "ы" => "yi", + "ь" => "", "э" => "e", "ю" => "yu", "я" => "ya", "ё" => "yo" + ); + + return strtr($str, $patern); + } + + /** + * Removes any leading and traling slashes from a string + * + * + * echo Text::trimSlashes('some text here/'); + * + * + * @param string $str String with slashes + * @return string + */ + public static function trimSlashes($str) + { + // Redefine vars + $str = (string) $str; + + return trim($str, '/'); + } + + /** + * Removes slashes contained in a string or in an array + * + * + * echo Text::strpSlashes('some \ text \ here'); + * + * + * @param 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 + * + * + * echo Text::stripQuotes('some "text" here'); + * + * + * @param string $str String with single and double quotes + * @return string + */ + public static function stripQuotes($str) + { + // Redefine vars + $str = (string) $str; + + return str_replace(array('"', "'"), '', $str); + } + + /** + * Convert single and double quotes to entities + * + * + * echo Text::quotesToEntities('some "text" here'); + * + * + * @param string $str String with single and double quotes + * @return string + */ + public static function quotesToEntities($str) + { + // Redefine vars + $str = (string) $str; + + return str_replace(array("\'", "\"", "'", '"'), array("'", """, "'", """), $str); + } + + /** + * Creates a random string of characters + * + * + * echo Text::random(); + * + * + * @param string $type The type of string. Default is 'alnum' + * @param integer $length The number of characters. Default is 16 + * @return string + */ + public static function random($type = 'alnum', $length = 16) + { + // Redefine vars + $type = (string) $type; + $length = (int) $length; + + switch ($type) { + + case 'basic': + return mt_rand(); + break; + + default: + case 'alnum': + case 'numeric': + case 'nozero': + case 'alpha': + case 'distinct': + case 'hexdec': + switch ($type) { + case 'alpha': + $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + + default: + case 'alnum': + $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + + case 'numeric': + $pool = '0123456789'; + break; + + case 'nozero': + $pool = '123456789'; + break; + + case 'distinct': + $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; + break; + + case 'hexdec': + $pool = '0123456789abcdef'; + break; + } + + $str = ''; + for ($i=0; $i < $length; $i++) { + $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); + } + + return $str; + break; + + case 'unique': + return md5(uniqid(mt_rand())); + break; + + case 'sha1' : + return sha1(uniqid(mt_rand(), true)); + break; + } + } + + /** + * Add's _1 to a string or increment the ending number to allow _2, _3, etc + * + * + * $str = Text::increment($str); + * + * + * @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 + * + * + * echo Text::cut('Some text here', 5); + * + * + * @param string $str Input string + * @param integer $length Length after cut + * @param string $cut_msg Message after cut string + * @return string + */ + public static function cut($str, $length, $cut_msg = null) + { + // Redefine vars + $str = (string) $str; + $length = (int) $length; + + if (isset($cut_msg)) $msg = $cut_msg; else $msg = '...'; + return function_exists('mb_substr') ? mb_substr($str, 0, $length, 'utf-8') . $msg : substr($str, 0, $length) . $msg; + } + + + /** + * Lowercase + * + * + * echo Text::lowercase('Some text here'); + * + * + * @param string $str String + * @return string + */ + public static function lowercase($str) + { + // Redefine vars + $str = (string) $str; + + return function_exists('mb_strtolower') ? mb_strtolower($str, 'utf-8') : strtolower($str); + } + + + /** + * Uppercase + * + * + * echo Text::uppercase('some text here'); + * + * + * @param string $str String + * @return string + */ + public static function uppercase($str) + { + // Redefine vars + $str = (string) $str; + + return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'utf-8') : strtoupper($str); + } + + + /** + * Get length + * + * + * echo Text::length('Some text here'); + * + * + * @param string $str String + * @return string + */ + public static function length($str) + { + // Redefine vars + $str = (string) $str; + + return function_exists('mb_strlen') ? mb_strlen($str, 'utf-8') : strlen($str); + } + + + /** + * Create a lorem ipsum text + * + * + * echo Text::lorem(2); + * + * + * @param integer $num Count + * @return string + */ + public static function lorem($num = 1) + { + // Redefine vars + $num = (int) $num; + + return str_repeat('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', (int) $num); + } + + + /** + * Extract the last `$num` characters from a string. + * + * + * echo Text::right('Some text here', 4); + * + * + * @param string $str The string to extract the characters from. + * @param integer $num The number of characters to extract. + * @return string + */ + public static function right($str, $num) + { + // Redefine vars + $str = (string) $str; + $num = (int) $num; + + return substr($str, Text::length($str)-$num, $num); + } + + + /** + * Extract the first `$num` characters from a string. + * + * + * echo Text::left('Some text here', 4); + * + * + * @param string $str The string to extract the characters from. + * @param integer $num The number of characters to extract. + * @return string + */ + public static function left($str, $num) + { + // Redefine vars + $str = (string) $str; + $num = (int) $num; + + return substr($str, 0, $num); + } + + + /** + * Replaces newline with
    or
    . + * + * + * echo Text::nl2br("Some \n text \n here"); + * + * + * @param string $str The input string + * @param boolean $xhtml Xhtml or not + * @return string + */ + public static function nl2br($str, $xhtml = true) + { + // Redefine vars + $str = (string) $str; + $xhtml = (bool) $xhtml; + + return str_replace(array("\r\n", "\n\r", "\n", "\r"), (($xhtml) ? '
    ' : '
    '), $str); + } + + + /** + * Replaces
    and
    with newline. + * + * + * echo Text::br2nl("Some
    text
    here"); + *
    + * + * @param string $str The input string + * @return string + */ + public static function br2nl($str) + { + // Redefine vars + $str = (string) $str; + + return str_replace(array('
    ', '
    ', '
    '), "\n", $str); + } + + + /** + * Converts & to &. + * + * + * echo Text::ampEncode("M&CMS"); + * + * + * @param string $str The input string + * @return string + */ + public static function ampEncode($str) + { + // Redefine vars + $str = (string) $str; + + return str_replace('&', '&', $str); + } + + + /** + * Converts & to &. + * + * + * echo Text::ampEncode("M&CMS"); + * + * + * @param string $str The input string + * @return string + */ + public static function ampDecode($str) + { + // Redefine vars + $str = (string) $str; + + return str_replace('&', '&', $str); + } + + + /** + * Convert plain text to html + * + * + * echo Text::toHtml('test'); + * + * + * @param string $str String + * @return string + */ + public static function toHtml($str) + { + // Redefine vars + $str = (string) $str; + + return html_entity_decode($str, ENT_QUOTES, 'utf-8'); + } + +} diff --git a/libraries/monstra/Url.php b/libraries/monstra/Url.php new file mode 100644 index 0000000..3013fee --- /dev/null +++ b/libraries/monstra/Url.php @@ -0,0 +1,107 @@ + + * echo Url::tiny('http:://sitename.com'); + * + * + * @param string $url Long url + * @return string + */ + public static function tiny($url) + { + return file_get_contents('http://tinyurl.com/api-create.php?url='.(string) $url); + } + + /** + * Check is url exists + * + * + * if (Url::exists('http:://sitename.com')) { + * // Do something... + * } + * + * + * @param string $url Url + * @return boolean + */ + public static function exists($url) + { + $a_url = parse_url($url); + if ( ! isset($a_url['port'])) $a_url['port'] = 80; + $errno = 0; + $errstr = ''; + $timeout = 30; + if (isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])) { + $fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout); + if ( ! $fid) return false; + $page = isset($a_url['path']) ? $a_url['path'] : ''; + $page .= isset($a_url['query']) ? '?'.$a_url['query'] : ''; + fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n"); + $head = fread($fid, 4096); + fclose($fid); + + return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head); + } else { + return false; + } + } + + /** + * Gets the base URL + * + * + * echo Url::base(); + * + * + * @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 + * + * + * echo Url::current(); + * + * + * @return string + */ + public static function current() + { + return (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; + } + +} diff --git a/libraries/monstra/Valid.php b/libraries/monstra/Valid.php new file mode 100644 index 0000000..773fb60 --- /dev/null +++ b/libraries/monstra/Valid.php @@ -0,0 +1,207 @@ + + * if (Valid::email('test@test.com')) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Valid::ip('127.0.0.1') || Valid::ip('0:0:0:0:0:0:7f00:1')) { + * // Do something... + * } + * + * + * @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. + * + * + * if (Valid::creditCard(7711111111111111, 'Visa')) { + * // Do something... + * } + * + * + * @param integer $num Credit card num + * @param string $type Credit card type: + * American - American Express + * Dinners - Diner's Club + * Discover - Discover Card + * Master - Mastercard + * Visa - Visa + * @return boolean + */ + public static function creditCard($num, $type) + { + // Redefine vars + $num = (int) $num; + $type = (string) $type; + + switch ($type) { + case "American": return (bool) preg_match("/^([34|37]{2})([0-9]{13})$/", $num); + case "Dinners": return (bool) preg_match("/^([30|36|38]{2})([0-9]{12})$/", $num); + case "Discover": return (bool) preg_match("/^([6011]{4})([0-9]{12})$/", $num); + case "Master": return (bool) preg_match("/^([51|52|53|54|55]{2})([0-9]{14})$/", $num); + case "Visa": return (bool) preg_match("/^([4]{1})([0-9]{12,15})$/", $num); + } + } + + + /** + * Check an phone number for correct format. + * + * + * if (Valid::phone(0661111117)) { + * // Do something... + * } + * + * + * @param string $num Phone number + * @return boolean + */ + public static function phone($num) + { + return (bool) preg_match("/^([0-9\(\)\/\+ \-]*)$/", (string) $num); + } + + + /** + * Check an url for correct format. + * + * + * if (Valid::url('http://site.com/')) { + * // Do something... + * } + * + * + * @param string $url Url + * @return boolean + */ + public static function url($url) + { + return (bool) filter_var((string) $url, FILTER_VALIDATE_URL); + } + + + /** + * Check an date for correct format. + * + * + * if (Valid::date('12/12/12')) { + * // Do something... + * } + * + * + * @param string $str Date + * @return boolean + */ + public static function date($str) + { + return (strtotime($str) !== false); + } + + + /** + * Checks whether a string consists of digits only (no dots or dashes). + * + * + * if (Valid::digit('12')) { + * // Do something... + * } + * + * + * @param string $str String + * @return boolean + */ + public static function digit($str) + { + return (bool) preg_match ("/[^0-9]/", $str); + } + + + /** + * Checks whether a string is a valid number (negative and decimal numbers allowed). + * + * + * if (Valid::numeric('3.14')) { + * // Do something... + * } + * + * + * Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion} + * to allow decimal point to be locale specific. + * + * @param string $str String + * @return boolean + */ + public static function numeric($str) + { + $locale = localeconv(); + + return (bool) preg_match('/^-?[0-9'.$locale['decimal_point'].']++$/D', (string) $str); + } + + + /** + * Checks if the given regex statement is valid. + * + * @param string $regexp The value to validate. + * @return boolean + */ + public static function regexp($regexp) + { + // dummy string + $dummy = 'Monstra - fast and simple PHP library'; + + // validate + return (@preg_match((string) $regexp, $dummy) !== false); + + } + +} diff --git a/libraries/monstra/Zip.php b/libraries/monstra/Zip.php new file mode 100644 index 0000000..385fc27 --- /dev/null +++ b/libraries/monstra/Zip.php @@ -0,0 +1,373 @@ +now = time(); + } + + /** + * Zip factory + * + * + * Zip::factory(); + * + * + * @return Zip + */ + public static function factory() + { + return new Zip(); + } + + /** + * Add Directory + * + * + * Zip::factory()->addDir('test'); + * + * + * @param mixed $directory The directory name. Can be string or array + */ + public function addDir($directory) + { + foreach ((array) $directory as $dir) { + + if ( ! preg_match("|.+/$|", $dir)) { + $dir .= '/'; + } + + $dir_time = $this->_get_mod_time($dir); + + $this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']); + } + + return $this; + } + + /** + * Get file/directory modification time + * + * @param string $dir Full path to the dir + * @return array + */ + protected function _get_mod_time($dir) + { + // If this is a newly created file/dir, we will set the time to 'now' + $date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now); + + $time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2; + $time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday']; + + return $time; + } + + /** + * Add Directory + * + * @param string $dir The directory name + * @param integer $file_mtime File mtime + * @param integer $file_mdate File mdate + */ + private function _add_dir($dir, $file_mtime, $file_mdate) + { + $dir = str_replace("\\", "/", $dir); + + $this->zipdata .= + "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00" + .pack('v', $file_mtime) + .pack('v', $file_mdate) + .pack('V', 0) // crc32 + .pack('V', 0) // compressed filesize + .pack('V', 0) // uncompressed filesize + .pack('v', strlen($dir)) // length of pathname + .pack('v', 0) // extra field length + .$dir + // below is "data descriptor" segment + .pack('V', 0) // crc32 + .pack('V', 0) // compressed filesize + .pack('V', 0); // uncompressed filesize + + $this->directory .= + "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00" + .pack('v', $file_mtime) + .pack('v', $file_mdate) + .pack('V',0) // crc32 + .pack('V',0) // compressed filesize + .pack('V',0) // uncompressed filesize + .pack('v', strlen($dir)) // length of pathname + .pack('v', 0) // extra field length + .pack('v', 0) // file comment length + .pack('v', 0) // disk number start + .pack('v', 0) // internal file attributes + .pack('V', 16) // external file attributes - 'directory' bit set + .pack('V', $this->offset) // relative offset of local header + .$dir; + + $this->offset = strlen($this->zipdata); + $this->entries++; + } + + /** + * Add Data to Zip + * + * + * Zip::factory()->addData('test.txt', 'Some test text here'); + * + * + * Lets you add files to the archive. If the path is included + * in the filename it will be placed within a directory. Make + * sure you use add_dir() first to create the folder. + * + * @param mixed $filepath Full path to the file + * @param string $data Data + */ + public function addData($filepath, $data = null) + { + if (is_array($filepath)) { + foreach ($filepath as $path => $data) { + $file_data = $this->_get_mod_time($path); + $this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']); + } + } else { + $file_data = $this->_get_mod_time($filepath); + $this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']); + } + + return $this; + } + + /** + * Add Data to Zip + * + * @param string $filepath Full path to the file + * @param string $data The data to be encoded + * @param integer $file_mtime File mtime + * @param integer $file_mdate File mdate + */ + private function _add_data($filepath, $data, $file_mtime, $file_mdate) + { + $filepath = str_replace("\\", "/", $filepath); + + $uncompressed_size = strlen($data); + $crc32 = crc32($data); + + $gzdata = gzcompress($data); + $gzdata = substr($gzdata, 2, -4); + $compressed_size = strlen($gzdata); + + $this->zipdata .= + "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00" + .pack('v', $file_mtime) + .pack('v', $file_mdate) + .pack('V', $crc32) + .pack('V', $compressed_size) + .pack('V', $uncompressed_size) + .pack('v', strlen($filepath)) // length of filename + .pack('v', 0) // extra field length + .$filepath + .$gzdata; // "file data" segment + + $this->directory .= + "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00" + .pack('v', $file_mtime) + .pack('v', $file_mdate) + .pack('V', $crc32) + .pack('V', $compressed_size) + .pack('V', $uncompressed_size) + .pack('v', strlen($filepath)) // length of filename + .pack('v', 0) // extra field length + .pack('v', 0) // file comment length + .pack('v', 0) // disk number start + .pack('v', 0) // internal file attributes + .pack('V', 32) // external file attributes - 'archive' bit set + .pack('V', $this->offset) // relative offset of local header + .$filepath; + + $this->offset = strlen($this->zipdata); + $this->entries++; + $this->file_num++; + } + + /** + * Read the contents of a file and add it to the zip + * + * + * Zip::factory()->readFile('test.txt'); + * + * + * @param string $path Path + * @param boolean $preserve_filepath Preserve filepath + * @return mixed + */ + 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. + * + * + * Zip::factory()->readDir('test/'); + * + * + * This function recursively reads a folder and everything it contains (including + * sub-folders) and creates a zip based on it. Whatever directory structure + * is in the original file path will be recreated in the zip file. + * + * @param string $path Path to source + * @param boolean $preserve_filepath Preserve filepath + * @param string $root_path Root path + * @return mixed + */ + public function readDir($path, $preserve_filepath = true, $root_path = null) + { + if ( ! $fp = @opendir($path)) { + return false; + } + + // Set the original directory root for child dir's to use as relative + if ($root_path === null) { + $root_path = dirname($path) . '/'; + } + + while (false !== ($file = readdir($fp))) { + + if (substr($file, 0, 1) == '.') { + continue; + } + + if (@is_dir($path.$file)) { + $this->readDir($path.$file."/", $preserve_filepath, $root_path); + } else { + if (false !== ($data = file_get_contents($path.$file))) { + $name = str_replace("\\", "/", $path); + + if ($preserve_filepath === false) { + $name = str_replace($root_path, '', $name); + } + + $this->addData($name.$file, $data); + } + } + } + + return $this; + } + + + /** + * Get the Zip file + * + * + * Zip::factory()->getZip(); + * + * + * @return string + */ + public function getZip() + { + // Is there any data to return? + if ($this->entries == 0) { + return false; + } + + $zip_data = $this->zipdata; + $zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00"; + $zip_data .= pack('v', $this->entries); // total # of entries "on this disk" + $zip_data .= pack('v', $this->entries); // total # of entries overall + $zip_data .= pack('V', strlen($this->directory)); // size of central dir + $zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir + $zip_data .= "\x00\x00"; // .zip file comment length + + return $zip_data; + } + + + /** + * Write File to the specified directory + * + * + * Zip::factory()->readDir('test1/')->readDir('test2/')->archive('test.zip'); + * + * + * @param string $filepath The file name + * @return boolean + */ + public function archive($filepath) + { + if ( ! ($fp = @fopen($filepath, "w"))) { + return false; + } + + flock($fp, LOCK_EX); + fwrite($fp, $this->getZip()); + flock($fp, LOCK_UN); + fclose($fp); + + return true; + } + + + /** + * Initialize Data + * + * + * Zip::factory()->clearData(); + * + * + * Lets you clear current zip data. Useful if you need to create + * multiple zips with different data. + */ + public function clearData() + { + $this->zipdata = ''; + $this->directory = ''; + $this->entries = 0; + $this->file_num = 0; + $this->offset = 0; + } + +} diff --git a/monstra/boot/actions.php b/monstra/boot/actions.php deleted file mode 100644 index f8d5ec7..0000000 --- a/monstra/boot/actions.php +++ /dev/null @@ -1,7 +0,0 @@ -'; } diff --git a/monstra/boot/defines.php b/monstra/boot/defines.php deleted file mode 100644 index 498a4ee..0000000 --- a/monstra/boot/defines.php +++ /dev/null @@ -1,117 +0,0 @@ - 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); - - // Cleanup cache - if (count($namespaces = Dir::scan(CACHE)) > 0) foreach ($namespaces as $namespace) Dir::delete(CACHE . DS . $namespace); - } - - // Load XMLDB API module - require_once(ENGINE . DS . 'xmldb.php'); - - // Load Options API module - require_once(ENGINE . DS . 'options.php'); - - // Init Options API module - Option::init(); - - // Set default timezone - @ini_set('date.timezone', Option::get('timezone')); - if (function_exists('date_default_timezone_set')) date_default_timezone_set(Option::get('timezone')); else putenv('TZ='.Option::get('timezone')); - - // Sanitize URL to prevent XSS - Cross-site scripting - Security::runSanitizeURL(); - - // Load Plugins API module - require_once(ENGINE . DS . 'plugins.php'); - - // Load Shortcodes API module - require_once(ENGINE . DS . 'shortcodes.php'); - - // Load default - Core::loadPluggable(); - - // Init I18n - I18n::init(Option::get('language')); - - // Init Plugins API - Plugin::init(); - - // Init Notification service - Notification::init(); - - // Load Site module - require_once(ENGINE . DS . 'site.php'); - - // Init site module - if( ! BACKEND) Site::init(); - - } - - - /** - * Autoload helpers - * - * @param string $class_name Class name - */ - protected static function autoloadHelpers($class_name) { - if (file_exists($path = HELPERS . DS . strtolower($class_name) . '.php')) include $path; - } - - - /** - * Load Defines - */ - protected static function loadDefines() { - - $environments = array(1 => 'production', - 2 => 'staging', - 3 => 'testing', - 4 => 'development'); - - $root_defines = ROOT . DS . 'boot' . DS . 'defines.php'; - $environment_defines = ROOT . DS . 'boot' . DS . $environments[Core::$environment] . DS . 'defines.php'; - $monstra_defines = ROOT . DS . 'monstra' . DS . 'boot' . DS . 'defines.php'; - - - if (file_exists($root_defines)) { - include $root_defines; - } elseif(file_exists($environment_defines)) { - include $environment_defines; - } elseif(file_exists($monstra_defines)) { - include $monstra_defines; - } else { - throw new RuntimeException("The defines file does not exist."); - } - } - - - /** - * Load Pluggable - */ - protected static function loadPluggable() { - - $environments = array(1 => 'production', - 2 => 'staging', - 3 => 'testing', - 4 => 'development'); - - $root_pluggable = ROOT . DS . 'boot'; - $environment_pluggable = ROOT . DS . 'boot' . DS . $environments[Core::$environment]; - $monstra_pluggable = ROOT . DS . 'monstra' . DS . 'boot'; - - - if (file_exists($root_pluggable . DS . 'filters.php')) { - include $root_pluggable . DS . 'filters.php'; - } elseif(file_exists($environment_pluggable . DS . 'filters.php')) { - include $environment_pluggable . DS . 'filters.php'; - } elseif(file_exists($monstra_pluggable . DS . 'filters.php')) { - include $monstra_pluggable . DS . 'filters.php'; - } else { - throw new RuntimeException("The pluggable file does not exist."); - } - - if (file_exists($root_pluggable . DS . 'actions.php')) { - include $root_pluggable . DS . 'actions.php'; - } elseif(file_exists($environment_pluggable . DS . 'actions.php')) { - include $environment_pluggable . DS . 'actions.php'; - } elseif(file_exists($monstra_pluggable . DS . 'actions.php')) { - include $monstra_pluggable . DS . 'actions.php'; - } else { - throw new RuntimeException("The pluggable file does not exist."); - } - - if (file_exists($root_pluggable . DS . 'shortcodes.php')) { - include $root_pluggable . DS . 'shortcodes.php'; - } elseif(file_exists($environment_pluggable . DS . 'shortcodes.php')) { - include $environment_pluggable . DS . 'shortcodes.php'; - } elseif(file_exists($monstra_pluggable . DS . 'shortcodes.php')) { - include $monstra_pluggable . DS . 'shortcodes.php'; - } else { - throw new RuntimeException("The pluggable file does not exist."); - } - - } - - - /** - * Exception Handler - * - * @param object $exception An exception object - */ - public static function exceptionHandler($exception) { - - // Empty output buffers - while (ob_get_level() > 0) ob_end_clean(); - - // Send headers and output - @header('Content-Type: text/html; charset=UTF-8'); - @header('HTTP/1.1 500 Internal Server Error'); - - - // Get highlighted code - $code = Core::highlightCode($exception->getFile(), $exception->getLine()); - - // Determine error type - if ($exception instanceof ErrorException) { - - $error_type = 'ErrorException: '; - - $codes = array ( - E_ERROR => 'Fatal Error', - E_PARSE => 'Parse Error', - E_COMPILE_ERROR => 'Compile Error', - E_COMPILE_WARNING => 'Compile Warning', - E_STRICT => 'Strict Mode Error', - E_NOTICE => 'Notice', - E_WARNING => 'Warning', - E_RECOVERABLE_ERROR => 'Recoverable Error', - /*E_DEPRECATED => 'Deprecated',*/ /* PHP 5.3 */ - E_USER_NOTICE => 'Notice', - E_USER_WARNING => 'Warning', - E_USER_ERROR => 'Error', - /*E_USER_DEPRECATED => 'Deprecated'*/ /* PHP 5.3 */ - ); - - $error_type .= in_array($exception->getCode(), array_keys($codes)) ? $codes[$exception->getCode()] : 'Unknown Error'; - } else { - $error_type = get_class($exception); - } - - // Show exception if core environment is DEVELOPMENT - if (Core::$environment == Core::DEVELOPMENT) { - - // Development - echo (" - - - - - Monstra - - - -
    -

    Monstra - ".$error_type."

    -

    ".$exception->getMessage()."

    -

    Location

    -

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

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

    Oops!

    -

    An unexpected error has occurred.

    -
    - - - "); - } - - // Writes message to log - @file_put_contents(LOGS . DS . gmdate('Y_m_d') . '.log', - gmdate('Y/m/d H:i:s') . ' --- ' . '['.$error_type.']' . ' --- ' . $exception->getMessage() . ' --- ' . 'Exception thrown on line '.$exception->getLine().' in '.$exception->getFile() . "\n", - FILE_APPEND); - - exit(1); - } - - - /** - * Converts errors to ErrorExceptions. - * - * @param integer $code The error code - * @param string $message The error message - * @param string $file The filename where the error occurred - * @param integer $line The line number where the error occurred - * @return boolean - */ - public static function errorHandler($code, $message, $file, $line) { - - // If isset error_reporting and $code then throw new error exception - if ((error_reporting() & $code) !== 0) { - throw new ErrorException($message, $code, 0, $file, $line); - } - - // Don't execute PHP internal error handler - return true; - } - - - - /** - * Returns an array of lines from a file. - * - * @param string $file File in which you want to highlight a line - * @param integer $line Line number to highlight - * @param integer $padding Number of padding lines - * @return array - */ - protected static function highlightCode($file, $line, $padding = 5) { - - // Is file readable ? - if ( ! is_readable($file)) { - return false; - } - - // Init vars - $lines = array(); - $current_line = 0; - - // Open file - $handle = fopen($file, 'r'); - - // Read file - while ( ! feof($handle)) { - - $current_line++; - - $temp = fgets($handle); - - if ($current_line > $line + $padding) { - break; // Exit loop after we have found what we were looking for - } - - if ($current_line >= ($line - $padding) && $current_line <= ($line + $padding)) { - - $lines[] = array ( - 'number' => str_pad($current_line, 4, ' ', STR_PAD_LEFT), - 'highlighted' => ($current_line === $line), - 'code' => Core::highlightString($temp), - ); - } - } - - // Close - fclose($handle); - - // Return lines - return $lines; - } - - - /** - * Highlight string - * - * @param string $string String - * @return string - */ - protected static function highlightString($string) { - - return str_replace(array("\n", '', '', '<?php ', '#$@r4!/*'), - array('', '', '', '', '/*'), - highlight_string(' - * Option::add('pages_limit', 10); - * Option::add(array('pages_count' => 10, 'pages_default' => 'home')); - * - * - * @param mixed $option Name of option to add. - * @param mixed $value Option value. - * @return boolean - */ - public static function add($option, $value = null) { - if (is_array($option)) { - foreach ($option as $k => $v) { - $_option = Option::$options->select('[name="'.$k.'"]', null); - if (count($_option) == 0) { - Option::$options->insert(array('name' => $k, 'value' => $v)); - } - } - } else { - $_option = Option::$options->select('[name="'.$option.'"]', null); - if (count($_option) == 0) { - return Option::$options->insert(array('name' => $option, 'value' => $value)); - } - } - } - - - /** - * Update option value - * - * - * Option::update('pages_limit', 12); - * Option::update(array('pages_count' => 10, 'pages_default' => 'home')); - * - * - * @param mixed $option Name of option to update. - * @param mixed $value Option value. - * @return boolean - */ - public static function update($option, $value = null) { - if (is_array($option)) { - foreach ($option as $k => $v) { - Option::$options->updateWhere('[name="'.$k.'"]', array('value' => $v)); - } - } else { - return Option::$options->updateWhere('[name="'.$option.'"]', array('value' => $value)); - } - } - - - /** - * Get option value - * - * - * $pages_limit = Option::get('pages_limit'); - * if ($pages_limit == '10') { - * // do something... - * } - * - * - * @param string $option Name of option to get. - * @return string - */ - public static function get($option) { - - // Redefine vars - $option = (string) $option; - - // Select specific option - $option_name = Option::$options->select('[name="'.$option.'"]', null); - - // Return specific option value - return isset($option_name['value']) ? $option_name['value'] : ''; - } - - - /** - * Delete option - * - * - * Option::delete('pages_limit'); - * - * - * @param string $option Name of option to delete. - * @return boolean - */ - public static function delete($option) { - - // Redefine vars - $option = (string) $option; - - // Delete specific option - return Option::$options->deleteWhere('[name="'.$option.'"]'); - } - - - /** - * Check if option exist - * - * - * if (Option::exists('pages_limit')) { - * // do something... - * } - * - * - * @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; - } - - } \ No newline at end of file diff --git a/monstra/engine/plugins.php b/monstra/engine/plugins.php deleted file mode 100644 index c97ead2..0000000 --- a/monstra/engine/plugins.php +++ /dev/null @@ -1,1260 +0,0 @@ -select(null, 'all', null, array('location', 'frontend', 'backend', 'status', 'priority'), 'priority', 'ASC'); - - // Now include plugins from $records plugins array - // If plugin is active then load it to the system. - foreach ($records as $record) { - if ($record['status'] == 'active') { - include_once ROOT . DS . $record['location']; - } - } - } - - - /** - * Get plugin admin - * - * - * // Get admin for Blog plugin - * Plugin::admin('blog'); - * - * - * @param string $plug Plugin Name - * @param string $alt_folder Alternative plugin folder - */ - public static function admin($plug, $alt_folder = null) { - - // Redefine arguments - $plug = (string) $plug; - - // Plugin admin extension - $ext = '.admin.php'; - - // Plugin admin can be loaded only in backend - if (BACKEND) { - - // Plugin admin folder - if ( ! empty($alt_folder)) { - $folder = $alt_folder . DS . strtolower($plug); - } else { - $folder = strtolower($plug); - } - - // Path to plugin admin file - $path = PLUGINS . DS . $folder . DS . $plug . $ext; - - // Load plugin admin - if (File::exists($path)) { - include $path; - } - } - } - - - - /** - * Register new plugin in system - * - * - * // Register plugin - * Plugin::register( __FILE__, - * __('Blog'), - * __('Blog plugin'), - * '1.0.0', - * 'Awilum', - * 'http://example.org/', - * 'blog'); - * - * - * @param string $file Plugin file - * @param string $title Plugin title - * @param string $description Plugin description - * @param string $version Plugin version - * @param string $author Plugin author - * @param string $author_uri Plugin author uri - * @param string $component Plugin as component - * @param boolean $box Plugin as box - */ - public static function register($file, $title, $description = null, $version = null, $author = null, $author_uri = null, $component = null, $box = false) { - - // Redefine arguments - $file = (string) $file; - $title = (string) $title; - $description = ($description === null) ? null : (string) $description; - $version = ($version === null) ? null : (string) $version; - $author = ($author === null) ? null : (string) $author; - $author_uri = ($author_uri === null) ? null : (string) $author_uri; - $component = ($component === null) ? null : (string) $component; - $box = (bool) $box; - - - // Get plugin id from name.plugin.php - $id = strtolower(basename($file, '.plugin.php')); - - // Set plugin privilege 'box' if $box is true - if ($box) $privilege = 'box'; else $privilege = ''; - - // Register plugin in global plugins array. - Plugin::$plugins[$id] = array( - 'id' => $id, - 'title' => $title, - 'privilege' => $privilege, - 'version' => $version, - 'description' => $description, - 'author' => $author, - 'author_uri' => $author_uri, - ); - - // Add plugin as a component - // Plugin - component will be available at the link sitename/component_name - // Example: - // www.example.org/guestbook - // www.example.org/news - if ( ! empty($component)) { - Plugin::$components[] = $component; - } - } - - } - - - /** - * Frontend class - */ - class Frontend { - - public static function main() { } - public static function title() { return ''; } - public static function description() { return ''; } - public static function keywords() { return ''; } - public static function template() { return 'index'; } - public static function content() { return ''; } - - } - - - /** - * Backend class - */ - class Backend { - - public static function main() { } - - } - - - /** - * View class - */ - class View { - - - /** - * Path to view file. - * - * @var string - */ - protected $view_file; - - - /** - * View variables. - * - * @var array - */ - protected $vars = array(); - - - /** - * Global view variables. - * - * @var array - */ - protected static $global_vars = array(); - - - /** - * The output. - * - * @var string - */ - protected $output; - - - /** - * Create a new view object. - * - * - * // Create new view object - * $view = new View('blog/views/backend/index'); - * - * // Assign some new variables - * $view->assign('msg', 'Some message...'); - * - * // Get view - * $output = $view->render(); - * - * // Display view - * echo $output; - * - * - * @param string $view Name of the view file - * @param array $variables Array of view variables - */ - public function __construct($view, array $variables = array()) { - - // Set view file - // 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 - * - * - * // Create new view object, assign some variables - * // and displays the rendered view in the browser. - * View::factory('blog/views/backend/index') - * ->assign('msg', 'Some message...') - * ->display(); - * - * - * @param string $view Name of the view file - * @param array $variables Array of view variables - * @return View - */ - public static function factory($view, array $variables = array()) { - return new View($view, $variables); - } - - - /** - * Assign a view variable. - * - * - * $view->assign('msg', 'Some message...'); - * - * - * @param string $key Variable name - * @param mixed $value Variable value - * @param boolean $global Set variable available in all views - * @return View - */ - public function assign($key, $value, $global = false) { - - // Assign a new view variable (global or locale) - if ($global === false) { - $this->vars[$key] = $value; - } else { - View::$global_vars[$key] = $value; - } - - return $this; - } - - - /** - * Include the view file and extracts the view variables before returning the generated output. - * - * - * // Get view - * $output = $view->render(); - * - * // Display output - * echo $output; - * - * - * @param string $filter Callback function used to filter output - * @return string - */ - public function render($filter = null) { - - // Is output empty ? - if (empty($this->output)) { - - // Extract variables as references - extract(array_merge($this->vars, View::$global_vars), EXTR_REFS); - - // Turn on output buffering - ob_start(); - - // Include view file - include($this->view_file); - - // Output... - $this->output = ob_get_clean(); - } - - // Filter output ? - if ($filter !== null) { - $this->output = call_user_func($filter, $this->output); - } - - // Return output - return $this->output; - } - - - /** - * Displays the rendered view in the browser. - * - * - * $view->display(); - * - * - */ - public function display() { - echo $this->render(); - } - - - /** - * Magic setter method that assigns a view variable. - * - * @param string $key Variable name - * @param mixed $value Variable value - */ - public function __set($key, $value) { - $this->vars[$key] = $value; - } - - - /** - * Magic getter method that returns a view variable. - * - * @param string $key Variable name - * @return mixed - */ - public function __get($key) { - - if (isset($this->vars[$key])) { - return $this->vars[$key]; - } - } - - - /** - * Magic isset method that checks if a view variable is set. - * - * @param string $key Variable name - * @return boolean - */ - public function __isset($key) { - return isset($this->vars[$key]); - } - - - /** - * Magic unset method that unsets a view variable. - * - * @param string $key Variable name - */ - public function __unset($key) { - unset($this->vars[$key]); - } - - - /** - * Method that magically converts the view object into a string. - * - * @return string - */ - public function __toString() { - return $this->render(); - } - } - - - /** - * I18n class - */ - class I18n { - - - /** - * Locales array - * - * @var array - */ - public static $locales = array( - 'ar' => 'العربية', - 'bg' => 'Български', - 'ca' => 'Català', - 'cs' => 'Česky', - 'da' => 'Dansk', - 'de' => 'Deutsch', - 'el' => 'Ελληνικά', - 'en' => 'English', - 'es' => 'Español', - 'fi' => 'Suomi', - 'fr' => 'Français', - 'gl' => 'Galego', - 'hu' => 'Magyar', - 'it' => 'Italiano', - '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', - 'tr' => 'Türkçe', - 'uk' => 'Українська', - 'zh' => '中文', - ); - - - /** - * Dictionary - * - * @var array - */ - public static $dictionary = array(); - - - /** - * An instance of the I18n class - * - * @var I18n - */ - protected static $instance = null; - - - /** - * Initializing I18n - * - * @param string $dir Plugins directory - */ - public static function init($locale) { - if ( ! isset(self::$instance)) self::$instance = new I18n($locale); - return self::$instance; - } - - - /** - * Protected clone method to enforce singleton behavior. - * - * @access protected - */ - protected function __clone() { - // Nothing here. - } - - - /** - * Construct - */ - protected function __construct($locale) { - - // Redefine arguments - $locale = (string) $locale; - - // Get lang table for current locale - $lang_table = Cache::get('i18n', $locale); - - // If lang_table is empty then create new - if ( ! $lang_table) { - - // Get plugins Table - $plugins = new Table('plugins'); - - // Get all plugins - $records = $plugins->select(null, 'all', null, array('location', 'priority'), 'priority', 'ASC'); - - // Init var - $lang_table = array(); - - // Loop through each installed plugin - foreach ($records as $record) { - - if (is_dir(ROOT . DS . dirname($record['location']) . DS . 'languages')) { - - // Init var - $t = array(); - - // Check lang file - if (file_exists(ROOT . DS . dirname($record['location']) . DS . 'languages' . DS . $locale . '.lang.php')) { - - // Merge the language strings into the sub table - $t = array_merge($t, include ROOT . DS . dirname($record['location']) . DS . 'languages' . DS . $locale . '.lang.php'); - - } - - // Append the sub table, preventing less specific language files from overloading more specific files - $lang_table += $t; - } - } - - // Save lang table for current locale - Cache::put('i18n', $locale, $lang_table); - - // Update dictionary - I18n::$dictionary = $lang_table; - } - - // Update dictionary - I18n::$dictionary = $lang_table; - } - - - /** - * Returns translation of a string. If no translation exists, the original - * string will be returned. No parameters are replaced. - * - * - * $hello = I18n::find('Hello friends, my name is :name', 'namespace'); - * - * - * @param string $string Text to translate - * @param string $namespace Namespace - * @return string - */ - public static function find($string, $namespace = null) { - - // Redefine arguments - $string = (string) $string; - - // Return string - if (isset(I18n::$dictionary[$namespace][$string])) return I18n::$dictionary[$namespace][$string]; else return $string; - } - - } - - - /** - * Global Translation/internationalization function. - * Accepts an English string and returns its translation - * to the active system language. If the given string is not available in the - * current dictionary the original English string will be returned. - * - * - * // Display a translated message - * echo __('Hello, world', 'namespace'); - * - * // With parameter replacement - * echo __('Hello, :user', 'namespace', array(':user' => $username)); - * - * - * @global array $dictionary Dictionary - * @param string $string String to translate - * @param array $values Values to replace in the translated text - * @param string $namespace Namespace - * @return string - */ - function __($string, $namespace = null, array $values = null) { - - // Redefine arguments - $string = (string) $string; - - // Find string in dictionary - $string = I18n::find($string, $namespace); - - // Return string - return empty($values) ? $string : strtr($string, $values); - } - - - /** - * Action class - */ - class Action { - - - /** - * Actions - * - * @var array - */ - public static $actions = array(); - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Hooks a function on to a specific action. - * - * - * // Hooks a function "newLink" on to a "footer" action. - * Action::add('footer', 'newLink', 10); - * - * function newLink() { - * echo 'My link'; - * } - * - * - * @param string $action_name Action name - * @param string $added_function Added function - * @param integer $priority Priority. Default is 10 - * @param array $args Arguments - */ - public static function add($action_name, $added_function, $priority = 10, array $args = null) { - - // Hooks a function on to a specific action. - Action::$actions[] = array( - 'action_name' => (string)$action_name, - 'function' => (string)$added_function, - 'priority' => (int)$priority, - 'args' => $args - ); - } - - - /** - * Run functions hooked on a specific action hook. - * - * - * // Run functions hooked on a "footer" action hook. - * Action::run('footer'); - * - * - * @param string $action_name Action name - * @param array $args Arguments - * @param boolean $return Return data or not. Default is false - * @return mixed - */ - public static function run($action_name, $args = array(), $return = false) { - - // Redefine arguments - $action_name = (string) $action_name; - $return = (bool) $return; - - // Run action - if (count(Action::$actions) > 0) { - - // Sort actions by priority - $actions = Arr::subvalSort(Action::$actions, 'priority'); - - // Loop through $actions array - foreach ($actions as $action) { - - // Execute specific action - if ($action['action_name'] == $action_name) { - - // isset arguments ? - if (isset($args)) { - - // Return or Render specific action results ? - if ($return) { - return call_user_func_array($action['function'], $args); - } else { - call_user_func_array($action['function'], $args); - } - - } else { - - if ($return) { - return call_user_func_array($action['function'], $action['args']); - } else { - call_user_func_array($action['function'], $action['args']); - } - - } - - } - - } - - } - - } - - } - - - /** - * Filter class - */ - class Filter { - - - /** - * Filters - * - * @var array - */ - public static $filters = array(); - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Apply filters - * - * - * Filter::apply('content', $content); - * - * - * @param string $filter_name The name of the filter hook. - * @param mixed $value The value on which the filters hooked. - * @return mixed - */ - public static function apply($filter_name, $value) { - - // Redefine arguments - $filter_name = (string) $filter_name; - - $args = array_slice(func_get_args(), 2); - - if ( ! isset(Filter::$filters[$filter_name])) { - return $value; - } - - foreach (Filter::$filters[$filter_name] as $priority => $functions) { - if ( ! is_null($functions)) { - foreach ($functions as $function) { - $all_args = array_merge(array($value), $args); - $function_name = $function['function']; - $accepted_args = $function['accepted_args']; - if ($accepted_args == 1) { - $the_args = array($value); - } elseif ($accepted_args > 1) { - $the_args = array_slice($all_args, 0, $accepted_args); - } elseif ($accepted_args == 0) { - $the_args = null; - } else { - $the_args = $all_args; - } - $value = call_user_func_array($function_name, $the_args); - } - } - } - return $value; - } - - - /** - * Add filter - * - * - * Filter::add('content', 'replacer'); - * - * function replacer($content) { - * return preg_replace(array('/\[b\](.*?)\[\/b\]/ms'), array('\1'), $content); - * } - * - * - * @param string $filter_name The name of the filter to hook the $function_to_add to. - * @param string $function_to_add The name of the function to be called when the filter is applied. - * @param integer $priority Function to add priority - default is 10. - * @param integer $accepted_args The number of arguments the function accept default is 1. - * @return boolean - */ - public static function add($filter_name, $function_to_add, $priority = 10, $accepted_args = 1) { - - // Redefine arguments - $filter_name = (string) $filter_name; - $function_to_add = (string) $function_to_add; - $priority = (int) $priority; - $accepted_args = (int) $accepted_args; - - // Check that we don't already have the same filter at the same priority. Thanks to WP :) - if (isset(Filter::$filters[$filter_name]["$priority"])) { - foreach (Filter::$filters[$filter_name]["$priority"] as $filter) { - if ($filter['function'] == $function_to_add) { - return true; - } - } - } - - Filter::$filters[$filter_name]["$priority"][] = array('function' => $function_to_add, 'accepted_args' => $accepted_args); - - // Sort - ksort(Filter::$filters[$filter_name]["$priority"]); - - return true; - } - - } - - - /** - * Stylesheet class - */ - class Stylesheet { - - - /** - * Stylesheets - * - * @var array - */ - public static $stylesheets = array(); - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Add stylesheet - * - * - * Stylesheet::add('path/to/my/stylesheet1.css'); - * Stylesheet::add('path/to/my/stylesheet2.css', 'frontend', 11); - * Stylesheet::add('path/to/my/stylesheet3.css', 'backend',12); - * - * - * @param string $file File path - * @param string $load Load stylesheet on frontend, backend or both - * @param integer $priority Priority. Default is 10 - */ - public static function add($file, $load = 'frontend', $priority = 10) { - Stylesheet::$stylesheets[] = array( - 'file' => (string)$file, - 'load' => (string)$load, - 'priority' => (int)$priority, - ); - } - - - /** - * Minify, combine and load site stylesheet - */ - public static function load() { - - $backend_site_css_path = MINIFY . DS . 'backend_site.minify.css'; - $frontend_site_css_path = MINIFY . DS . 'frontend_site.minify.css'; - - // Load stylesheets - if (count(Stylesheet::$stylesheets) > 0) { - - $backend_buffer = ''; - $backend_regenerate = false; - - $frontend_buffer = ''; - $frontend_regenerate = false; - - - // Sort stylesheets by priority - $stylesheets = Arr::subvalSort(Stylesheet::$stylesheets, 'priority'); - - 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, Minify::css($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, Minify::css($frontend_buffer)); - $frontend_regenerate = false; - } - - } - - // Render - if (BACKEND) { - echo ''; - } else { - echo ''; - } - } - } - - - /** - * CSS Parser - */ - public static function parseVariables($frontend_buffer) { - return str_replace(array('@site_url', - '@theme_site_url', - '@theme_admin_url'), - array(Option::get('siteurl'), - Option::get('siteurl').'public/themes/'.Option::get('theme_site_name'), - Option::get('siteurl').'admin/themes/'.Option::get('theme_admin_name')), - $frontend_buffer); - } - - - } - - - /** - * Javascript class - */ - class Javascript { - - - /** - * Javascripts - * - * @var array - */ - public static $javascripts = array(); - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Add javascript - * - * - * Javascript::add('path/to/my/script1.js'); - * Javascript::add('path/to/my/script2.js', 'frontend', 11); - * Javascript::add('path/to/my/script3.js', 'backend', 12); - * - * - * @param string $file File path - * @param string $load Load script on frontend, backend or both - * @param inteeer $priority Priority default is 10 - */ - public static function add($file, $load = 'frontend', $priority = 10) { - Javascript::$javascripts[] = array( - 'file' => (string)$file, - 'load' => (string)$load, - 'priority' => (int)$priority, - ); - } - - - /** - * Combine and load site javascript - */ - public static function load() { - - $backend_site_js_path = MINIFY . DS . 'backend_site.minify.js'; - $frontend_site_js_path = MINIFY . DS . 'frontend_site.minify.js'; - - // Load javascripts - if (count(Javascript::$javascripts) > 0) { - - $backend_buffer = ''; - $backend_regenerate = false; - - $frontend_buffer = ''; - $frontend_regenerate = false; - - - // Sort javascripts by priority - $javascripts = Arr::subvalSort(Javascript::$javascripts, 'priority'); - - - 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']); - } - } - 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']); - } - } - file_put_contents($frontend_site_js_path, $frontend_buffer); - $frontend_regenerate = false; - } - - } - - // Render - if (BACKEND) { - echo ''; - } else { - echo ''; - } - } - } - - } - - - /** - * Navigation class - */ - class Navigation { - - - /** - * Items - * - * @var array - */ - public static $items = array(); - - - /** - * Navigation types - */ - const LEFT = 1; - const TOP = 2; - - - /** - * Add new item - * - * - * // Add link for left navigation - * Navigation::add(__('Blog'), 'content', 'blog', 11); - * - * // Add link for top navigation - * Navigation::add(__('View site'), 'top', 'http://site.com/', 11, Navigation::TOP, true); - * - * - * @param string $name Name - * @param string $category Category - * @param stirng $link Link - * @param integer $priority Priority. Default is 10 - * @param integer $type Type. Default is LEFT - * @param bool $external External or not. Default is false - */ - public static function add($name, $category, $id, $priority = 10, $type = Navigation::LEFT, $external = false) { - Navigation::$items[] = array( - 'name' => (string)$name, - 'category' => (string)$category, - 'id' => (string)$id, - 'priority' => (int)$priority, - 'type' => (int)$type, - 'external' => (bool)$external, - ); - } - - - /** - * Draw items - * - * - * Navigation::draw('content'); - * Navigation::draw('top', Navigation::TOP); - * - * - * @param string $category Category - * @param integer $type Type. Default is LEFT - */ - public static function draw($category, $type = Navigation::LEFT) { - - // Sort items by priority - $items = Arr::subvalSort(Navigation::$items, 'priority'); - - // Draw left navigation - if ($type == Navigation::LEFT) { - - // Loop trough the items - foreach ($items as $item) { - - // If current plugin id == selected item id then set class to current - if (Request::get('id') == $item['id'] && $item['external'] == false) $class = 'class = "current" '; else $class = ''; - - // If current category == item category and navigation type is left them draw this item - if ($item['category'] == $category && $item['type'] == Navigation::LEFT) { - - // Is external item id or not ? - if ($item['external'] == false) { - echo '
  • '.$item['name'].'
  • '; - } else { - echo '
  • '.$item['name'].'
  • '; - } - } - } - } elseif ($type == Navigation::TOP) { - // Draw top navigation - foreach ($items as $item) { - if ($item['category'] == $category && $item['type'] == Navigation::TOP) { - if ($item['external'] == false) { - echo ''.$item['name'].''.Html::nbsp(2); - } else { - echo ''.$item['name'].''.Html::nbsp(2); - } - } - } - } - } - - } \ No newline at end of file diff --git a/monstra/engine/shortcodes.php b/monstra/engine/shortcodes.php deleted file mode 100644 index 74ab6d0..0000000 --- a/monstra/engine/shortcodes.php +++ /dev/null @@ -1,187 +0,0 @@ - - * function returnSiteUrl() { - * return Option::get('siteurl'); - * } - * - * // Add shortcode {siteurl} - * Shortcode::add('siteurl', 'returnSiteUrl'); - *
    - * - * @param string $shortcode Shortcode tag to be searched in content. - * @param string $callback_function The callback function to replace the shortcode with. - */ - public static function add($shortcode, $callback_function) { - - // Redefine vars - $shortcode = (string) $shortcode; - - // Add new shortcode - if (is_callable($callback_function)) Shortcode::$shortcode_tags[$shortcode] = $callback_function; - } - - - /** - * Remove a specific registered shortcode. - * - * - * Shortcode::delete('shortcode_name'); - * - * - * @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. - * - * - * Shortcode::clear(); - * - * - */ - public static function clear() { - Shortcode::$shortcode_tags = array(); - } - - - /** - * Check if a shortcode has been registered. - * - * - * if (Shortcode::exists('shortcode_name')) { - * // do something... - * } - * - * - * @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. - * - * - * $content = Shortcode::parse($content); - * - * - * @param string $content Content - * @return string - */ - public static function parse($content) { - - if ( ! Shortcode::$shortcode_tags) return $content; - - $shortcodes = implode('|', array_map('preg_quote', array_keys(Shortcode::$shortcode_tags))); - $pattern = "/(.?)\{([$shortcodes]+)(.*?)(\/)?\}(?(4)|(?:(.+?)\{\/\s*\\2\s*\}))?(.?)/s"; - - return preg_replace_callback($pattern, 'Shortcode::_handle', $content); - } - - - /** - * _handle() - */ - protected static function _handle($matches) { - - $prefix = $matches[1]; - $suffix = $matches[6]; - $shortcode = $matches[2]; - - // Allow for escaping shortcodes by enclosing them in {{shortcode}} - if ($prefix == '{' && $suffix == '}') { - return substr($matches[0], 1, -1); - } - - $attributes = array(); // Parse attributes into into this array. - - if (preg_match_all('/(\w+) *= *(?:([\'"])(.*?)\\2|([^ "\'>]+))/', $matches[3], $match, PREG_SET_ORDER)) { - foreach ($match as $attribute) { - if ( ! empty($attribute[4])) { - $attributes[strtolower($attribute[1])] = $attribute[4]; - } elseif ( ! empty($attribute[3])) { - $attributes[strtolower($attribute[1])] = $attribute[3]; - } - } - } - - // 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 : ''; - } - -} \ No newline at end of file diff --git a/monstra/engine/site.php b/monstra/engine/site.php deleted file mode 100644 index e9ae7d4..0000000 --- a/monstra/engine/site.php +++ /dev/null @@ -1,228 +0,0 @@ - - * echo Site::name(); - *
    - * - * @return string - */ - public static function name() { - return Option::get('sitename'); - } - - - /** - * Get site theme - * - * - * echo Site::theme(); - * - * - * @return string - */ - public static function theme() { - return Option::get('theme_site_name'); - } - - - /** - * Get Page title - * - * - * echo Site::title(); - * - * - * @return string - */ - public static function title() { - return call_user_func(ucfirst(Uri::command()).'::title'); - } - - - /** - * Get page description - * - * - * echo Site::description(); - * - * - * @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 - * - * - * echo Site::keywords(); - * - * - * @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 - * - * - * echo Site::slogan(); - * - * - * @return string - */ - public static function slogan() { - return Option::get('slogan'); - } - - - /** - * Get page content - * - * - * echo Site::content(); - * - * - * @return string - */ - public static function content() { - return Filter::apply('content', call_user_func(ucfirst(Uri::command()).'::content')); - } - - - /** - * Get compressed template - * - * - * echo Site::template(); - * - * - * @param string $theme Theme name - * @return mixed - */ - public static function template($theme = null) { - - // Get specific theme or current theme - $current_theme = ($theme == null) ? Option::get('theme_site_name') : $theme ; - - // Get template - $template = call_user_func(ucfirst(Uri::command()).'::template'); - - // Check whether is there such a template in the current theme - // else return default template: index - // also compress template file :) - if (File::exists(THEMES_SITE . DS . $current_theme . DS . $template . '.template.php')) { - if ( ! file_exists(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php') or - filemtime(THEMES_SITE . DS . $current_theme . DS . $template .'.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php')) { - $buffer = file_get_contents(THEMES_SITE. DS . $current_theme . DS . $template .'.template.php'); - $buffer = Minify::html($buffer); - file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php', $buffer); - } - return 'minify.'.$template; - } else { - if ( ! File::exists(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php') or - filemtime(THEMES_SITE . DS . $current_theme . DS . 'index.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php')) { - $buffer = file_get_contents(THEMES_SITE . DS . $current_theme . DS . 'index.template.php'); - $buffer = Minify::html($buffer); - file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php', $buffer); - } - return 'minify.index'; - } - } - - - /** - * Get site url - * - * - * echo Site::url(); - * - * - * @return string - */ - public static function url() { - return Option::get('siteurl'); - } - - - /** - * Get copyright information - * - * - * echo Site::powered(); - * - * - * @return string - */ - public static function powered() { - return __('Powered by', 'system').' Monstra ' . Core::VERSION; - } - - } \ No newline at end of file diff --git a/monstra/engine/xmldb.php b/monstra/engine/xmldb.php deleted file mode 100644 index bd1b2b3..0000000 --- a/monstra/engine/xmldb.php +++ /dev/null @@ -1,1062 +0,0 @@ - - * $xml_safe = XML::safe($xml_unsafe); - *
    - * - * @param string $str String - * @param boolean $flag Flag - * @return string - */ - public static function safe($str, $flag = true) { - - // Redefine vars - $str = (string) $str; - $flag = (bool) $flag; - - // Remove invisible chars - $non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/'); - do { - $cleaned = $str; - $str = preg_replace($non_displayables, '', $str); - } while ($cleaned != $str); - - // htmlspecialchars - if ($flag) $str = htmlspecialchars($str, ENT_QUOTES, 'utf-8'); - - // Return safe string - return $str; - } - - - /** - * Get XML file - * - * - * $xml_file = XML::loadFile('path/to/file.xml'); - * - * - * @param string $file File name - * @param boolean $force Method - * @return array - */ - public static function loadFile($file, $force = false) { - - // Redefine vars - $file = (string) $file; - $force = (bool) $force; - - // For CMS API XML file force method - if ($force) { - $xml = file_get_contents($file); - $data = simplexml_load_string($xml); - return $data; - } else { - if (file_exists($file) && is_file($file)) { - $xml = file_get_contents($file); - $data = simplexml_load_string($xml); - return $data; - } else { - return false; - } - } - } - - } - - - /** - * DB Class - */ - class DB { - - - /** - * XMLDB directory - * - * @var string - */ - public static $db_dir = STORAGE; - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Configure the settings of XMLDB - * - * @param mixed $setting Setting name - * @param mixed $value Setting value - */ - public static function configure($setting, $value){ - if (property_exists("db", $setting)) DB::$$setting = $value; - } - - - /** - * Create new database - * - * @param string $db_name Database name - * @param integer $mode Mode - * @return boolean - */ - public static function create($db_name, $chmod = 0775) { - - // Redefine vars - $db_name = (string) $db_name; - - // Create - if (is_dir(DB::$db_dir . '/' . $db_name)) return false; - return mkdir(DB::$db_dir . '/' . $db_name, $chmod); - } - - - /** - * Drop database - * - * @param string $db_name Database name - * @return boolean - */ - public static function drop($db_name) { - - // Redefine vars - $db_name = (string) $db_name; - - // Drop - if (is_dir(DB::$db_dir . '/' . $db_name)){$ob=scandir(DB::$db_dir . '/' . $db_name); foreach ($ob as $o){if($o!='.'&&$o!='..'){if(filetype(DB::$db_dir . '/' . $db_name.'/'.$o)=='dir')DB::drop(DB::$db_dir . '/' . $db_name.'/'.$o); else unlink(DB::$db_dir . '/' . $db_name.'/'.$o);}}} - reset($ob); rmdir(DB::$db_dir . '/' . $db_name); - } - - } - - - /** - * Table class - */ - class Table { - - - /** - * XMLDB Tables directory - * - * @var string - */ - public static $tables_dir = XMLDB; - - - /** - * Table - * - * @var object - */ - private $table; - - - /** - * Table name - * - * @var string - */ - private $name; - - - /** - * Configure the settings of XMLDB Tables - * - * @param mixed $setting Setting name - * @param mixed $value Setting value - */ - public static function configure($setting, $value){ - if (property_exists("table", $setting)) Table::$$setting = $value; - } - - - /** - * Table factory. - * - * - * $users = Table::factory('table_name'); - * - * - * @param string $table_name Table name - * @return Table - */ - public static function factory($table_name) { - return new Table($table_name); - } - - - /** - * Table construct - * - * - * $users = new Table('table_name'); - * - * - * @param string $table_name Table name - */ - function __construct($table_name) { - - // Redefine vars - $table_name = (string) $table_name; - - $this->table = Table::get($table_name); - $this->name = $table_name; - } - - - /** - * Create new table - * - * XMLDB Table structure: - * - * - * - * 0 - * - * - * - * - * - * value - * value - * - * - * - * - * Table::create('table_name', array('field1', 'field2')); - * - * - * @param string $table_name Table name - * @param array $fields Fields - * @return boolean - */ - public static function create($table_name, $fields) { - - // Redefine vars - $table_name = (string) $table_name; - - if ( ! file_exists(Table::$tables_dir . '/' . $table_name . '.table.xml') && - is_dir(dirname(Table::$tables_dir)) && - is_writable(dirname(Table::$tables_dir)) && - isset($fields) && - is_array($fields)) { - - // Create table fields - $_fields = ''; - foreach ($fields as $field) $_fields .= "<$field/>"; - $_fields .= ''; - - // Create new table - return file_put_contents(Table::$tables_dir . '/' . $table_name . '.table.xml','0'.$_fields.'', LOCK_EX); - - } else { - - // Something wrong... return false - return false; - } - } - - - /** - * Delete table - * - * - * Table::drop('table_name'); - * - * - * @param string $table_name Table name - * @return boolean - */ - public static function drop($table_name) { - - // Redefine vars - $table_name = (string) $table_name; - - // Drop - if ( ! is_dir(Table::$tables_dir . '/' . $table_name . '.table.xml')) { - return unlink(Table::$tables_dir . '/' . $table_name . '.table.xml'); - } - - return false; - } - - - /** - * Get table - * - * - * $table = Table::get('table_name'); - * - * - * @param array $table_name Table name - * @return mixed - */ - public static function get($table_name) { - - // Redefine vars - $table_name = (string) $table_name; - - // Load table - if (file_exists(Table::$tables_dir . '/' . $table_name.'.table.xml') && is_file(Table::$tables_dir . '/' . $table_name.'.table.xml')) { - $data = array('xml_object' => XML::loadFile(Table::$tables_dir . '/' . $table_name.'.table.xml'), - 'xml_filename' => Table::$tables_dir . '/' . $table_name.'.table.xml'); - return $data; - } else { - return false; - } - } - - - /** - * Get information about table - * - * - * var_dump($users->info()); - * - * - * @return array - */ - public function info() { - return array( - 'table_name' => basename($this->table['xml_filename'], '.table.xml'), - 'table_size' => filesize($this->table['xml_filename']), - 'table_last_change' => filemtime($this->table['xml_filename']), - 'table_last_access' => fileatime($this->table['xml_filename']), - 'table_fields' => $this->fields(), - 'records_count' => $this->count(), - 'records_last_id' => $this->lastId() - ); - } - - - /** - * Get table fields - * - * - * var_dump($users->fields()); - * - * - * @return array - */ - public function fields() { - - // Select fields - $fields_obj = Table::_selectOne($this->table, "fields"); - - // Create fields array - foreach ($fields_obj as $key => $field) { - $fields[] = $key; - } - - // Return array of fields - return $fields; - } - - - /** - * Add new field - * - * - * $users->addField('test'); - * - * - * @param string $name Field name - * @return boolean - */ - public function addField($name) { - - // Redefine vars - $name = (string) $name; - - // Get table - $table = $this->table; - - // Select all fields - $fields = Table::_selectOne($this->table, "fields"); - - // Select current field - $field = Table::_selectOne($this->table, "fields/{$name}"); - - // If field dosnt exists than create new field - if ($field == null) { - - // Create new field - $fields->addChild($name, ''); - - // Save table - return Table::_save($table); - - } else { - - return false; - - } - - } - - - /** - * Delete field - * - * - * $users->deleteField('test'); - * - * - * @param string $name Field name - * @return boolean - */ - public function deleteField($name) { - - // Redefine vars - $name = (string) $name; - - // Get table - $table = $this->table; - - // Select field - $field = Table::_selectOne($this->table, "fields/{$name}"); - - // If field exist than delete it - if ($field != null) { - - // Delete field - unset($field[0]); - - // Save table - return Table::_save($table); - - } else { - - return false; - - } - } - - - /** - * Update field - * - * - * $users->updateField('login', 'username'); - * - * - * @param string $old_name Old field name - * @param string $new_name New field name - * @return boolean - */ - public function updateField($old_name, $new_name) { - if (file_exists(Table::$tables_dir . '/' . $this->name.'.table.xml') && is_file(Table::$tables_dir . '/' . $this->name.'.table.xml')) { - $table = strtr(file_get_contents(Table::$tables_dir . '/' . $this->name.'.table.xml'), array('<'.$old_name.'>' => '<'.$new_name.'>', - '' => '', - '<'.$old_name.'/>' => '<'.$new_name.'/>')); - if (file_put_contents(Table::$tables_dir . '/' . $this->name.'.table.xml', $table)) { - return true; - } else { - return false; - } - } - } - - - /** - * Check if field exist - * - * - * if ($users->existsField('field_name')) { - * // do something... - * } - * - * - * @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 - * - * - * $users->insert(array('login'=>'admin', 'password'=>'pass')); - * - * - * @param array $fields Record fields to insert - * @return boolean - */ - public function insert(array $fields = null) { - - // Set save flag to true - $save = true; - - // Foreach fields check is current field alredy exists - if (count($fields) !== 0) { - foreach ($fields as $key => $value) { - if (Table::_selectOne($this->table, "fields/{$key}") == null) { - $save = false; - break; - } - } - } - - // Get table fields and create fields names array - $_fields = Table::_selectOne($this->table, "fields"); - foreach ($_fields as $key => $value) { - $field_names[(string)$key] = (string)$key; - } - - // Save record - if ($save) { - - // Find autoincrement option - $inc = Table::_selectOne($this->table, "options/autoincrement"); - - // Increment - $inc_upd = $inc + 1; - - // Add record - $node = $this->table['xml_object']->addChild(XML::safe($this->name)); - - // Update autoincrement - Table::_updateWhere($this->table, "options", array('autoincrement' => $inc_upd)); - - // Add common record fields: id and uid - $node->addChild('id', $inc_upd); - $node->addChild('uid', Table::_generateUID()); - - // If exists fields to insert then insert them - if (count($fields) !== 0) { - - $table_fields = array_diff_key($field_names, $fields); - - // Defined fields - foreach ($table_fields as $table_field) { - $node->addChild($table_field, ''); - } - - // User fields - foreach ($fields as $key => $value) { - $node->addChild($key, XML::safe($value)); - } - } - - // Save table - return Table::_save($this->table); - - } else { - - return false; - - } - } - - - /** - * Select record(s) in table - * - * - * $records = $users->select('[id=2]'); - * $records = $users->select(null, 'all'); - * $records = $users->select(null, 'all', null, array('login')); - * $records = $users->select(null, 2, 1); - * - * - * @param string $query XPath query - * @param integer $row_count Row count. To select all records write 'all' - * @param integer $offset Offset - * @param array $fields Fields - * @param string $order_by Order by - * @param string $order Order type - * @return array - */ - public function select($query = null, $row_count = 'all', $offset = null, array $fields = null, $order_by = 'id', $order = 'ASC') { - - // Redefine vars - $query = ($query === null) ? null : (string) $query; - $offset = ($offset === null) ? null : (int) $offset; - $order_by = (string) $order_by; - $order = (string) $order; - - // Execute query - if ($query !== null) { - $tmp = $this->table['xml_object']->xpath('//'.$this->name.$query); - } else { - $tmp = $this->table['xml_object']->xpath($this->name); - } - - // Init vars - $data = array(); - $records = array(); - $_records = array(); - - $one_record = false; - - // If row count is null then select only one record - // eg: $users->select('[login="admin"]', null); - if ($row_count == null) { - - if (isset($tmp[0])) { - $_records = $tmp[0]; - $one_record = true; - } - - } else { - - // If row count is 'all' then select all records - // eg: - // $users->select('[status="active"]', 'all'); - // or - // $users->select('[status="active"]'); - 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)$value; - } - } - - - $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 - * - * - * $users->delete(2); - * - * - * @param integer $id Record ID - * @return boolean - */ - public function delete($id) { - - // Redefine vars - $id = (int) $id; - - // Find record to delete - $xml_arr = Table::_selectOne($this->table, "//".$this->name."[id='".$id."']"); - - // If its exists then delete it - if (count($xml_arr) !== 0) { - - // Delete - unset($xml_arr[0]); - - } - - // Save table - return Table::_save($this->table); - } - - - /** - * Delete with xPath query record in xml file - * - * - * $users->deleteWhere('[id=2]'); - * - * - * @param string $query xPath query - * @return boolean - */ - public function deleteWhere($query) { - - // Redefine vars - $query = (string) $query; - - // Find record to delete - $xml_arr = Table::_selectOne($this->table, '//'.$this->name.$query); - - // If its exists then delete it - if (count($xml_arr) !== 0) { - - // Delete - unset($xml_arr[0]); - - } - - // Save table - return Table::_save($this->table); - } - - - /** - * Update record with xPath query in XML file - * - * - * $users->updateWhere('[id=2]', array('login'=>'Admin', 'password'=>'new pass')); - * - * - * @param string $query XPath query - * @param array $fields Record fields to udpate - * @return boolean - */ - public function updateWhere($query, array $fields = null) { - - // Redefine vars - $query = (string) $query; - - // Set save flag to true - $save = true; - - // Foreach fields check is current field alredy exists - if (count($fields) !== 0) { - foreach ($fields as $key => $value) { - if (Table::_selectOne($this->table, "fields/{$key}") == null) { - $save = false; - break; - } - } - } - - // Get table fields and create fields names array - $_fields = Table::_selectOne($this->table, "fields"); - foreach ($_fields as $key => $value) { - $field_names[(string)$key] = (string)$key; - } - - // Save record - if ($save) { - - // Find record - $xml_arr = Table::_selectOne($this->table, '//'.$this->name.$query); - - // If its exists then delete it - if (count($fields) !== 0) { - foreach ($fields as $key => $value) { - // Else: Strict Mode Error - // Creating default object from empty value - @$xml_arr->$key = XML::safe($value, false); - } - } - - // Save table - return Table::_save($this->table); - - } else { - - return false; - - } - } - - - /** - * Update current record in table - * - * - * $users->update(1, array('login'=>'Admin','password'=>'new pass')); - * - * - * @param integer $id Record ID - * @param array $fields Record fields to udpate - * @return boolean - */ - public function update($id, array $fields = null) { - - // Redefine vars - $id = (int) $id; - - // Set save flag to true - $save = true; - - // Foreach fields check is current field alredy exists - if (count($fields) !== 0) { - foreach ($fields as $key => $value) { - if (Table::_selectOne($this->table, "fields/{$key}") == null) { - $save = false; - break; - } - } - } - - // Get table fields and create fields names array - $_fields = Table::_selectOne($this->table, "fields"); - foreach ($_fields as $key => $value) { - $field_names[(string)$key] = (string)$key; - } - - // Save record - if ($save) { - - // Find record to delete - $xml_arr = Table::_selectOne($this->table, "//".$this->name."[id='".(int)$id."']"); - - // If its exists then update it - if (count($fields) !== 0) { - foreach ($fields as $key => $value) { - - // Delete current - unset($xml_arr->$key); - - // And add new one - $xml_arr->addChild($key, XML::safe($value, false)); - - } - } - - // Save table - return Table::_save($this->table); - - } else { - - return false; - - } - } - - - /** - * Get last record id - * - * - * echo $users->lastId(); - * - * - * @return integer - */ - public function lastId() { - $data = $this->table['xml_object']->xpath("//root/node()[last()]"); - return (int)$data[0]->id; - } - - - /** - * Get count of records - * - * - * echo $users->count(); - * - * - * @return integer - */ - public function count() { - return count($this->table['xml_object'])-2; - } - - - - /** - * Subval sort - * - * @param array $a Array - * @param string $subkey Key - * @param string $order Order type DESC or ASC - * @return array - */ - protected static function subvalSort($a, $subkey, $order = null) { - if (count($a) != 0 || (!empty($a))) { - foreach ($a as $k=>$v) $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]); - if ($order==null || $order== 'ASC') asort($b); else if ($order == 'DESC') arsort($b); - foreach ($b as $key=>$val) $c[] = $a[$key]; - return $c; - } - } - - - /** - * _selectOne - */ - protected static function _selectOne($table, $query) { - $tmp = $table['xml_object']->xpath($query); - return isset($tmp[0])? $tmp[0]: null; - } - - - /** - * _updateWhere - */ - protected static function _updateWhere($table, $query, $fields = array()) { - - // Find record to delete - $xml_arr = Table::_selectOne($table, $query); - - // If its exists then delete it - if (count($fields) !== 0) { - foreach ($fields as $key => $value) { - $xml_arr->$key = XML::safe($value, false); - } - } - - // Save table - Table::_save($table); - } - - - /** - * _generateUID - */ - protected static function _generateUID() { - return substr(md5(uniqid(rand(), true)), 0, 10); - } - - - /** - * Format XML and save - * - * @param array $table Array of database name and XML object - */ - protected static function _save($table) { - $dom = new DOMDocument('1.0'); - $dom->preserveWhiteSpace = false; - - // Save new xml data to xml file only if loadXML successful. - // Preventing the destruction of the database by unsafe data. - // note: If loadXML !successful then _save() add&save empty record. - // This record cant be removed by delete[Where]() Problem solved by hand removing... - // Possible solution: modify delete[Where]() or prevent add&saving of such records. - // the result now: database cant be destroyed :) - if ($dom->loadXML($table['xml_object']->asXML())) { - $dom->save($table['xml_filename']); - return true; - } else { - return false; - // report about errors... - } - } - - } \ No newline at end of file diff --git a/monstra/helpers/agent.php b/monstra/helpers/agent.php deleted file mode 100644 index f9ee9cc..0000000 --- a/monstra/helpers/agent.php +++ /dev/null @@ -1,171 +0,0 @@ - - * if (Agent::isMobile()) { - * // Do something... - * } - *
    - * - * @return boolean - */ - public static function isMobile() { - return Agent::find(Agent::$mobiles); - } - - - /** - * Returns true if the user agent that made the request is identified as a robot/crawler. - * - * - * if (Agent::isRobot()) { - * // Do something... - * } - * - * - * @return boolean - */ - public static function isRobot() { - return Agent::find(Agent::$robots); - } - - - /** - * Returns TRUE if the string you're looking for exists in the user agent string and FALSE if not. - * - * - * if (Agent::is('iphone')) { - * // Do something... - * } - * - * if (Agent::is(array('iphone', 'ipod'))) { - * // Do something... - * } - * - * - * @param mixed $device String or array of strings you're looking for - * @return boolean - */ - public static function is($device) { - return Agent::find((array) $device); - } - -} \ No newline at end of file diff --git a/monstra/helpers/alert.php b/monstra/helpers/alert.php deleted file mode 100644 index 316ad6d..0000000 --- a/monstra/helpers/alert.php +++ /dev/null @@ -1,97 +0,0 @@ - - * Alert::success('Message here...'); - *
    - * - * @param string $message Message - * @param integer $time Time - */ - public static function success($message, $time = 3000) { - - // Redefine vars - $message = (string) $message; - $time = (int) $time; - - echo '
    '.$message.'
    - '; - } - - - /** - * Show warning message - * - * - * Alert::warning('Message here...'); - * - * - * @param string $message Message - * @param integer $time Time - */ - public static function warning($message, $time = 3000) { - - // Redefine vars - $message = (string) $message; - $time = (int) $time; - - echo '
    '.$message.'
    - '; - } - - - /** - * Show error message - * - * - * Alert::error('Message here...'); - * - * - * @param string $message Message - * @param integer $time Time - */ - public static function error($message, $time = 3000) { - - // Redefine vars - $message = (string) $message; - $time = (int) $time; - - echo '
    '.$message.'
    - '; - } - - } \ No newline at end of file diff --git a/monstra/helpers/arr.php b/monstra/helpers/arr.php deleted file mode 100644 index 456d000..0000000 --- a/monstra/helpers/arr.php +++ /dev/null @@ -1,193 +0,0 @@ - - * $new_array = Arr::subvalSort($old_array, 'sort'); - *
    - * - * @param array $a Array - * @param string $subkey Key - * @param string $order Order type DESC or ASC - * @return array - */ - public static function subvalSort($a, $subkey, $order = null) { - if (count($a) != 0 || (!empty($a))) { - foreach ($a as $k => $v) $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]); - if ($order == null || $order == 'ASC') asort($b); else if ($order == 'DESC') arsort($b); - foreach ($b as $key => $val) $c[] = $a[$key]; - return $c; - } - } - - - /** - * Returns value from array using "dot notation". - * If the key does not exist in the array, the default value will be returned instead. - * - * - * $login = Arr::get($_POST, 'login'); - * - * $array = array('foo' => 'bar'); - * $foo = Arr::get($array, 'foo'); - * - * $array = array('test' => array('foo' => 'bar')); - * $foo = Arr::get($array, 'test.foo'); - * - * - * @param array $array Array to extract from - * @param string $path Array path - * @param mixed $default Default value - * @return mixed - */ - public static function get($array, $path, $default = null) { - - // Get segments from path - $segments = explode('.', $path); - - // Loop through segments - foreach($segments as $segment) { - - // Check - if ( ! is_array($array) || !isset($array[$segment])) { - return $default; - } - - // Write - $array = $array[$segment]; - } - - // Return - return $array; - } - - - /** - * Deletes an array value using "dot notation". - * - * - * Arr::delete($array, 'foo.bar'); - * - * - * @access public - * @param array $array Array you want to modify - * @param string $path Array path - * @return boolean - */ - public static function delete(&$array, $path) { - - // Get segments from path - $segments = explode('.', $path); - - // Loop through segments - while(count($segments) > 1) { - - $segment = array_shift($segments); - - if ( ! isset($array[$segment]) || !is_array($array[$segment])) { - return false; - } - - $array =& $array[$segment]; - } - - unset($array[array_shift($segments)]); - - return true; - } - - - /** - * Checks if the given dot-notated key exists in the array. - * - * - * if (Arr::keyExists($array, 'foo.bar')) { - * // Do something... - * } - * - * - * @param array $array The search array - * @param mixed $path Array path - * @return boolean - */ - public static function keyExists($array, $path) { - - foreach (explode('.', $path) as $segment) { - - if ( ! is_array($array) or ! array_key_exists($segment, $array)) { - return false; - } - - $array = $array[$segment]; - } - - return true; - } - - - /** - * Returns a random value from an array. - * - * - * Arr::random(array('php', 'js', 'css', 'html')); - * - * - * @access public - * @param array $array Array path - * @return mixed - */ - public static function random($array) { - return $array[array_rand($array)]; - } - - - /** - * Returns TRUE if the array is associative and FALSE if not. - * - * - * if (Arr::isAssoc($array)) { - * // Do something... - * } - * - * - * @param array $array Array to check - * @return boolean - */ - public static function isAssoc($array) { - return (bool) count(array_filter(array_keys($array), 'is_string')); - } - - } \ No newline at end of file diff --git a/monstra/helpers/cache.php b/monstra/helpers/cache.php deleted file mode 100644 index 34022e0..0000000 --- a/monstra/helpers/cache.php +++ /dev/null @@ -1,225 +0,0 @@ - - * Cache::configure('cache_dir', 'path/to/cache/dir'); - *
    - * - * @param mixed $setting Setting name - * @param mixed $value Setting value - */ - public static function configure($setting, $value){ - if (property_exists("cache", $setting)) Cache::$$setting = $value; - } - - - /** - * Get data from cache - * - * - * $profile = Cache::get('profiles', 'profile'); - * - * - * @param string $namespace Namespace - * @param string $key Cache key - * @return boolean - */ - public static function get($namespace, $key){ - - // Redefine vars - $namespace = (string) $namespace; - - // Get cache file id - $cache_file_id = Cache::getCacheFileID($namespace, $key); - - // Is cache file exists ? - if (file_exists($cache_file_id)) { - - // If cache file has not expired then fetch it - if ((time() - filemtime($cache_file_id)) < Cache::$cache_time) { - - $handle = fopen($cache_file_id, 'r'); - - $cache = ''; - - while ( ! feof($handle)) { - $cache .= fgets($handle); - } - - fclose($handle); - - return unserialize($cache); - - } else { - unlink($cache_file_id); - return false; - } - } else { - return false; - } - } - - - /** - * Create new cache file $key in namescapce $namespace with the given data $data - * - * - * $profile = array('login' => 'Awilum', - * 'email' => 'awilum@msn.com'); - * Cache::put('profiles', 'profile', $profile); - * - * - * @param string $namespace Namespace - * @param string $key Cache key - * @param mixed $data The variable to store - * @return boolean - */ - public static function put($namespace, $key, $data) { - - // Redefine vars - $namespace = (string) $namespace; - - // Is CACHE directory writable ? - if (file_exists(CACHE) === false || is_readable(CACHE) === false || is_writable(CACHE) === false) { - throw new RuntimeException(vsprintf("%s(): Cache directory ('%s') is not writable.", array(__METHOD__, CACHE))); - } - - // Create namespace - if ( ! file_exists(Cache::getNamespaceID($namespace))) { - mkdir(Cache::getNamespaceID($namespace), 0775, true); - } - - // Write cache to specific namespace - return file_put_contents(Cache::getCacheFileID($namespace, $key), serialize($data), LOCK_EX); - } - - - /** - * Deletes a cache in specific namespace - * - * - * Cache::delete('profiles', 'profile'); - * - * - * @param string $namespace Namespace - * @param string $key Cache key - * @return boolean - */ - public static function delete($namespace, $key) { - - // Redefine vars - $namespace = (string) $namespace; - - if (file_exists(Cache::getCacheFileID($namespace, $key))) unlink(Cache::getCacheFileID($namespace, $key)); else return false; - } - - - /** - * Clean specific cache namespace. - * - * - * Cache::clean('profiles'); - * - * - * @param string $namespace Namespace - * @return null - */ - public static function clean($namespace) { - - // Redefine vars - $namespace = (string) $namespace; - - array_map("unlink", glob(Cache::$cache_dir . DS . md5($namespace) . DS . "*." . Cache::$cache_file_ext)); - } - - - /** - * Get cache file ID - * - * @param string $namespace Namespace - * @param string $key Cache key - * @return string - */ - protected static function getCacheFileID($namespace, $key) { - - // Redefine vars - $namespace = (string) $namespace; - - return Cache::$cache_dir . DS . md5($namespace) . DS . md5($key) . '.' . Cache::$cache_file_ext; - } - - - /** - * Get namespace ID - * - * @param string $namespace Namespace - * @return string - */ - protected static function getNamespaceID($namespace) { - - // Redefine vars - $namespace = (string) $namespace; - - return Cache::$cache_dir . DS . md5($namespace); - } - - - } \ No newline at end of file diff --git a/monstra/helpers/captcha.php b/monstra/helpers/captcha.php deleted file mode 100644 index 903cf5d..0000000 --- a/monstra/helpers/captcha.php +++ /dev/null @@ -1,84 +0,0 @@ - - *
    - * - * - * - *
    - *
    - * - * @return string - */ - public static function getMathQuestion() { - - if ( ! isset($_SESSION["math_question_v1"]) && ! isset($_SESSION["math_question_v2"])) { - $v1 = rand(1,9); - $v2 = rand(1,9); - $_SESSION["math_question_v1"] = $v1; - $_SESSION["math_question_v2"] = $v2; - } else { - $v1 = $_SESSION["math_question_v1"]; - $v2 = $_SESSION["math_question_v2"]; - } - - return sprintf("%s + %s = ", $v1, $v2); - } - - - /** - * Checks the given answer if it matches the addition of the saved session variables. - * - * - * if (isset($_POST['submit'])) { - * if (Captcha::correctAnswer($_POST['answer'])) { - * // Do something... - * } - * } - * - * - * @param integer $answer User answer - */ - public static function correctAnswer($answer){ - - $v1 = $_SESSION["math_question_v1"]; - $v2 = $_SESSION["math_question_v2"]; - - unset($_SESSION['math_question_v1']); - unset($_SESSION['math_question_v2']); - - if (($v1 + $v2) == $answer) { - return true; - } - - return false; - - } - - } diff --git a/monstra/helpers/cookie.php b/monstra/helpers/cookie.php deleted file mode 100644 index 29289f8..0000000 --- a/monstra/helpers/cookie.php +++ /dev/null @@ -1,113 +0,0 @@ - - * Cookie::set('limit', 10); - *
    - * - * @param string $key A name for the cookie. - * @param mixed $value The value to be stored. Keep in mind that they will be serialized. - * @param integer $expire The number of seconds that this cookie will be available. - * @param string $path The path on the server in which the cookie will be availabe. Use / for the entire domain, /foo if you just want it to be available in /foo. - * @param string $domain The domain that the cookie is available on. Use .example.com to make it available on all subdomains of example.com. - * @param boolean $secure Should the cookie be transmitted over a HTTPS-connection? If true, make sure you use a secure connection, otherwise the cookie won't be set. - * @param boolean $httpOnly Should the cookie only be available through HTTP-protocol? If true, the cookie can't be accessed by Javascript, ... - * @return boolean - */ - public static function set($key, $value, $expire = 86400, $domain = '', $path = '/', $secure = false, $httpOnly = false) { - - // Redefine vars - $key = (string) $key; - $value = serialize($value); - $expire = time() + (int) $expire; - $path = (string) $path; - $domain = (string) $domain; - $secure = (bool) $secure; - $httpOnly = (bool) $httpOnly; - - // Set cookie - return setcookie($key, $value, $expire, $path, $domain, $secure, $httpOnly); - } - - - /** - * Get a cookie - * - * - * $limit = Cookie::get('limit'); - * - * - * @param string $key The name of the cookie that should be retrieved. - * @return mixed - */ - public static function get($key) { - - // Redefine key - $key = (string) $key; - - // Cookie doesn't exist - if( ! isset($_COOKIE[$key])) return false; - - // Fetch base value - $value = (get_magic_quotes_gpc()) ? stripslashes($_COOKIE[$key]) : $_COOKIE[$key]; - - // Unserialize - $actual_value = @unserialize($value); - - // If unserialize failed - if($actual_value === false && serialize(false) != $value) return false; - - // Everything is fine - return $actual_value; - - } - - - /** - * Delete a cookie - * - * - * Cookie::delete('limit'); - * - * - * @param string $name The name of the cookie that should be deleted. - */ - public static function delete($key) { - unset($_COOKIE[$key]); - } - - } \ No newline at end of file diff --git a/monstra/helpers/curl.php b/monstra/helpers/curl.php deleted file mode 100644 index 015167d..0000000 --- a/monstra/helpers/curl.php +++ /dev/null @@ -1,153 +0,0 @@ - 'Mozilla/5.0 (compatible; Monstra CMS; +http://monstra.org)', - CURLOPT_RETURNTRANSFER => true - ); - - - /** - * Information about the last transfer. - * - * @var array - */ - protected static $info; - - - /** - * Performs a curl GET request. - * - * - * $res = Curl::get('http://site.com/'); - * - * - * @param string $url The URL to fetch - * @param array $options An array specifying which options to set and their values - * @return string - */ - public static function get($url, array $options = null) { - - // Redefine vars - $url = (string) $url; - - // Check if curl is available - if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__))); - - // Initialize a cURL session - $handle = curl_init($url); - - // Merge options - $options = (array) $options + Curl::$default_options; - - // Set multiple options for a cURL transfer - curl_setopt_array($handle, $options); - - // Perform a cURL session - $response = curl_exec($handle); - - // Set information regarding a specific transfer - Curl::$info = curl_getinfo($handle); - - // Close a cURL session - curl_close($handle); - - // Return response - return $response; - } - - - /** - * Performs a curl POST request. - * - * - * $res = Curl::post('http://site.com/login'); - * - * - * @param string $url The URL to fetch - * @param array $data An array with the field name as key and field data as value - * @param boolean $multipart True to send data as multipart/form-data and false to send as application/x-www-form-urlencoded - * @param array $options An array specifying which options to set and their values - * @return string - */ - public static function post($url, array $data = null, $multipart = false, array $options = null) { - - // Redefine vars - $url = (string) $url; - - // Check if curl is available - if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__))); - - // Initialize a cURL session - $handle = curl_init($url); - - // Merge options - $options = (array) $options + Curl::$default_options; - - // Add options - $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = ($multipart === true) ? (array) $data : http_build_query((array) $data); - - // Set multiple options for a cURL transfer - curl_setopt_array($handle, $options); - - // Perform a cURL session - $response = curl_exec($handle); - - // Set information regarding a specific transfer - Curl::$info = curl_getinfo($handle); - - // Close a cURL session - curl_close($handle); - - // Return response - return $response; - } - - - /** - * Gets information about the last transfer. - * - * - * $res = Curl::getInfo(); - * - * - * @param string $value Array key of the array returned by curl_getinfo() - * @return mixed - */ - public static function getInfo($value = null) { - - if (empty(Curl::$info)) { - return false; - } - - return ($value === null) ? Curl::$info : Curl::$info[$value]; - } - - } \ No newline at end of file diff --git a/monstra/helpers/date.php b/monstra/helpers/date.php deleted file mode 100644 index 0adf332..0000000 --- a/monstra/helpers/date.php +++ /dev/null @@ -1,432 +0,0 @@ - - * echo Date::format($date, 'j.n.Y'); - *
    - * - * @param integer $date Unix timestamp - * @param string $format Date format - * @return integer - */ - public static function format($date, $format = '') { - - // Redefine vars - $format = (string) $format; - $date = (int) $date; - - if ($format != '') { return date($format, $date); } else { return date(MONSTRA_DATE_FORMAT, $date); } - } - - - /** - * Get number of seconds in a minute, incrementing by a step. - * - * - * $seconds = Date::seconds(); - * - * - * @param integer $step Amount to increment each step by, 1 to 30 - * @param integer $start Start value - * @param integer $end End value - * @return array - */ - public static function seconds($step = 1, $start = 0, $end = 60) { - - // Redefine vars - $step = (int) $step; - $start = (int) $start; - $end = (int) $end; - - return Date::_range($step, $start, $end); - } - - - /** - * Get number of minutes in a hour, incrementing by a step. - * - * - * $minutes = Date::minutes(); - * - * - * @param integer $step Amount to increment each step by, 1 to 30 - * @param integer $start Start value - * @param integer $end End value - * @return array - */ - public static function minutes($step = 5, $start = 0, $end = 60) { - - // Redefine vars - $step = (int) $step; - $start = (int) $start; - $end = (int) $end; - - return Date::_range($step, $start, $end); - } - - - /** - * Get number of hours, incrementing by a step. - * - * - * $hours = Date::hours(); - * - * - * @param integer $step Amount to increment each step by, 1 to 30 - * @param integer $long Start value - * @param integer $start End value - * @return array - */ - public static function hours($step = 1, $long = false, $start = null) { - - // Redefine vars - $step = (int) $step; - $long = (bool) $long; - - if ($start === null) $start = ($long === FALSE) ? 1 : 0; - $end = ($long === true) ? 23 : 12; - - return Date::_range($step, $start, $end, true); - } - - - /** - * Get number of months. - * - * - * $months = Date::months(); - * - * - * @return array - */ - public static function months() { - return Date::_range(1, 1, 12, true); - } - - - /** - * Get number of days. - * - * - * $months = Date::days(); - * - * - * @return array - */ - public static function days() { - return Date::_range(1, 1, Date::daysInMonth((int)date('M')), true); - } - - - /** - * Returns the number of days in the requested month - * - * - * $days = Date::daysInMonth(1); - * - * - * @param integer $month Month as a number (1-12) - * @param integer $year The year - * @return integer - */ - public static function daysInMonth($month, $year = null) { - - // Redefine vars - $month = (int) $month; - $year = ! empty($year) ? (int) $year : (int) date('Y'); - - if ($month < 1 or $month > 12) { - return false; - } elseif ($month == 2) { - if ($year % 400 == 0 or ($year % 4 == 0 and $year % 100 != 0)) { - return 29; - } - } - - $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); - return $days_in_month[$month-1]; - } - - - /** - * Get number of years. - * - * - * $years = Date::years(); - * - * - * @param integer $long Start value - * @param integer $start End value - * @return array - */ - public static function years($start = 1980, $end = 2024) { - - // Redefine vars - $start = (int) $start; - $end = (int) $end; - - return Date::_range(1, $start, $end, true); - } - - - /** - * Get current season name - * - * - * echo Date::season(); - * - * - * @return string - */ - public static function season() { - $seasons = array("Winter", "Spring", "Summer", "Autumn"); - return $seasons[(int)((date("n") %12)/3)]; - } - - - /** - * Get today date - * - * - * echo Date::today(); - * - * - * @param string $format Date format - * @return string - */ - public static function today($format = '') { - - // Redefine vars - $format = (string) $format; - - if ($format != '') { return date($format); } else { return date(MONSTRA_DATE_FORMAT); } - } - - - /** - * Get yesterday date - * - * - * echo Date::yesterday(); - * - * - * @param string $format Date format - * @return string - */ - public static function yesterday($format = '') { - - // Redefine vars - $format = (string) $format; - - if ($format != '') { return date($format, strtotime("-1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); } - } - - - /** - * Get tomorrow date - * - * - * echo Date::tomorrow(); - * - * - * @param string $format Date format - * @return string - */ - public static function tomorrow($format = '') { - - // Redefine vars - $format = (string) $format; - - if ($format != '') { return date($format, strtotime("+1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); } - } - - - /** - * Converts a UNIX timestamp to DOS format. - * - * - * $dos = Date::unix2dos($unix); - * - * - * @param integer $timestamp UNIX timestamp - * @return integer - */ - public static function unix2dos($timestamp = 0) { - - $timestamp = ($_timestamp == 0) ? getdate() : getdate($_timestamp); - - if ($timestamp['year'] < 1980) return (1 << 21 | 1 << 16); - - $timestamp['year'] -= 1980; - - return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 | - $timestamp['mday'] << 16 | $timestamp['hours'] << 11 | - $timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1); - } - - - /** - * Converts a DOS timestamp to UNIX format. - * - * - * $unix = Date::dos2unix($dos); - * - * - * @param integer $timestamp DOS timestamp - * @return integer - */ - public static function dos2unix($timestamp) { - $sec = 2 * ($timestamp & 0x1f); - $min = ($timestamp >> 5) & 0x3f; - $hrs = ($timestamp >> 11) & 0x1f; - $day = ($timestamp >> 16) & 0x1f; - $mon = (($timestamp >> 21) & 0x0f); - $year = (($timestamp >> 25) & 0x7f) + 1980; - return mktime($hrs, $min, $sec, $mon, $day, $year); - } - - - /** - * Get Time zones - * - * @return array - */ - public static function timezones() { - return array('Kwajalein'=>'(GMT-12:00) International Date Line West', - 'Pacific/Samoa'=>'(GMT-11:00) Midway Island, Samoa', - 'Pacific/Honolulu'=>'(GMT-10:00) Hawaii', - 'America/Anchorage'=>'(GMT-09:00) Alaska', - 'America/Los_Angeles'=>'(GMT-08:00) Pacific Time (US & Canada)', - 'America/Tijuana'=>'(GMT-08:00) Tijuana, Baja California', - 'America/Denver'=>'(GMT-07:00) Mountain Time (US & Canada)', - 'America/Chihuahua'=>'(GMT-07:00) Chihuahua, La Paz, Mazatlan', - 'America/Phoenix'=>'(GMT-07:00) Arizona', - 'America/Regina'=>'(GMT-06:00) Saskatchewan', - 'America/Tegucigalpa'=>'(GMT-06:00) Central America', - 'America/Chicago'=>'(GMT-06:00) Central Time (US & Canada)', - 'America/Mexico_City'=>'(GMT-06:00) Guadalajara, Mexico City, Monterrey', - 'America/New_York'=>'(GMT-05:00) Eastern Time (US & Canada)', - 'America/Bogota'=>'(GMT-05:00) Bogota, Lima, Quito, Rio Branco', - 'America/Indiana/Indianapolis'=>'(GMT-05:00) Indiana (East)', - 'America/Caracas'=>'(GMT-04:30) Caracas', - 'America/Halifax'=>'(GMT-04:00) Atlantic Time (Canada)', - 'America/Manaus'=>'(GMT-04:00) Manaus', - 'America/Santiago'=>'(GMT-04:00) Santiago', - 'America/La_Paz'=>'(GMT-04:00) La Paz', - 'America/St_Johns'=>'(GMT-03:30) Newfoundland', - 'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Buenos Aires', - 'America/Sao_Paulo'=>'(GMT-03:00) Brasilia', - 'America/Godthab'=>'(GMT-03:00) Greenland', - 'America/Montevideo'=>'(GMT-03:00) Montevideo', - 'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Georgetown', - 'Atlantic/South_Georgia'=>'(GMT-02:00) Mid-Atlantic', - 'Atlantic/Azores'=>'(GMT-01:00) Azores', - 'Atlantic/Cape_Verde'=>'(GMT-01:00) Cape Verde Is.', - 'Europe/London'=>'(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London', - 'Atlantic/Reykjavik'=>'(GMT) Monrovia, Reykjavik', - 'Africa/Casablanca'=>'(GMT) Casablanca', - 'Europe/Belgrade'=>'(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague', - 'Europe/Sarajevo'=>'(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb', - 'Europe/Brussels'=>'(GMT+01:00) Brussels, Copenhagen, Madrid, Paris', - 'Africa/Algiers'=>'(GMT+01:00) West Central Africa', - 'Europe/Amsterdam'=>'(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna', - 'Africa/Cairo'=>'(GMT+02:00) Cairo', - 'Europe/Helsinki'=>'(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius', - 'Europe/Athens'=>'(GMT+02:00) Athens, Bucharest, Istanbul', - 'Asia/Jerusalem'=>'(GMT+02:00) Jerusalem', - 'Asia/Amman'=>'(GMT+02:00) Amman', - 'Asia/Beirut'=>'(GMT+02:00) Beirut', - 'Africa/Windhoek'=>'(GMT+02:00) Windhoek', - 'Africa/Harare'=>'(GMT+02:00) Harare, Pretoria', - 'Asia/Kuwait'=>'(GMT+03:00) Kuwait, Riyadh', - 'Asia/Baghdad'=>'(GMT+03:00) Baghdad', - 'Europe/Minsk'=>'(GMT+03:00) Minsk', - 'Africa/Nairobi'=>'(GMT+03:00) Nairobi', - 'Asia/Tbilisi'=>'(GMT+03:00) Tbilisi', - 'Asia/Tehran'=>'(GMT+03:30) Tehran', - 'Asia/Muscat'=>'(GMT+04:00) Abu Dhabi, Muscat', - 'Asia/Baku'=>'(GMT+04:00) Baku', - 'Europe/Moscow'=>'(GMT+04:00) Moscow, St. Petersburg, Volgograd', - 'Asia/Yerevan'=>'(GMT+04:00) Yerevan', - 'Asia/Karachi'=>'(GMT+05:00) Islamabad, Karachi', - 'Asia/Tashkent'=>'(GMT+05:00) Tashkent', - 'Asia/Kolkata'=>'(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi', - 'Asia/Colombo'=>'(GMT+05:30) Sri Jayawardenepura', - 'Asia/Katmandu'=>'(GMT+05:45) Kathmandu', - 'Asia/Dhaka'=>'(GMT+06:00) Astana, Dhaka', - 'Asia/Yekaterinburg'=>'(GMT+06:00) Ekaterinburg', - 'Asia/Rangoon'=>'(GMT+06:30) Yangon (Rangoon)', - 'Asia/Novosibirsk'=>'(GMT+07:00) Almaty, Novosibirsk', - 'Asia/Bangkok'=>'(GMT+07:00) Bangkok, Hanoi, Jakarta', - 'Asia/Beijing'=>'(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi', - 'Asia/Ulaanbaatar'=>'(GMT+08:00) Irkutsk, Ulaan Bataar', - 'Asia/Krasnoyarsk'=>'(GMT+08:00) Krasnoyarsk', - 'Asia/Kuala_Lumpur'=>'(GMT+08:00) Kuala Lumpur, Singapore', - 'Asia/Taipei'=>'(GMT+08:00) Taipei', - 'Australia/Perth'=>'(GMT+08:00) Perth', - 'Asia/Seoul'=>'(GMT+09:00) Seoul', - 'Asia/Tokyo'=>'(GMT+09:00) Osaka, Sapporo, Tokyo', - 'Australia/Darwin'=>'(GMT+09:30) Darwin', - 'Australia/Adelaide'=>'(GMT+09:30) Adelaide', - 'Australia/Sydney'=>'(GMT+10:00) Canberra, Melbourne, Sydney', - 'Australia/Brisbane'=>'(GMT+10:00) Brisbane', - 'Australia/Hobart'=>'(GMT+10:00) Hobart', - 'Asia/Yakutsk'=>'(GMT+10:00) Yakutsk', - 'Pacific/Guam'=>'(GMT+10:00) Guam, Port Moresby', - 'Asia/Vladivostok'=>'(GMT+11:00) Vladivostok', - 'Pacific/Fiji'=>'(GMT+12:00) Fiji, Kamchatka, Marshall Is.', - 'Asia/Magadan'=>'(GMT+12:00) Magadan, Solomon Is., New Caledonia', - 'Pacific/Auckland'=>'(GMT+12:00) Auckland, Wellington', - 'Pacific/Tongatapu'=>'(GMT+13:00) Nukualofa' - ); - } - - - /** - * _range() - */ - protected static function _range($step, $start, $end, $flag = false) { - $result = array(); - if ($flag) { - for ($i = $start; $i <= $end; $i += $step) $result[$i] = (string)$i; - } else { - for ($i = $start; $i < $end; $i += $step) $result[$i] = sprintf('%02d', $i); - } - return $result; - } - - } \ No newline at end of file diff --git a/monstra/helpers/debug.php b/monstra/helpers/debug.php deleted file mode 100644 index 71f886f..0000000 --- a/monstra/helpers/debug.php +++ /dev/null @@ -1,124 +0,0 @@ - - * Debug::elapsedTimeSetPoint('point_name'); - * - * - * @param string $point_name Point name - */ - public static function elapsedTimeSetPoint($point_name) { - Debug::$time[$point_name] = microtime(true); - } - - - /** - * Get elapsed time for current point - * - * - * echo Debug::elapsedTime('point_name'); - * - * - * @param string $point_name Point name - * @return string - */ - public static function elapsedTime($point_name) { - if (isset(Debug::$time[$point_name])) return sprintf("%01.4f", microtime(true) - Debug::$time[$point_name]); - } - - - /** - * Save current memory for current point - * - * - * Debug::memoryUsageSetPoint('point_name'); - * - * - * @param string $point_name Point name - */ - public static function memoryUsageSetPoint($point_name) { - Debug::$memory[$point_name] = memory_get_usage(); - } - - - /** - * Get memory usage for current point - * - * - * echo Debug::memoryUsage('point_name'); - * - * - * @param string $point_name Point name - * @return string - */ - public static function memoryUsage($point_name) { - if (isset(Debug::$memory[$point_name])) return Number::byteFormat(memory_get_usage() - Debug::$memory[$point_name]); - } - - - /** - * Print the variable $data and exit if exit = true - * - * - * Debug::dump($data); - * - * - * @param mixed $data Data - * @param boolean $exit Exit - */ - public static function dump($data, $exit = false){ - echo "
    dump \n---------------------- \n\n" . print_r($data, true) . "\n----------------------
    "; - if ($exit) exit; - } - - } \ No newline at end of file diff --git a/monstra/helpers/dir.php b/monstra/helpers/dir.php deleted file mode 100644 index a101102..0000000 --- a/monstra/helpers/dir.php +++ /dev/null @@ -1,215 +0,0 @@ - - * Dir::create('folder1'); - * - * - * @param string $dir Name of directory to create - * @param integer $chmod Chmod - * @return boolean - */ - public static function create($dir, $chmod = 0775) { - - // Redefine vars - $dir = (string) $dir; - - // Create new dir if $dir !exists - return ( ! Dir::exists($dir)) ? @mkdir($dir, $chmod, true) : true; - } - - - /** - * Checks if this directory exists. - * - * - * if (Dir::exists('folder1')) { - * // Do something... - * } - * - * - * @param string $dir Full path of the directory to check. - * @return boolean - */ - public static function exists($dir) { - - // Redefine vars - $dir = (string) $dir; - - // Directory exists - if (file_exists($dir) && is_dir($dir)) return true; - - // Doesn't exist - return false; - } - - - /** - * Check dir permission - * - * - * echo Dir::checkPerm('folder1'); - * - * - * @param string $dir Directory to check - * @return string - */ - public static function checkPerm($dir) { - - // Redefine vars - $dir = (string) $dir; - - // Clear stat cache - clearstatcache(); - - // Return perm - return substr(sprintf('%o', fileperms($dir)), -4); - } - - - /** - * Delete directory - * - * - * Dir::delete('folder1'); - * - * - * @param string $dir Name of directory to delete - */ - public static function delete($dir) { - - // Redefine vars - $dir = (string) $dir; - - // Delete dir - if (is_dir($dir)){$ob=scandir($dir);foreach ($ob as $o){if($o!='.'&&$o!='..'){if(filetype($dir.'/'.$o)=='dir')Dir::delete($dir.'/'.$o); else unlink($dir.'/'.$o);}}} - reset($ob); rmdir($dir); - } - - - /** - * Get list of directories - * - * - * $dirs = Dir::scan('folders'); - * - * - * @param string $dir Directory - */ - public static function scan($dir){ - - // Redefine vars - $dir = (string) $dir; - - // Scan dir - if (is_dir($dir)&&$dh=opendir($dir)){$f=array();while ($fn=readdir($dh)){if($fn!='.'&&$fn!='..'&&is_dir($dir.DS.$fn))$f[]=$fn;}return$f;} - } - - - /** - * Check if a directory is writable. - * - * - * if (Dir::writable('folder1')) { - * // Do something... - * } - * - * - * @param string $path The path to check. - * @return booleans - */ - public static function writable($path) { - - // Redefine vars - $path = (string) $path; - - // Create temporary file - $file = tempnam($path, 'writable'); - - // File has been created - if($file !== false) { - - // Remove temporary file - File::delete($file); - - // Writable - return true; - } - - // Else not writable - return false; - } - - - /** - * Get directory size. - * - * - * echo Dir::size('folder1'); - * - * - * @param string $path The path to directory. - * @return integer - */ - public static function size($path) { - - // Redefine vars - $path = (string) $path; - - $total_size = 0; - $files = scandir($path); - $clean_path = rtrim($path, '/') . '/'; - - foreach ($files as $t) { - if ( $t <> "." && $t <> "..") { - $current_file = $clean_path . $t; - if (is_dir($current_file)) { - $total_size += Dir::size($current_file); - } else { - $total_size += filesize($current_file); - } - } - } - - // Return total size - return $total_size; - } - - } diff --git a/monstra/helpers/file.php b/monstra/helpers/file.php deleted file mode 100644 index eb23942..0000000 --- a/monstra/helpers/file.php +++ /dev/null @@ -1,596 +0,0 @@ - 'audio/aac', - 'atom' => 'application/atom+xml', - 'avi' => 'video/avi', - 'bmp' => 'image/x-ms-bmp', - 'c' => 'text/x-c', - 'class' => 'application/octet-stream', - 'css' => 'text/css', - 'csv' => 'text/csv', - 'deb' => 'application/x-deb', - 'dll' => 'application/x-msdownload', - 'dmg' => 'application/x-apple-diskimage', - 'doc' => 'application/msword', - 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'exe' => 'application/octet-stream', - 'flv' => 'video/x-flv', - 'gif' => 'image/gif', - 'gz' => 'application/x-gzip', - 'h' => 'text/x-c', - 'htm' => 'text/html', - 'html' => 'text/html', - 'ini' => 'text/plain', - 'jar' => 'application/java-archive', - 'java' => 'text/x-java', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'js' => 'text/javascript', - 'json' => 'application/json', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mka' => 'audio/x-matroska', - 'mkv' => 'video/x-matroska', - 'mp3' => 'audio/mpeg', - 'mp4' => 'application/mp4', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'odt' => 'application/vnd.oasis.opendocument.text', - 'ogg' => 'audio/ogg', - 'pdf' => 'application/pdf', - 'php' => 'text/x-php', - 'png' => 'image/png', - 'psd' => 'image/vnd.adobe.photoshop', - 'py' => 'application/x-python', - 'ra' => 'audio/vnd.rn-realaudio', - 'ram' => 'audio/vnd.rn-realaudio', - 'rar' => 'application/x-rar-compressed', - 'rss' => 'application/rss+xml', - 'safariextz' => 'application/x-safari-extension', - 'sh' => 'text/x-shellscript', - 'shtml' => 'text/html', - 'swf' => 'application/x-shockwave-flash', - 'tar' => 'application/x-tar', - 'tif' => 'image/tiff', - 'tiff' => 'image/tiff', - 'torrent' => 'application/x-bittorrent', - 'txt' => 'text/plain', - 'wav' => 'audio/wav', - 'webp' => 'image/webp', - 'wma' => 'audio/x-ms-wma', - 'xls' => 'application/vnd.ms-excel', - 'xml' => 'text/xml', - 'zip' => 'application/zip', - ); - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Returns true if the File exists. - * - * - * if (File::exists('filename.txt')) { - * // Do something... - * } - * - * - * @param string $filename The file name - * @return boolean - */ - public static function exists($filename) { - - // Redefine vars - $filename = (string) $filename; - - // Return - return (file_exists($filename) && is_file($filename)); - } - - - /** - * Delete file - * - * - * File::delete('filename.txt'); - * - * - * @param mixed $filename The file name or array of files - * @return boolean - */ - public static function delete($filename) { - - // Is array - if (is_array($filename)) { - - // Delete each file in $filename array - foreach($filename as $file) { - @unlink((string) $file); - } - - } else { - // Is string - return @unlink((string) $filename); - } - - } - - - /** - * Rename file - * - * - * File::rename('filename1.txt', 'filename2.txt'); - * - * - * @param string $from Original file location - * @param string $to Desitination location of the file - * @return boolean - */ - public static function rename($from, $to) { - - // Redefine vars - $from = (string) $from; - $to = (string) $to; - - // If file exists $to than rename it - if ( ! File::exists($to)) return rename($from, $to); - - // Else return false - return false; - } - - - /** - * Copy file - * - * - * File::copy('folder1/filename.txt', 'folder2/filename.txt'); - * - * - * @param string $from Original file location - * @param string $to Desitination location of the file - * @return boolean - */ - public static function copy($from, $to) { - - // Redefine vars - $from = (string) $from; - $to = (string) $to; - - // If file !exists $from and exists $to then return false - if ( ! File::exists($from) || File::exists($to)) return false; - - // Else copy file - return copy($from, $to); - } - - - /** - * Get the File extension. - * - * - * echo File::ext('filename.txt'); - * - * - * @param string $filename The file name - * @return string - */ - public static function ext($filename){ - - // Redefine vars - $filename = (string) $filename; - - // Return file extension - return substr(strrchr($filename, '.'), 1); - } - - - /** - * Get the File name - * - * - * echo File::name('filename.txt'); - * - * - * @param string $filename The file name - * @return string - */ - public static function name($filename) { - - // Redefine vars - $filename = (string) $filename; - - // Return filename - return basename($filename, '.'.File::ext($filename)); - } - - - /** - * Get list of files in directory recursive - * - * - * $files = File::scan('folder'); - * $files = File::scan('folder', 'txt'); - * $files = File::scan('folder', array('txt', 'log')); - * - * - * @param string $folder Folder - * @param mixed $type Files types - * @return array - */ - public static function scan($folder, $type = null) { - $data = array(); - if (is_dir($folder)) { - $iterator = new RecursiveDirectoryIterator($folder); - foreach (new RecursiveIteratorIterator($iterator) as $file) { - if ($type !== null) { - if (is_array($type)) { - $file_ext = substr(strrchr($file->getFilename(), '.'), 1); - if (in_array($file_ext, $type)) { - if (strpos($file->getFilename(), $file_ext, 1)) { - $data[] = $file->getFilename(); - } - } - } else { - if (strpos($file->getFilename(), $type, 1)) { - $data[] = $file->getFilename(); - } - } - } else { - if ($file->getFilename() !== '.' && $file->getFilename() !== '..') $data[] = $file->getFilename(); - } - } - return $data; - } else { - return false; - } - } - - - /** - * Fetch the content from a file or URL. - * - * - * echo File::getContent('filename.txt'); - * - * - * @param string $filename The file name - * @return boolean - */ - public static function getContent($filename) { - - // Redefine vars - $filename = (string) $filename; - - // If file exists load it - if (File::exists($filename)) { - return file_get_contents($filename); - } - } - - - /** - * Writes a string to a file. - * - * @param string $filename The path of the file. - * @param string $content The content that should be written. - * @param boolean $createFile Should the file be created if it doesn't exists? - * @param boolean $append Should the content be appended if the file already exists? - * @param integer $chmod Mode that should be applied on the file. - * @return boolean - */ - public static function setContent($filename, $content, $create_file = true, $append = false, $chmod = 0666) { - - // Redefine vars - $filename = (string) $filename; - $content = (string) $content; - $create_file = (bool) $create_file; - $append = (bool) $append; - - // File may not be created, but it doesn't exist either - if ( ! $create_file && File::exists($filename)) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' doesn't exist", array(__METHOD__))); - - // Create directory recursively if needed - Dir::create(dirname($filename)); - - // Create file & open for writing - $handler = ($append) ? @fopen($filename, 'a') : @fopen($filename, 'w'); - - // Something went wrong - if ($handler === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__))); - - // Store error reporting level - $level = error_reporting(); - - // Disable errors - error_reporting(0); - - // Write to file - $write = fwrite($handler, $content); - - // Validate write - if($write === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__))); - - // Close the file - fclose($handler); - - // Chmod file - chmod($filename, $chmod); - - // Restore error reporting level - error_reporting($level); - - // Return - return true; - } - - - /** - * Get time(in Unix timestamp) the file was last changed - * - * - * echo File::lastChange('filename.txt'); - * - * - * @param string $filename The file name - * @return boolean - */ - public static function lastChange($filename) { - - // Redefine vars - $filename = (string) $filename; - - // If file exists return filemtime - if (File::exists($filename)) { - return filemtime($filename); - } - - // Return - return false; - - } - - - /** - * Get last access time - * - * - * echo File::lastAccess('filename.txt'); - * - * - * @param string $filename The file name - * @return boolean - */ - public static function lastAccess($filename) { - - // Redefine vars - $filename = (string) $filename; - - // If file exists return fileatime - if (File::exists($filename)) { - return fileatime($filename); - } - - // Return - return false; - } - - - /** - * Returns the mime type of a file. Returns false if the mime type is not found. - * - * - * echo File::mime('filename.txt'); - * - * - * @param string $file Full path to the file - * @param boolean $guess Set to false to disable mime type guessing - * @return string - */ - public static function mime($file, $guess = true) { - - // Redefine vars - $file = (string) $file; - $guess = (bool) $guess; - - // Get mime using the file information functions - if (function_exists('finfo_open')) { - - $info = finfo_open(FILEINFO_MIME_TYPE); - - $mime = finfo_file($info, $file); - - finfo_close($info); - - return $mime; - - } else { - - // Just guess mime by using the file extension - if ($guess === true) { - - $mime_types = File::$mime_types; - - $extension = pathinfo($file, PATHINFO_EXTENSION); - - return isset($mime_types[$extension]) ? $mime_types[$extension] : false; - } else { - return false; - } - } - } - - - /** - * Forces a file to be downloaded. - * - * - * File::download('filename.txt'); - * - * - * @param string $file Full path to file - * @param string $content_type Content type of the file - * @param string $filename Filename of the download - * @param integer $kbps Max download speed in KiB/s - */ - public static function download($file, $content_type = null, $filename = null, $kbps = 0) { - - // Redefine vars - $file = (string) $file; - $content_type = ($content_type === null) ? null : (string) $content_type; - $filename = ($filename === null) ? null : (string) $filename; - $kbps = (int) $kbps; - - // Check that the file exists and that its readable - if (file_exists($file) === false || is_readable($file) === false) { - throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__))); - } - - // Empty output buffers - while (ob_get_level() > 0) ob_end_clean(); - - // Send headers - if ($content_type === null) $content_type = File::mime($file); - - if ($filename === null) $filename = basename($file); - - - header('Content-type: ' . $content_type); - header('Content-Disposition: attachment; filename="' . $filename . '"'); - header('Content-Length: ' . filesize($file)); - - // Read file and write it to the output - @set_time_limit(0); - - if ($kbps === 0) { - - readfile($file); - - } else { - - $handle = fopen($file, 'r'); - - while ( ! feof($handle) && !connection_aborted()) { - - $s = microtime(true); - - echo fread($handle, round($kbps * 1024)); - - if (($wait = 1e6 - (microtime(true) - $s)) > 0) usleep($wait); - - } - - fclose($handle); - } - - exit(); - } - - - /** - * Display a file in the browser. - * - * - * File::display('filename.txt'); - * - * - * @param string $file Full path to file - * @param string $content_type Content type of the file - * @param string $filename Filename of the download - */ - public static function display($file, $content_type = null, $filename = null) { - - // Redefine vars - $file = (string) $file; - $content_type = ($content_type === null) ? null : (string) $content_type; - $filename = ($filename === null) ? null : (string) $filename; - - // Check that the file exists and that its readable - if (file_exists($file) === false || is_readable($file) === false) { - throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__))); - } - - // Empty output buffers - while (ob_get_level() > 0) ob_end_clean(); - - // Send headers - if ($content_type === null) $content_type = File::mime($file); - - if($filename === null) $filename = basename($file); - - header('Content-type: ' . $content_type); - header('Content-Disposition: inline; filename="' . $filename . '"'); - header('Content-Length: ' . filesize($file)); - - // Read file and write to output - readfile($file); - - exit(); - } - - - /** - * Tests whether a file is writable for anyone. - * - * - * if (File::writable('filename.txt')) { - * // do something... - * } - * - * - * @param string $file File to check - * @return boolean - */ - public static function writable($file) { - - // Redefine vars - $file = (string) $file; - - // Is file exists ? - if ( ! file_exists($file)) throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__))); - - // Gets file permissions - $perms = fileperms($file); - - // Is writable ? - if (is_writable($file) || ($perms & 0x0080) || ($perms & 0x0010) || ($perms & 0x0002)) return true; - } - - } \ No newline at end of file diff --git a/monstra/helpers/form.php b/monstra/helpers/form.php deleted file mode 100644 index e6e6538..0000000 --- a/monstra/helpers/form.php +++ /dev/null @@ -1,429 +0,0 @@ - - * - * // Registering a Form macro - * Form::macro('my_field', function() { - * return ''; - * }); - * - * // Calling a custom Form macro - * echo Form::my_field(); - * - * - * // Registering a Form macro with parameters - * Form::macro('my_field', function($value = '') { - * return ''; - * }); - * - * // Calling a custom Form macro with parameters - * echo Form::my_field('Monstra'); - * - * - * - * @param string $name Name - * @param Closure $macro Macro - */ - public static function macro($name, $macro) { - Form::$macros[$name] = $macro; - } - - - /** - * Create an opening HTML form tag. - * - * - * // Form will submit back to the current page using POST - * echo Form::open(); - * - * // Form will submit to 'search' using GET - * echo Form::open('search', array('method' => 'get')); - * - * // When "file" inputs are present, you must include the "enctype" - * echo Form::open(null, array('enctype' => 'multipart/form-data')); - * - * - * @param mixed $action Form action, defaults to the current request URI. - * @param array $attributes HTML attributes. - * @uses Url::base - * @uses Html::attributes - * @return string - */ - public static function open($action = null, array $attributes = null) { - - if ( ! $action) { - - // Submits back to the current url - $action = ''; - - } elseif (strpos($action, '://') === false) { - - // Make the URI absolute - $action = Url::base() . '/' . $action; - } - - // Add the form action to the attributes - $attributes['action'] = $action; - - if ( ! isset($attributes['method'])) { - - // Use POST method - $attributes['method'] = 'post'; - } - - return ''; - } - - - /** - * Create a form input. - * Text is default input type. - * - * - * echo Form::input('username', $username); - * - * - * @param string $name Input name - * @param string $value Input value - * @param array $attributes HTML attributes - * @uses Html::attributes - * @return string - */ - public static function input($name, $value = null, array $attributes = null) { - - // Set the input name - $attributes['name'] = $name; - - // Set the input 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 ''; - } - - - /** - * Create a hidden form input. - * - * - * echo Form::hidden('user_id', $user_id); - * - * - * @param string $name Input name - * @param string $value Input value - * @param array $attributes HTML attributes - * @uses Form::input - * @return string - */ - public static function hidden($name, $value = null, array $attributes = null) { - - // Set the input type - $attributes['type'] = 'hidden'; - - return Form::input($name, $value, $attributes); - } - - - /** - * Creates a password form input. - * - * - * echo Form::password('password'); - * - * - * @param string $name Input name - * @param string $value Input value - * @param array $attributes HTML attributes - * @uses Form::input - * @return string - */ - public static function password($name, $value = null, array $attributes = null) { - - // Set the input type - $attributes['type'] = 'password'; - - return Form::input($name, $value, $attributes); - } - - - /** - * Creates a file upload form input. - * - * - * echo Form::file('image'); - * - * - * @param string $name Input name - * @param array $attributes HTML attributes - * @uses Form::input - * @return string - */ - public static function file($name, array $attributes = null) { - - // Set the input type - $attributes['type'] = 'file'; - - return Form::input($name, null, $attributes); - } - - - /** - * Creates a checkbox form input. - * - * - * echo Form::checkbox('i_am_not_a_robot'); - * - * - * @param string $name Input name - * @param string $input Input value - * @param boolean $checked Checked status - * @param array $attributes HTML attributes - * @uses Form::input - * @return string - */ - public static function checkbox($name, $value = null, $checked = false, array $attributes = null) { - - // Set the input type - $attributes['type'] = 'checkbox'; - - if ($checked === true) { - // Make the checkbox active - $attributes['checked'] = 'checked'; - } - - return Form::input($name, $value, $attributes); - } - - - /** - * Creates a radio form input. - * - * - * echo Form::radio('i_am_not_a_robot'); - * - * - * @param string $name Input name - * @param string $value Input value - * @param boolean $checked Checked status - * @param array $attributes HTML attributes - * @uses Form::input - * @return string - */ - public static function radio($name, $value = null, $checked = null, array $attributes = null) { - - // Set the input type - $attributes['type'] = 'radio'; - - if ($checked === true) { - // Make the radio active - $attributes['checked'] = 'checked'; - } - return Form::input($name, $value, $attributes); - } - - - /** - * Creates a textarea form input. - * - * - * echo Form::textarea('text', $text); - * - * - * @param string $name Name - * @param string $body Body - * @param array $attributes HTML attributes - * @uses Html::attributes - * @return string - */ - public static function textarea($name, $body = '', array $attributes = null) { - - // Set the input name - $attributes['name'] = $name; - - // Set the input id - $attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name; - - return ''.$body.''; - } - - - /** - * Creates a select form input. - * - * - * echo Form::select('themes', array('default', 'classic', 'modern')); - * - * - * @param string $name Name - * @param array $options Options array - * @param string $selected Selected option - * @param array $attributes HTML attributes - * @uses Html::attributes - * @return string - */ - public static function select($name, array $options = null, $selected = null, array $attributes = null) { - - // Set the input name - $attributes['name'] = $name; - - // 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 .= ''; - } - - return ''.$options_output.''; - } - - - /** - * Creates a submit form input. - * - * - * echo Form::submit('save', 'Save'); - * - * - * @param string $name Input name - * @param string $value Input value - * @param array $attributes HTML attributes - * @uses Form::input - * @return string - */ - public static function submit($name, $value, array $attributes = null) { - - // Set the input type - $attributes['type'] = 'submit'; - - return Form::input($name, $value, $attributes); - } - - - /** - * Creates a button form input. - * - * - * echo Form::button('save', 'Save Profile', array('type' => 'submit')); - * - * - * @param string $name Input name - * @param string $value Input value - * @param array $attributes HTML attributes - * @uses Html::attributes - * @return string - */ - public static function button($name, $body, array $attributes = null) { - - // Set the input name - $attributes['name'] = $name; - - return ''.$body.''; - } - - - /** - * Creates a form label. - * - * - * echo Form::label('username', 'Username'); - * - * - * @param string $input Target input - * @param string $text Label text - * @param array $attributes HTML attributes - * @uses Html::attributes - * @return string - */ - public static function label($input, $text, array $attributes = null) { - - // Set the label target - $attributes['for'] = $input; - - return ''.$text.''; - } - - - /** - * Create closing form tag. - * - * - * echo Form::close(); - * - * - * @return string - */ - public static function close() { - return ''; - } - - - /** - * 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."); - } - - } \ No newline at end of file diff --git a/monstra/helpers/html.php b/monstra/helpers/html.php deleted file mode 100644 index 82ecfc0..0000000 --- a/monstra/helpers/html.php +++ /dev/null @@ -1,327 +0,0 @@ - - * - * // Registering a Htmlk macro - * Html::macro('my_element', function() { - * return ''; - * }); - * - * // Calling a custom Html macro - * echo Html::my_element(); - * - * - * // Registering a Html macro with parameters - * Html::macro('my_element', function(id = '') { - * return ''; - * }); - * - * // Calling a custom Html macro with parameters - * echo Html::my_element('monstra'); - * - * - * - * @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. - * - * - * echo Html::chars($username); - * - * - * @param string $value String to convert - * @param boolean $double_encode Encode existing entities - * @return string - */ - public static function chars($value, $double_encode = true) { - return htmlspecialchars((string)$value, ENT_QUOTES, 'utf-8', $double_encode); - } - - - /** - * Compiles an array of HTML attributes into an attribute string. - * Attributes will be sorted using Html::$attribute_order for consistency. - * - * - * echo ''.$content.''; - * - * - * @param array $attributes Attribute list - * @return string - */ - public static function attributes(array $attributes = null) { - - if (empty($attributes)) return ''; - - // Init var - $sorted = array(); - - foreach (Html::$attribute_order as $key) { - - if (isset($attributes[$key])) { - // Add the attribute to the sorted list - $sorted[$key] = $attributes[$key]; - } - - } - - // Combine the sorted attributes - $attributes = $sorted + $attributes; - - $compiled = ''; - foreach ($attributes as $key => $value) { - - if ($value === NULL) { - // Skip attributes that have NULL values - continue; - } - - if (is_int($key)) { - // Assume non-associative keys are mirrored attributes - $key = $value; - } - - // Add the attribute value - $compiled .= ' '.$key.'="'.Html::chars($value).'"'; - } - - return $compiled; - } - - - /** - * Create br tags - * - * - * echo Html::br(2); - * - * - * @param integer $num Count of line break tag - * @return string - */ - public static function br($num = 1) { - return str_repeat("
    ",(int)$num); - } - - - /** - * Create   - * - * - * echo Html::nbsp(2); - * - * - * @param integer $num Count of   - * @return string - */ - public static function nbsp($num = 1) { - return str_repeat(" ", (int)$num); - } - - - /** - * Create an arrow - * - * - * echo Html::arrow('right'); - * - * - * @param string $direction Arrow direction [up,down,left,right] - * @param boolean $render If this option is true then render html object else return it - * @return string - */ - public static function arrow($direction) { - switch ($direction) { - case "up": $output = ''; break; - case "down": $output = ''; break; - case "left": $output = ''; break; - case "right": $output = ''; break; - } - return $output; - } - - - /** - * Create HTML link anchor. - * - * - * echo Html::anchor('About', 'http://sitename.com/about'); - * - * - * @param string $title Anchor title - * @param string $url Anchor url - * @param array $attributes Anchor attributes - * @uses Html::attributes - * @return string - */ - public static function anchor($title, $url = null, array $attributes = null) { - - // Add link - if ($url !== null) $attributes['href'] = $url; - - return ''.$title.''; - } - - - /** - * Create HTML tag - * - * - * echo Html::heading('Title', 1); - * - * - * @param string $title Text - * @param integer $h Number [1-6] - * @param array $attributes Heading attributes - * @uses Html::attributes - * @return string - */ - public static function heading($title, $h = 1, array $attributes = null) { - - $output = ''.$title.''; - - return $output; - } - - - /** - * Generate document type declarations - * - * - * echo Html::doctype('html5'); - * - * - * @param string $type Doctype to generated - * @return mixed - */ - public static function doctype($type = 'html5') { - - $doctypes = array('xhtml11' => '', - 'xhtml1-strict' => '', - 'xhtml1-trans' => '', - 'xhtml1-frame' => '', - 'html5' => '', - 'html4-strict' => '', - 'html4-trans' => '', - 'html4-frame' => ''); - - if (isset($doctypes[$type])) return $doctypes[$type]; else return false; - - } - - - /** - * Create image - * - * - * echo Html::image('data/files/pic1.jpg'); - * - * - * @param array $attributes Image attributes - * @param string $file File - * @uses Url::base - * @return string - */ - public static function image($file, array $attributes = null) { - - if (strpos($file, '://') === FALSE) { - $file = Url::base().'/'.$file; - } - - // Add the image link - $attributes['src'] = $file; - $attributes['alt'] = (isset($attributes['alt'])) ? $attributes['alt'] : pathinfo($file, PATHINFO_FILENAME); - - return ''; - } - - - /** - * Convert html to plain text - * - * - * echo Html::toText('test'); - * - * - * @param string $str String - * @return string - */ - public static function toText($str) { - return htmlspecialchars($str, ENT_QUOTES, 'utf-8'); - } - - - /** - * 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."); - } - - } \ No newline at end of file diff --git a/monstra/helpers/image.php b/monstra/helpers/image.php deleted file mode 100644 index 619df77..0000000 --- a/monstra/helpers/image.php +++ /dev/null @@ -1,673 +0,0 @@ -image_info)) return $this->image_info[$key]; - } - - - /** - * Set value for specific key - * - * @param string $key Key - * @param mixed $value Value - */ - public function __set($key, $value) { - $this->image_info[$key] = $value; - } - - - /** - * Image factory. - * - * - * $image = Image::factory('original.png'); - * - * - * @param string $filename Filename - * @return Image - */ - public static function factory($filename) { - return new Image($filename); - } - - - /** - * Construct - * - * @param string $file Filename - */ - public function __construct($file) { - - // Redefine vars - $file = (string) $file; - - // Check if the file exists - if (file_exists($file)) { - - // Extract attributes of the image file - list($this->width, $this->height, $type, $a) = getimagesize($file); - - // Save image type - $this->type = $type; - - // Create a new image - $this->image = $this->createImage($file, $type); - } else { - throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__))); - } - } - - - /** - * Create a new image from file. - * - * @param string $file Path to the image file - * @param integer $type Image type - * @return resource - */ - protected function createImage($file, $type) { - - // Create image from file - switch($type) { - case IMAGETYPE_JPEG: - return imagecreatefromjpeg($file); - break; - case IMAGETYPE_GIF: - return imagecreatefromgif($file); - break; - case IMAGETYPE_PNG: - return imagecreatefrompng($file); - break; - default: - throw new RuntimeException(vsprintf("%s(): Unable to open '%s'. Unsupported image type.", array(__METHOD__, $type))); - } - } - - - /** - * Resizes the image to the chosen size. - * - * - * Image::factory('original.png')->resize(800, 600)->save('edited.png'); - * - * - * @param integer $width Width of the image - * @param integer $height Height of the image - * @param integer $aspect_ratio Aspect ratio (Image::AUTO Image::WIDTH Image::HEIGHT) - * @return Image - */ - public function resize($width, $height = null, $aspect_ratio = null) { - - // Redefine vars - $width = (int) $width; - $height = ($height === null) ? null : (int) $height; - $aspect_ratio = ($aspect_ratio === null) ? null : (int) $aspect_ratio; - - // Resizes the image to {$width}% of the original size - if ($height === null) { - - $new_width = round($this->width * ($width / 100)); - $new_height = round($this->height * ($width / 100)); - - } else { - - // Resizes the image to the smalles possible dimension while maintaining aspect ratio - if ($aspect_ratio === Image::AUTO) { - - // Calculate smallest size based on given height and width while maintaining aspect ratio - $percentage = min(($width / $this->width), ($height / $this->height)); - - $new_width = round($this->width * $percentage); - $new_height = round($this->height * $percentage); - - // Resizes the image using the width to maintain aspect ratio - } else if ($aspect_ratio === Image::WIDTH) { - - // Base new size on given width while maintaining aspect ratio - $new_width = $width; - $new_height = round($this->height * ($width / $this->width)); - - // Resizes the image using the height to maintain aspect ratio - } else if($aspect_ratio === Image::HEIGHT) { - - // Base new size on given height while maintaining aspect ratio - $new_width = round($this->width * ($height / $this->height)); - $new_height = $height; - - // Resizes the image to a dimension of {$width}x{$height} pixels while ignoring the aspect ratio - } else { - - $new_width = $width; - $new_height = $height; - } - } - - // Create a new true color image width new width and height - $resized = imagecreatetruecolor($new_width, $new_height); - - // Copy and resize part of an image with resampling - imagecopyresampled($resized, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->width, $this->height); - - // Destroy an image - imagedestroy($this->image); - - // Create a new true color image width new width and height - $this->image = imagecreatetruecolor($new_width, $new_height); - - // Copy and resize part of an image with resampling - imagecopyresampled($this->image, $resized, 0, 0, 0, 0, $new_width, $new_height, $new_width, $new_height); - - // Destroy an image - imagedestroy($resized); - - // Save new width and height - $this->width = $new_width; - $this->height = $new_height; - - return $this; - } - - - /** - * Crops the image - * - * - * Image::factory('original.png')->crop(800, 600, 0, 0)->save('edited.png'); - * - * - * @param integer $width Width of the crop - * @param integer $height Height of the crop - * @param integer $x The X coordinate of the cropped region's top left corner - * @param integer $y The Y coordinate of the cropped region's top left corner - * @return Image - */ - public function crop($width, $height, $x, $y) { - - // Redefine vars - $width = (int) $width; - $height = (int) $height; - $x = (int) $x; - $y = (int) $y; - - // Calculate - if ($x + $width > $this->width) $width = $this->width - $x; - if ($y + $height > $this->height) $height = $this->height - $y; - if ($width <= 0 || $height <= 0) return false; - - // Create a new true color image - $crop = imagecreatetruecolor($width, $height); - - // Copy and resize part of an image with resampling - imagecopyresampled($crop, $this->image, 0, 0, $x, $y, $this->width, $this->height, $this->width, $this->height); - - // Destroy an image - imagedestroy($this->image); - - // Create a new true color image - $this->image = imagecreatetruecolor($width, $height); - - // Copy and resize part of an image with resampling - imagecopyresampled($this->image, $crop, 0, 0, 0, 0, $width, $height, $width, $height); - - // Destroy an image - imagedestroy($crop); - - // Save new width and height - $this->width = $width; - $this->height = $height; - - return $this; - } - - - /** - * Adds a watermark to the image. - * - * @param string $file Path to the image file - * @param integer $position Position of the watermark - * @param integer $opacity Opacity of the watermark in percent - * @return Image - */ - public function watermark($file, $position = null, $opacity = 100) { - - // Check if the image exists - if ( ! file_exists($file)) { - throw new RuntimeException(vsprintf("%s(): The image file ('%s') does not exist.", array(__METHOD__, $file))); - } - - $watermark = $this->createImage($file, $this->type); - - $watermarkW = imagesx($watermark); - $watermarkH = imagesy($watermark); - - // Make sure that opacity is between 0 and 100 - $opacity = max(min((int) $opacity, 100), 0); - - if($opacity < 100) { - - if(GD_BUNDLED === 0) { - throw new RuntimeException(vsprintf("%s(): Setting watermark opacity requires the 'imagelayereffect' function which is only available in the bundled version of GD.", array(__METHOD__))); - } - - // Convert alpha to 0-127 - $alpha = min(round(abs(($opacity * 127 / 100) - 127)), 127); - - $transparent = imagecolorallocatealpha($watermark, 0, 0, 0, $alpha); - - imagelayereffect($watermark, IMG_EFFECT_OVERLAY); - - imagefilledrectangle($watermark, 0, 0, $watermarkW, $watermarkH, $transparent); - } - - // Position the watermark. - switch($position) { - case Image::TOP_RIGHT: - $x = imagesx($this->image) - $watermarkW; - $y = 0; - break; - case Image::BOTTOM_LEFT: - $x = 0; - $y = imagesy($this->image) - $watermarkH; - break; - case Image::BOTTOM_RIGHT: - $x = imagesx($this->image) - $watermarkW; - $y = imagesy($this->image) - $watermarkH; - break; - case Image::CENTER: - $x = (imagesx($this->image) / 2) - ($watermarkW / 2); - $y = (imagesy($this->image) / 2) - ($watermarkH / 2); - break; - default: - $x = 0; - $y = 0; - } - - imagealphablending($this->image, true); - - imagecopy($this->image, $watermark, $x, $y, 0, 0, $watermarkW, $watermarkH); - - imagedestroy($watermark); - - // Return Image - return $this; - } - - - /** - * Convert image into grayscale - * - * - * Image::factory('original.png')->grayscale()->save('edited.png'); - * - * - * @return Image - */ - public function grayscale() { - imagefilter($this->image, IMG_FILTER_GRAYSCALE); - return $this; - } - - - /** - * Convert image into sepia - * - * - * Image::factory('original.png')->sepia()->save('edited.png'); - * - * - * @return Image - */ - public function sepia() { - imagefilter($this->image, IMG_FILTER_GRAYSCALE); - imagefilter($this->image, IMG_FILTER_COLORIZE, 112, 66, 20); - return $this; - } - - - /** - * Convert image into brightness - * - * - * Image::factory('original.png')->brightness(60)->save('edited.png'); - * - * - * @param integer $level Level. From -255(min) to 255(max) - * @return Image - */ - public function brightness($level = 0) { - imagefilter($this->image, IMG_FILTER_BRIGHTNESS, (int)$level); - return $this; - } - - - /** - * Convert image into colorize - * - * - * Image::factory('original.png')->colorize(60, 0, 0)->save('edited.png'); - * - * - * @param integer $red Red - * @param integer $green Green - * @param integer $blue Blue - * @return Image - */ - public function colorize($red, $green, $blue) { - imagefilter($this->image, IMG_FILTER_COLORIZE, (int)$red, (int)$green, (int)$blue); - return $this; - } - - - /** - * Convert image into contrast - * - * - * Image::factory('original.png')->contrast(60)->save('edited.png'); - * - * - * @param integer $level Level. From -100(max) to 100(min) note the direction! - * @return Image - */ - public function contrast($level) { - imagefilter($this->image, IMG_FILTER_CONTRAST, (int)$level); - return $this; - } - - - /** - * Creates a color based on a hex value. - * - * @param string $hex Hex code of the color - * @param integer $alpha Alpha. Default is 100 - * @param boolean $returnRGB FALSE returns a color identifier, TRUE returns a RGB array - * @return integer - */ - protected function createColor($hex, $alpha = 100, $return_rgb = false) { - - // Redefine vars - $hex = (string) $hex; - $alpha = (int) $alpha; - $return_rgb = (bool) $return_rgb; - - $hex = str_replace('#', '', $hex); - - if (preg_match('/^([a-f0-9]{3}){1,2}$/i', $hex) === 0) { - throw new RuntimeException(vsprintf("%s(): Invalid color code ('%s').", array(__METHOD__, $hex))); - } - - if (strlen($hex) === 3) { - - $r = hexdec(str_repeat(substr($hex, 0, 1), 2)); - $g = hexdec(str_repeat(substr($hex, 1, 1), 2)); - $b = hexdec(str_repeat(substr($hex, 2, 1), 2)); - - } else { - - $r = hexdec(substr($hex, 0, 2)); - $g = hexdec(substr($hex, 2, 2)); - $b = hexdec(substr($hex, 4, 2)); - - } - - if ($return_rgb === true) { - - return array('r' => $r, 'g' => $g, 'b' => $b); - - } else { - - // Convert alpha to 0-127 - $alpha = min(round(abs(($alpha * 127 / 100) - 127)), 127); - - return imagecolorallocatealpha($this->image, $r, $g, $b, $alpha); - } - } - - - /** - * Rotates the image using the given angle in degrees. - * - * - * Image::factory('original.png')->rotate(90)->save('edited.png'); - * - * - * @param integer $degrees Degrees to rotate the image - * @return Image - */ - public function rotate($degrees) { - - if (GD_BUNDLED === 0) { - throw new RuntimeException(vsprintf("%s(): This method requires the 'imagerotate' function which is only available in the bundled version of GD.", array(__METHOD__))); - } - - // Redefine vars - $degrees = (int) $degrees; - - // Get image width and height - $width = imagesx($this->image); - $height = imagesy($this->image); - - // Allocate a color for an image - $transparent = imagecolorallocatealpha($this->image, 0, 0, 0, 127); - - // Rotate gif image - if ($this->image_info['type'] === IMAGETYPE_GIF) { - - // Create a new true color image - $temp = imagecreatetruecolor($width, $height); - - // Flood fill - imagefill($temp, 0, 0, $transparent); - - // Copy part of an image - imagecopy($temp, $this->image, 0, 0, 0, 0, $width, $height); - - // Destroy an image - imagedestroy($this->image); - - // Save temp image - $this->image = $temp; - } - - // Rotate an image with a given angle - $this->image = imagerotate($this->image, (360 - $degrees), $transparent); - - // Define a color as transparent - imagecolortransparent($this->image, $transparent); - - return $this; - } - - - /** - * Adds a border to the image. - * - * - * Image::factory('original.png')->border('#000', 5)->save('edited.png'); - * - * - * @param string $color Hex code for the color - * @param integer $thickness Thickness of the frame in pixels - * @return Image - */ - public function border($color = '#000', $thickness = 5) { - - // Redefine vars - $color = (string) $color; - $thickness = (int) $thickness; - - // Get image width and height - $width = imagesx($this->image); - $height = imagesy($this->image); - - // Creates a color based on a hex value - $color = $this->createColor($color); - - // Create border - for ($i = 0; $i < $thickness; $i++) { - - if ($i < 0) { - - $x = $width + 1; - $y = $hidth + 1; - - } else { - - $x = --$width; - $y = --$height; - - } - - imagerectangle($this->image, $i, $i, $x, $y, $color); - } - - return $this; - } - - - /** - * Save image - * - * - * Image::factory('original.png')->save('edited.png'); - * - * - * @param string $dest Desitination location of the file - * @param integer $quality Image quality. Default is 100 - * @return Image - */ - public function save($file, $quality = 100) { - - // Redefine vars - $file = (string) $file; - $quality = (int) $quality; - - $path_info = pathinfo($file); - - if ( ! is_writable($path_info['dirname'])) { - throw new RuntimeException(vsprintf("%s(): '%s' is not writable.", array(__METHOD__, $path_info['dirname']))); - } - - // Make sure that quality is between 0 and 100 - $quality = max(min((int) $quality, 100), 0); - - // Save image - switch ($path_info['extension']) { - case 'jpg': - case 'jpeg': - imagejpeg($this->image, $file, $quality); - break; - case 'gif': - imagegif($this->image, $file); - break; - case 'png': - imagealphablending($this->image, true); - imagesavealpha($this->image, true); - imagepng($this->image, $file, (9 - (round(($quality / 100) * 9)))); - break; - default: - throw new RuntimeException(vsprintf("%s(): Unable to save to '%s'. Unsupported image format.", array(__METHOD__, $path_info['extension']))); - } - - // Return Image - return $this; - } - - - /** - * Destructor - */ - public function __destruct() { - imagedestroy($this->image); - } - - } \ No newline at end of file diff --git a/monstra/helpers/inflector.php b/monstra/helpers/inflector.php deleted file mode 100644 index bb5cfc7..0000000 --- a/monstra/helpers/inflector.php +++ /dev/null @@ -1,238 +0,0 @@ - '\1\2en', // ox - '/([m|l])ouse$/' => '\1ice', // mouse, louse - '/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index - '/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address - '/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency - '/(hive)$/' => '\1s', // archive, hive - '/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife - '/sis$/' => 'ses', // basis, diagnosis - '/([ti])um$/' => '\1a', // datum, medium - '/(p)erson$/' => '\1eople', // person, salesperson - '/(m)an$/' => '\1en', // man, woman, spokesman - '/(c)hild$/' => '\1hildren', // child - '/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato - '/(bu|campu)s$/' => '\1\2ses', // bus, campus - '/(alias|status|virus)$/' => '\1es', // alias - '/(octop)us$/' => '\1i', // octopus - '/(ax|cris|test)is$/' => '\1es', // axis, crisis - '/s$/' => 's', // no change (compatibility) - '/$/' => 's', - ); - - - /** - * Singular rules - * - * @var array - */ - protected static $singular_rules = array( - '/(matr)ices$/' => '\1ix', - '/(vert|ind)ices$/' => '\1ex', - '/^(ox)en/' => '\1', - '/(alias)es$/' => '\1', - '/([octop|vir])i$/' => '\1us', - '/(cris|ax|test)es$/' => '\1is', - '/(shoe)s$/' => '\1', - '/(o)es$/' => '\1', - '/(bus|campus)es$/' => '\1', - '/([m|l])ice$/' => '\1ouse', - '/(x|ch|ss|sh)es$/' => '\1', - '/(m)ovies$/' => '\1\2ovie', - '/(s)eries$/' => '\1\2eries', - '/([^aeiouy]|qu)ies$/' => '\1y', - '/([lr])ves$/' => '\1f', - '/(tive)s$/' => '\1', - '/(hive)s$/' => '\1', - '/([^f])ves$/' => '\1fe', - '/(^analy)ses$/' => '\1sis', - '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis', - '/([ti])a$/' => '\1um', - '/(p)eople$/' => '\1\2erson', - '/(m)en$/' => '\1an', - '/(s)tatuses$/' => '\1\2tatus', - '/(c)hildren$/' => '\1\2hild', - '/(n)ews$/' => '\1\2ews', - '/([^us])s$/' => '\1', - ); - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Returns a camelized string from a string using underscore syntax. - * - * - * // "some_text_here" becomes "SomeTextHere" - * echo Inflector::camelize('some_text_here'); - * - * - * @param string $string Word to camelize. - * @return string Camelized word. - */ - public static function camelize($string) { - - // Redefine vars - $string = (string) $string; - - return str_replace(' ', '', ucwords(str_replace('_', ' ', $string))); - } - - - /** - * Returns a string using underscore syntax from a camelized string. - * - * - * // "SomeTextHere" becomes "some_text_here" - * echo Inflector::underscore('SomeTextHere'); - * - * - * @param string $string CamelCased word - * @return string Underscored version of the $string - */ - public static function underscore($string) { - - // Redefine vars - $string = (string) $string; - - return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string)); - } - - - /** - * Returns a humanized string from a string using underscore syntax. - * - * - * // "some_text_here" becomes "Some text here" - * echo Inflector::humanize('some_text_here'); - * - * - * @param string $string String using underscore syntax. - * @return string Humanized version of the $string - */ - public static function humanize($string) { - - // Redefine vars - $string = (string) $string; - - return ucfirst(strtolower(str_replace('_', ' ', $string))); - } - - - /** - * Returns ordinalize number. - * - * - * // 1 becomes 1st - * echo Inflector::ordinalize(1); - * - * - * @param integer $number Number to ordinalize - * @return string - */ - public static function ordinalize($number) { - - if ( ! is_numeric($number)) { - return $number; - } - - if (in_array(($number % 100), range(11, 13))) { - return $number . 'th'; - } else { - switch ($number % 10) { - case 1: return $number . 'st'; break; - case 2: return $number . 'nd'; break; - case 3: return $number . 'rd'; break; - default: return $number . 'th'; break; - } - } - } - - - /** - * Returns the plural version of the given word - * - * - * echo Inflector::pluralize('cat'); - * - * - * @param string $word Word to pluralize - * @return string - */ - public static function pluralize($word) { - - $result = (string) $word; - - foreach (Inflector::$plural_rules as $rule => $replacement) { - if (preg_match($rule, $result)) { - $result = preg_replace($rule, $replacement, $result); - break; - } - } - - return $result; - } - - - /** - * Returns the singular version of the given word - * - * - * echo Inflector::singularize('cats'); - * - * - * @param string $word Word to singularize - * @return string - */ - public static function singularize($word) { - - $result = (string) $word; - - foreach (Inflector::$singular_rules as $rule => $replacement) { - if (preg_match($rule, $result)) { - $result = preg_replace($rule, $replacement, $result); - break; - } - } - - return $result; - } - - } diff --git a/monstra/helpers/minify.php b/monstra/helpers/minify.php deleted file mode 100644 index c90a292..0000000 --- a/monstra/helpers/minify.php +++ /dev/null @@ -1,98 +0,0 @@ - - * echo Minify::html($buffer); - * - * - * @param string $buffer html - * @return string - */ - public static function html($buffer) { - return preg_replace('/^\\s+|\\s+$/m', '', $buffer); - } - - - /** - * Minify css - * - * - * echo Minify::css($buffer); - * - * - * @param string $buffer css - * @return string - */ - public static function css($buffer) { - - // Remove comments - $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); - - // Remove tabs, spaces, newlines, etc. - $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); - - // Preserve empty comment after '>' http://www.webdevout.net/css-hacks#in_css-selectors - $buffer = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $buffer); - - // Preserve empty comment between property and value - // http://css-discuss.incutio.com/?page=BoxModelHack - $buffer = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $buffer); - $buffer = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $buffer); - - // Remove ws around { } and last semicolon in declaration block - $buffer = preg_replace('/\\s*{\\s*/', '{', $buffer); - $buffer = preg_replace('/;?\\s*}\\s*/', '}', $buffer); - - // Remove ws surrounding semicolons - $buffer = preg_replace('/\\s*;\\s*/', ';', $buffer); - - // Remove ws around urls - $buffer = preg_replace('/url\\(\\s*([^\\)]+?)\\s*\\)/x', 'url($1)', $buffer); - - // Remove ws between rules and colons - $buffer = preg_replace('/\\s*([{;])\\s*([\\*_]?[\\w\\-]+)\\s*:\\s*(\\b|[#\'"])/x', '$1$2:$3', $buffer); - - // Minimize hex colors - $buffer = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $buffer); - - // Replace any ws involving newlines with a single newline - $buffer = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $buffer); - - return $buffer; - } - - } \ No newline at end of file diff --git a/monstra/helpers/notification.php b/monstra/helpers/notification.php deleted file mode 100644 index 34bc064..0000000 --- a/monstra/helpers/notification.php +++ /dev/null @@ -1,150 +0,0 @@ - - * echo Notification::get('success'); - * echo Notification::get('errors'); - * - * - * @param string $key Variable name - * @return mixed - */ - public static function get($key) { - - // Redefine arguments - $key = (string) $key; - - // Return specific variable from the Notifications array - return isset(Notification::$notifications[$key]) ? Notification::$notifications[$key] : null; - } - - - /** - * Adds specific variable to the Notifications array. - * - * - * Notification::set('success', 'Data has been saved with success!'); - * Notification::set('errors', 'Data not saved!'); - * - * - * @param string $key Variable name - * @param mixed $value Variable value - */ - public static function set($key, $value) { - - // Redefine arguments - $key = (string) $key; - - // Save specific variable to the Notifications array - $_SESSION[Notification::SESSION_KEY][$key] = $value; - } - - - /** - * Adds specific variable to the Notifications array for current page. - * - * - * Notification::setNow('success', 'Success!'); - * - * - * @param string $var Variable name - * @param mixed $value Variable value - */ - public static function setNow($key, $value) { - - // Redefine arguments - $key = (string) $key; - - // Save specific variable for current page only - Notification::$notifications[$key] = $value; - } - - - /** - * Clears the Notifications array. - * - * - * Notification::clean(); - * - * - * Data that previous pages stored will not be deleted, just the data that - * this page stored itself. - */ - public static function clean() { - $_SESSION[Notification::SESSION_KEY] = array(); - } - - - /** - * Initializes the Notification service. - * - * - * Notification::init(); - * - * - * This will read notification/flash data from the $_SESSION variable and load it into - * the $this->previous array. - */ - public static function init() { - - // Get notification/flash data... - - if ( ! empty($_SESSION[Notification::SESSION_KEY]) && is_array($_SESSION[Notification::SESSION_KEY])) { - Notification::$notifications = $_SESSION[Notification::SESSION_KEY]; - } - - $_SESSION[Notification::SESSION_KEY] = array(); - - } - - } diff --git a/monstra/helpers/number.php b/monstra/helpers/number.php deleted file mode 100644 index 389a367..0000000 --- a/monstra/helpers/number.php +++ /dev/null @@ -1,213 +0,0 @@ - - * echo Number::byteFormat(10000); - * - * - * @param integer $size Data to convert - * @return string - */ - public static function byteFormat($size) { - - // Redefine vars - $size = (int) $size; - - $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb'); - - return @round($size/pow(1024, ($i=floor(log($size, 1024)))), 2).' '.$unit[$i]; - } - - - /** - * Converts a number into a more readable human-type number. - * - * - * echo Number::quantity(7000); // 7K - * echo Number::quantity(7500); // 8K - * echo Number::quantity(7500, 1); // 7.5K - * - * - * @param integer $num Num to convert - * @param integer $decimals Decimals - * @return string - */ - public static function quantity($num, $decimals = 0) { - - // Redefine vars - $num = (int) $num; - $decimals = (int) $decimals; - - if ($num >= 1000 && $num < 1000000) { - return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000)).'K'; - } elseif ($num >= 1000000 && $num < 1000000000) { - return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000)).'M'; - } elseif ($num >= 1000000000) { - return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000000)).'B'; - } - - return $num; - } - - - /** - * Checks if the value is between the minimum and maximum (min & max included). - * - * - * if (Number::between(2, 10, 5)) { - * // do something... - * } - * - * - * @param float $minimum The minimum. - * @param float $maximum The maximum. - * @param float $value The value to validate. - * @return boolean - */ - public static function between($minimum, $maximum, $value) { - return ((float) $value >= (float) $minimum && (float) $value <= (float) $maximum); - } - - - /** - * Checks the value for an even number. - * - * - * if (Number::even(2)) { - * // do something... - * } - * - * - * @param integer $value The value to validate. - * @return boolean - */ - public static function even($value) { - return (((int) $value % 2) == 0); - } - - - /** - * Checks if the value is greather than a given minimum. - * - * - * if (Number::greaterThan(2, 10)) { - * // do something... - * } - * - * - * @param float $minimum The minimum as a float. - * @param float $value The value to validate. - * @return boolean - */ - public static function greaterThan($minimum, $value) { - return ((float) $value > (float) $minimum); - } - - - /** - * Checks if the value is smaller than a given maximum. - * - * - * if (Number::smallerThan(2, 10)) { - * // do something... - * } - * - * - * @param integer $maximum The maximum. - * @param integer $value The value to validate. - * @return boolean - */ - public static function smallerThan($maximum, $value) { - return ((int) $value < (int) $maximum); - } - - - /** - * Checks if the value is not greater than or equal a given maximum. - * - * - * if (Number::maximum(2, 10)) { - * // do something... - * } - * - * - * @param integer $maximum The maximum. - * @param integer $value The value to validate. - * @return boolean - */ - public static function maximum($maximum, $value) { - return ((int) $value <= (int) $maximum); - } - - - /** - * Checks if the value is greater than or equal to a given minimum. - * - * - * if (Number::minimum(2, 10)) { - * // do something... - * } - * - * - * @param integer $minimum The minimum. - * @param integer $value The value to validate. - * @return boolean - */ - public static function minimum($minimum, $value) { - return ((int) $value >= (int) $minimum); - } - - - /** - * Checks the value for an odd number. - * - * - * if (Number::odd(2)) { - * // do something... - * } - * - * - * @param integer $value The value to validate. - * @return boolean - */ - public static function odd($value) { - return ! Number::even((int) $value); - } - - } - - diff --git a/monstra/helpers/orm.php b/monstra/helpers/orm.php deleted file mode 100644 index 005b790..0000000 --- a/monstra/helpers/orm.php +++ /dev/null @@ -1,1141 +0,0 @@ - 'sqlite::memory:', - 'id_column' => 'id', - 'id_column_overrides' => array(), - 'error_mode' => PDO::ERRMODE_EXCEPTION, - 'username' => null, - 'password' => null, - 'driver_options' => null, - 'identifier_quote_character' => null, // if this is null, will be autodetected - 'logging' => false, - 'caching' => false, - ); - - // Database connection, instance of the PDO class - protected static $_db; - - // Last query run, only populated if logging is enabled - protected static $_last_query; - - // Log of all queries run, only populated if logging is enabled - protected static $_query_log = array(); - - // Query cache, only used if query caching is enabled - protected static $_query_cache = array(); - - // --------------------------- // - // --- INSTANCE PROPERTIES --- // - // --------------------------- // - - // The name of the table the current ORM instance is associated with - protected $_table_name; - - // Alias for the table to be used in SELECT queries - protected $_table_alias = null; - - // Values to be bound to the query - protected $_values = array(); - - // Columns to select in the result - protected $_result_columns = array('*'); - - // Are we using the default result column or have these been manually changed? - protected $_using_default_result_columns = true; - - // Join sources - protected $_join_sources = array(); - - // Should the query include a DISTINCT keyword? - protected $_distinct = false; - - // Is this a raw query? - protected $_is_raw_query = false; - - // The raw query - protected $_raw_query = ''; - - // The raw query parameters - protected $_raw_parameters = array(); - - // Array of WHERE clauses - protected $_where_conditions = array(); - - // LIMIT - protected $_limit = null; - - // OFFSET - protected $_offset = null; - - // ORDER BY - protected $_order_by = array(); - - // GROUP BY - protected $_group_by = array(); - - // The data for a hydrated instance of the class - protected $_data = array(); - - // Fields that have been modified during the - // lifetime of the object - protected $_dirty_fields = array(); - - // Is this a new object (has create() been called)? - protected $_is_new = false; - - // Name of the column to use as the primary key for - // this instance only. Overrides the config settings. - protected $_instance_id_column = null; - - // ---------------------- // - // --- STATIC METHODS --- // - // ---------------------- // - - /** - * Pass configuration settings to the class in the form of - * key/value pairs. As a shortcut, if the second argument - * is omitted, the setting is assumed to be the DSN string - * used by PDO to connect to the database. Often, this - * will be the only configuration required to use Idiorm. - */ - public static function configure($key, $value=null) { - // Shortcut: If only one argument is passed, - // assume it's a connection string - if (is_null($value)) { - $value = $key; - $key = 'connection_string'; - } - self::$_config[$key] = $value; - } - - /** - * Despite its slightly odd name, this is actually the factory - * method used to acquire instances of the class. It is named - * this way for the sake of a readable interface, ie - * ORM::for_table('table_name')->find_one()-> etc. As such, - * this will normally be the first method called in a chain. - */ - public static function for_table($table_name) { - self::_setup_db(); - return new self($table_name); - } - - /** - * Set up the database connection used by the class. - */ - protected static function _setup_db() { - if (!is_object(self::$_db)) { - $connection_string = self::$_config['connection_string']; - $username = self::$_config['username']; - $password = self::$_config['password']; - $driver_options = self::$_config['driver_options']; - $db = new PDO($connection_string, $username, $password, $driver_options); - $db->setAttribute(PDO::ATTR_ERRMODE, self::$_config['error_mode']); - self::set_db($db); - } - } - - /** - * Set the PDO object used by Idiorm to communicate with the database. - * This is public in case the ORM should use a ready-instantiated - * PDO object as its database connection. - */ - public static function set_db($db) { - self::$_db = $db; - self::_setup_identifier_quote_character(); - } - - /** - * Detect and initialise the character used to quote identifiers - * (table names, column names etc). If this has been specified - * manually using ORM::configure('identifier_quote_character', 'some-char'), - * this will do nothing. - */ - public static function _setup_identifier_quote_character() { - if (is_null(self::$_config['identifier_quote_character'])) { - self::$_config['identifier_quote_character'] = self::_detect_identifier_quote_character(); - } - } - - /** - * Return the correct character used to quote identifiers (table - * names, column names etc) by looking at the driver being used by PDO. - */ - protected static function _detect_identifier_quote_character() { - switch(self::$_db->getAttribute(PDO::ATTR_DRIVER_NAME)) { - case 'pgsql': - case 'sqlsrv': - case 'dblib': - case 'mssql': - case 'sybase': - return '"'; - case 'mysql': - case 'sqlite': - case 'sqlite2': - default: - return '`'; - } - } - - /** - * Returns the PDO instance used by the the ORM to communicate with - * the database. This can be called if any low-level DB access is - * required outside the class. - */ - public static function get_db() { - self::_setup_db(); // required in case this is called before Idiorm is instantiated - return self::$_db; - } - - /** - * Add a query to the internal query log. Only works if the - * 'logging' config option is set to true. - * - * This works by manually binding the parameters to the query - the - * query isn't executed like this (PDO normally passes the query and - * parameters to the database which takes care of the binding) but - * doing it this way makes the logged queries more readable. - */ - protected static function _log_query($query, $parameters) { - // If logging is not enabled, do nothing - if (!self::$_config['logging']) { - return false; - } - - if (count($parameters) > 0) { - // Escape the parameters - $parameters = array_map(array(self::$_db, 'quote'), $parameters); - - // Replace placeholders in the query for vsprintf - $query = str_replace("?", "%s", $query); - - // Replace the question marks in the query with the parameters - $bound_query = vsprintf($query, $parameters); - } else { - $bound_query = $query; - } - - self::$_last_query = $bound_query; - self::$_query_log[] = $bound_query; - return true; - } - - /** - * Get the last query executed. Only works if the - * 'logging' config option is set to true. Otherwise - * this will return null. - */ - public static function get_last_query() { - return self::$_last_query; - } - - /** - * Get an array containing all the queries run up to - * now. Only works if the 'logging' config option is - * set to true. Otherwise returned array will be empty. - */ - public static function get_query_log() { - return self::$_query_log; - } - - // ------------------------ // - // --- INSTANCE METHODS --- // - // ------------------------ // - - /** - * "Private" constructor; shouldn't be called directly. - * Use the ORM::for_table factory method instead. - */ - protected function __construct($table_name, $data=array()) { - $this->_table_name = $table_name; - $this->_data = $data; - } - - /** - * Create a new, empty instance of the class. Used - * to add a new row to your database. May optionally - * be passed an associative array of data to populate - * the instance. If so, all fields will be flagged as - * dirty so all will be saved to the database when - * save() is called. - */ - public function create($data=null) { - $this->_is_new = true; - if (!is_null($data)) { - return $this->hydrate($data)->force_all_dirty(); - } - return $this; - } - - /** - * Specify the ID column to use for this instance or array of instances only. - * This overrides the id_column and id_column_overrides settings. - * - * This is mostly useful for libraries built on top of Idiorm, and will - * not normally be used in manually built queries. If you don't know why - * you would want to use this, you should probably just ignore it. - */ - public function use_id_column($id_column) { - $this->_instance_id_column = $id_column; - return $this; - } - - /** - * Create an ORM instance from the given row (an associative - * array of data fetched from the database) - */ - protected function _create_instance_from_row($row) { - $instance = self::for_table($this->_table_name); - $instance->use_id_column($this->_instance_id_column); - $instance->hydrate($row); - return $instance; - } - - /** - * Tell the ORM that you are expecting a single result - * back from your query, and execute it. Will return - * a single instance of the ORM class, or false if no - * rows were returned. - * As a shortcut, you may supply an ID as a parameter - * to this method. This will perform a primary key - * lookup on the table. - */ - public function find_one($id=null) { - if (!is_null($id)) { - $this->where_id_is($id); - } - $this->limit(1); - $rows = $this->_run(); - - if (empty($rows)) { - return false; - } - - return $this->_create_instance_from_row($rows[0]); - } - - /** - * Tell the ORM that you are expecting multiple results - * from your query, and execute it. Will return an array - * of instances of the ORM class, or an empty array if - * no rows were returned. - */ - public function find_many() { - $rows = $this->_run(); - return array_map(array($this, '_create_instance_from_row'), $rows); - } - - /** - * Tell the ORM that you wish to execute a COUNT query. - * Will return an integer representing the number of - * rows returned. - */ - public function count() { - $this->select_expr('COUNT(*)', 'count'); - $result = $this->find_one(); - return ($result !== false && isset($result->count)) ? (int) $result->count : 0; - } - - /** - * This method can be called to hydrate (populate) this - * instance of the class from an associative array of data. - * This will usually be called only from inside the class, - * but it's public in case you need to call it directly. - */ - public function hydrate($data=array()) { - $this->_data = $data; - return $this; - } - - /** - * Force the ORM to flag all the fields in the $data array - * as "dirty" and therefore update them when save() is called. - */ - public function force_all_dirty() { - $this->_dirty_fields = $this->_data; - return $this; - } - - /** - * Perform a raw query. The query should contain placeholders, - * in either named or question mark style, and the parameters - * should be an array of values which will be bound to the - * placeholders in the query. If this method is called, all - * other query building methods will be ignored. - */ - public function raw_query($query, $parameters) { - $this->_is_raw_query = true; - $this->_raw_query = $query; - $this->_raw_parameters = $parameters; - return $this; - } - - /** - * Add an alias for the main table to be used in SELECT queries - */ - public function table_alias($alias) { - $this->_table_alias = $alias; - return $this; - } - - /** - * Internal method to add an unquoted expression to the set - * of columns returned by the SELECT query. The second optional - * argument is the alias to return the expression as. - */ - protected function _add_result_column($expr, $alias=null) { - if (!is_null($alias)) { - $expr .= " AS " . $this->_quote_identifier($alias); - } - - if ($this->_using_default_result_columns) { - $this->_result_columns = array($expr); - $this->_using_default_result_columns = false; - } else { - $this->_result_columns[] = $expr; - } - return $this; - } - - /** - * Add a column to the list of columns returned by the SELECT - * query. This defaults to '*'. The second optional argument is - * the alias to return the column as. - */ - public function select($column, $alias=null) { - $column = $this->_quote_identifier($column); - return $this->_add_result_column($column, $alias); - } - - /** - * Add an unquoted expression to the list of columns returned - * by the SELECT query. The second optional argument is - * the alias to return the column as. - */ - public function select_expr($expr, $alias=null) { - return $this->_add_result_column($expr, $alias); - } - - /** - * Add a DISTINCT keyword before the list of columns in the SELECT query - */ - public function distinct() { - $this->_distinct = true; - return $this; - } - - /** - * Internal method to add a JOIN source to the query. - * - * The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this - * will be prepended to JOIN. - * - * The table should be the name of the table to join to. - * - * The constraint may be either a string or an array with three elements. If it - * is a string, it will be compiled into the query as-is, with no escaping. The - * recommended way to supply the constraint is as an array with three elements: - * - * first_column, operator, second_column - * - * Example: array('user.id', '=', 'profile.user_id') - * - * will compile to - * - * ON `user`.`id` = `profile`.`user_id` - * - * The final (optional) argument specifies an alias for the joined table. - */ - protected function _add_join_source($join_operator, $table, $constraint, $table_alias=null) { - - $join_operator = trim("{$join_operator} JOIN"); - - $table = $this->_quote_identifier($table); - - // Add table alias if present - if (!is_null($table_alias)) { - $table_alias = $this->_quote_identifier($table_alias); - $table .= " {$table_alias}"; - } - - // Build the constraint - if (is_array($constraint)) { - list($first_column, $operator, $second_column) = $constraint; - $first_column = $this->_quote_identifier($first_column); - $second_column = $this->_quote_identifier($second_column); - $constraint = "{$first_column} {$operator} {$second_column}"; - } - - $this->_join_sources[] = "{$join_operator} {$table} ON {$constraint}"; - return $this; - } - - /** - * Add a simple JOIN source to the query - */ - public function join($table, $constraint, $table_alias=null) { - return $this->_add_join_source("", $table, $constraint, $table_alias); - } - - /** - * Add an INNER JOIN souce to the query - */ - public function inner_join($table, $constraint, $table_alias=null) { - return $this->_add_join_source("INNER", $table, $constraint, $table_alias); - } - - /** - * Add a LEFT OUTER JOIN souce to the query - */ - public function left_outer_join($table, $constraint, $table_alias=null) { - return $this->_add_join_source("LEFT OUTER", $table, $constraint, $table_alias); - } - - /** - * Add an RIGHT OUTER JOIN souce to the query - */ - public function right_outer_join($table, $constraint, $table_alias=null) { - return $this->_add_join_source("RIGHT OUTER", $table, $constraint, $table_alias); - } - - /** - * Add an FULL OUTER JOIN souce to the query - */ - public function full_outer_join($table, $constraint, $table_alias=null) { - return $this->_add_join_source("FULL OUTER", $table, $constraint, $table_alias); - } - - /** - * Internal method to add a WHERE condition to the query - */ - protected function _add_where($fragment, $values=array()) { - if (!is_array($values)) { - $values = array($values); - } - $this->_where_conditions[] = array( - self::WHERE_FRAGMENT => $fragment, - self::WHERE_VALUES => $values, - ); - return $this; - } - - /** - * Helper method to compile a simple COLUMN SEPARATOR VALUE - * style WHERE condition into a string and value ready to - * be passed to the _add_where method. Avoids duplication - * of the call to _quote_identifier - */ - protected function _add_simple_where($column_name, $separator, $value) { - $column_name = $this->_quote_identifier($column_name); - return $this->_add_where("{$column_name} {$separator} ?", $value); - } - - /** - * Return a string containing the given number of question marks, - * separated by commas. Eg "?, ?, ?" - */ - protected function _create_placeholders($number_of_placeholders) { - return join(", ", array_fill(0, $number_of_placeholders, "?")); - } - - /** - * Add a WHERE column = value clause to your query. Each time - * this is called in the chain, an additional WHERE will be - * added, and these will be ANDed together when the final query - * is built. - */ - public function where($column_name, $value) { - return $this->where_equal($column_name, $value); - } - - /** - * More explicitly named version of for the where() method. - * Can be used if preferred. - */ - public function where_equal($column_name, $value) { - return $this->_add_simple_where($column_name, '=', $value); - } - - /** - * Add a WHERE column != value clause to your query. - */ - public function where_not_equal($column_name, $value) { - return $this->_add_simple_where($column_name, '!=', $value); - } - - /** - * Special method to query the table by its primary key - */ - public function where_id_is($id) { - return $this->where($this->_get_id_column_name(), $id); - } - - /** - * Add a WHERE ... LIKE clause to your query. - */ - public function where_like($column_name, $value) { - return $this->_add_simple_where($column_name, 'LIKE', $value); - } - - /** - * Add where WHERE ... NOT LIKE clause to your query. - */ - public function where_not_like($column_name, $value) { - return $this->_add_simple_where($column_name, 'NOT LIKE', $value); - } - - /** - * Add a WHERE ... > clause to your query - */ - public function where_gt($column_name, $value) { - return $this->_add_simple_where($column_name, '>', $value); - } - - /** - * Add a WHERE ... < clause to your query - */ - public function where_lt($column_name, $value) { - return $this->_add_simple_where($column_name, '<', $value); - } - - /** - * Add a WHERE ... >= clause to your query - */ - public function where_gte($column_name, $value) { - return $this->_add_simple_where($column_name, '>=', $value); - } - - /** - * Add a WHERE ... <= clause to your query - */ - public function where_lte($column_name, $value) { - return $this->_add_simple_where($column_name, '<=', $value); - } - - /** - * Add a WHERE ... IN clause to your query - */ - public function where_in($column_name, $values) { - $column_name = $this->_quote_identifier($column_name); - $placeholders = $this->_create_placeholders(count($values)); - return $this->_add_where("{$column_name} IN ({$placeholders})", $values); - } - - /** - * Add a WHERE ... NOT IN clause to your query - */ - public function where_not_in($column_name, $values) { - $column_name = $this->_quote_identifier($column_name); - $placeholders = $this->_create_placeholders(count($values)); - return $this->_add_where("{$column_name} NOT IN ({$placeholders})", $values); - } - - /** - * Add a WHERE column IS NULL clause to your query - */ - public function where_null($column_name) { - $column_name = $this->_quote_identifier($column_name); - return $this->_add_where("{$column_name} IS NULL"); - } - - /** - * Add a WHERE column IS NOT NULL clause to your query - */ - public function where_not_null($column_name) { - $column_name = $this->_quote_identifier($column_name); - return $this->_add_where("{$column_name} IS NOT NULL"); - } - - /** - * Add a raw WHERE clause to the query. The clause should - * contain question mark placeholders, which will be bound - * to the parameters supplied in the second argument. - */ - public function where_raw($clause, $parameters=array()) { - return $this->_add_where($clause, $parameters); - } - - /** - * Add a LIMIT to the query - */ - public function limit($limit) { - $this->_limit = $limit; - return $this; - } - - /** - * Add an OFFSET to the query - */ - public function offset($offset) { - $this->_offset = $offset; - return $this; - } - - /** - * Add an ORDER BY clause to the query - */ - protected function _add_order_by($column_name, $ordering) { - $column_name = $this->_quote_identifier($column_name); - $this->_order_by[] = "{$column_name} {$ordering}"; - return $this; - } - - /** - * Add an ORDER BY column DESC clause - */ - public function order_by_desc($column_name) { - return $this->_add_order_by($column_name, 'DESC'); - } - - /** - * Add an ORDER BY column ASC clause - */ - public function order_by_asc($column_name) { - return $this->_add_order_by($column_name, 'ASC'); - } - - /** - * Add a column to the list of columns to GROUP BY - */ - public function group_by($column_name) { - $column_name = $this->_quote_identifier($column_name); - $this->_group_by[] = $column_name; - return $this; - } - - /** - * Build a SELECT statement based on the clauses that have - * been passed to this instance by chaining method calls. - */ - protected function _build_select() { - // If the query is raw, just set the $this->_values to be - // the raw query parameters and return the raw query - if ($this->_is_raw_query) { - $this->_values = $this->_raw_parameters; - return $this->_raw_query; - } - - // Build and return the full SELECT statement by concatenating - // the results of calling each separate builder method. - return $this->_join_if_not_empty(" ", array( - $this->_build_select_start(), - $this->_build_join(), - $this->_build_where(), - $this->_build_group_by(), - $this->_build_order_by(), - $this->_build_limit(), - $this->_build_offset(), - )); - } - - /** - * Build the start of the SELECT statement - */ - protected function _build_select_start() { - $result_columns = join(', ', $this->_result_columns); - - if ($this->_distinct) { - $result_columns = 'DISTINCT ' . $result_columns; - } - - $fragment = "SELECT {$result_columns} FROM " . $this->_quote_identifier($this->_table_name); - - if (!is_null($this->_table_alias)) { - $fragment .= " " . $this->_quote_identifier($this->_table_alias); - } - return $fragment; - } - - /** - * Build the JOIN sources - */ - protected function _build_join() { - if (count($this->_join_sources) === 0) { - return ''; - } - - return join(" ", $this->_join_sources); - } - - /** - * Build the WHERE clause(s) - */ - protected function _build_where() { - // If there are no WHERE clauses, return empty string - if (count($this->_where_conditions) === 0) { - return ''; - } - - $where_conditions = array(); - foreach ($this->_where_conditions as $condition) { - $where_conditions[] = $condition[self::WHERE_FRAGMENT]; - $this->_values = array_merge($this->_values, $condition[self::WHERE_VALUES]); - } - - return "WHERE " . join(" AND ", $where_conditions); - } - - /** - * Build GROUP BY - */ - protected function _build_group_by() { - if (count($this->_group_by) === 0) { - return ''; - } - return "GROUP BY " . join(", ", $this->_group_by); - } - - /** - * Build ORDER BY - */ - protected function _build_order_by() { - if (count($this->_order_by) === 0) { - return ''; - } - return "ORDER BY " . join(", ", $this->_order_by); - } - - /** - * Build LIMIT - */ - protected function _build_limit() { - if (!is_null($this->_limit)) { - return "LIMIT " . $this->_limit; - } - return ''; - } - - /** - * Build OFFSET - */ - protected function _build_offset() { - if (!is_null($this->_offset)) { - return "OFFSET " . $this->_offset; - } - return ''; - } - - /** - * Wrapper around PHP's join function which - * only adds the pieces if they are not empty. - */ - protected function _join_if_not_empty($glue, $pieces) { - $filtered_pieces = array(); - foreach ($pieces as $piece) { - if (is_string($piece)) { - $piece = trim($piece); - } - if (!empty($piece)) { - $filtered_pieces[] = $piece; - } - } - return join($glue, $filtered_pieces); - } - - /** - * Quote a string that is used as an identifier - * (table names, column names etc). This method can - * also deal with dot-separated identifiers eg table.column - */ - protected function _quote_identifier($identifier) { - $parts = explode('.', $identifier); - $parts = array_map(array($this, '_quote_identifier_part'), $parts); - return join('.', $parts); - } - - /** - * This method performs the actual quoting of a single - * part of an identifier, using the identifier quote - * character specified in the config (or autodetected). - */ - protected function _quote_identifier_part($part) { - if ($part === '*') { - return $part; - } - $quote_character = self::$_config['identifier_quote_character']; - return $quote_character . $part . $quote_character; - } - - /** - * Create a cache key for the given query and parameters. - */ - protected static function _create_cache_key($query, $parameters) { - $parameter_string = join(',', $parameters); - $key = $query . ':' . $parameter_string; - return sha1($key); - } - - /** - * Check the query cache for the given cache key. If a value - * is cached for the key, return the value. Otherwise, return false. - */ - protected static function _check_query_cache($cache_key) { - if (isset(self::$_query_cache[$cache_key])) { - return self::$_query_cache[$cache_key]; - } - return false; - } - - /** - * Clear the query cache - */ - public static function clear_cache() { - self::$_query_cache = array(); - } - - /** - * Add the given value to the query cache. - */ - protected static function _cache_query_result($cache_key, $value) { - self::$_query_cache[$cache_key] = $value; - } - - /** - * Execute the SELECT query that has been built up by chaining methods - * on this class. Return an array of rows as associative arrays. - */ - protected function _run() { - $query = $this->_build_select(); - $caching_enabled = self::$_config['caching']; - - if ($caching_enabled) { - $cache_key = self::_create_cache_key($query, $this->_values); - $cached_result = self::_check_query_cache($cache_key); - - if ($cached_result !== false) { - return $cached_result; - } - } - - self::_log_query($query, $this->_values); - $statement = self::$_db->prepare($query); - $statement->execute($this->_values); - - $rows = array(); - while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { - $rows[] = $row; - } - - if ($caching_enabled) { - self::_cache_query_result($cache_key, $rows); - } - - return $rows; - } - - /** - * Return the raw data wrapped by this ORM - * instance as an associative array. Column - * names may optionally be supplied as arguments, - * if so, only those keys will be returned. - */ - public function as_array() { - if (func_num_args() === 0) { - return $this->_data; - } - $args = func_get_args(); - return array_intersect_key($this->_data, array_flip($args)); - } - - /** - * Return the value of a property of this object (database row) - * or null if not present. - */ - public function get($key) { - return isset($this->_data[$key]) ? $this->_data[$key] : null; - } - - /** - * Return the name of the column in the database table which contains - * the primary key ID of the row. - */ - protected function _get_id_column_name() { - if (!is_null($this->_instance_id_column)) { - return $this->_instance_id_column; - } - if (isset(self::$_config['id_column_overrides'][$this->_table_name])) { - return self::$_config['id_column_overrides'][$this->_table_name]; - } else { - return self::$_config['id_column']; - } - } - - /** - * Get the primary key ID of this object. - */ - public function id() { - return $this->get($this->_get_id_column_name()); - } - - /** - * Set a property to a particular value on this object. - * Flags that property as 'dirty' so it will be saved to the - * database when save() is called. - */ - public function set($key, $value) { - $this->_data[$key] = $value; - $this->_dirty_fields[$key] = $value; - } - - /** - * Check whether the given field has been changed since this - * object was saved. - */ - public function is_dirty($key) { - return isset($this->_dirty_fields[$key]); - } - - /** - * Save any fields which have been modified on this object - * to the database. - */ - public function save() { - $query = array(); - $values = array_values($this->_dirty_fields); - - if (!$this->_is_new) { // UPDATE - // If there are no dirty values, do nothing - if (count($values) == 0) { - return true; - } - $query = $this->_build_update(); - $values[] = $this->id(); - } else { // INSERT - $query = $this->_build_insert(); - } - - self::_log_query($query, $values); - $statement = self::$_db->prepare($query); - $success = $statement->execute($values); - - // If we've just inserted a new record, set the ID of this object - if ($this->_is_new) { - $this->_is_new = false; - if (is_null($this->id())) { - $this->_data[$this->_get_id_column_name()] = self::$_db->lastInsertId(); - } - } - - $this->_dirty_fields = array(); - return $success; - } - - /** - * Build an UPDATE query - */ - protected function _build_update() { - $query = array(); - $query[] = "UPDATE {$this->_quote_identifier($this->_table_name)} SET"; - - $field_list = array(); - foreach ($this->_dirty_fields as $key => $value) { - $field_list[] = "{$this->_quote_identifier($key)} = ?"; - } - $query[] = join(", ", $field_list); - $query[] = "WHERE"; - $query[] = $this->_quote_identifier($this->_get_id_column_name()); - $query[] = "= ?"; - return join(" ", $query); - } - - /** - * Build an INSERT query - */ - protected function _build_insert() { - $query[] = "INSERT INTO"; - $query[] = $this->_quote_identifier($this->_table_name); - $field_list = array_map(array($this, '_quote_identifier'), array_keys($this->_dirty_fields)); - $query[] = "(" . join(", ", $field_list) . ")"; - $query[] = "VALUES"; - - $placeholders = $this->_create_placeholders(count($this->_dirty_fields)); - $query[] = "({$placeholders})"; - return join(" ", $query); - } - - /** - * Delete this record from the database - */ - public function delete() { - $query = join(" ", array( - "DELETE FROM", - $this->_quote_identifier($this->_table_name), - "WHERE", - $this->_quote_identifier($this->_get_id_column_name()), - "= ?", - )); - $params = array($this->id()); - self::_log_query($query, $params); - $statement = self::$_db->prepare($query); - return $statement->execute($params); - } - - // --------------------- // - // --- MAGIC METHODS --- // - // --------------------- // - public function __get($key) { - return $this->get($key); - } - - public function __set($key, $value) { - $this->set($key, $value); - } - - public function __isset($key) { - return isset($this->_data[$key]); - } - } diff --git a/monstra/helpers/request.php b/monstra/helpers/request.php deleted file mode 100644 index 92d57da..0000000 --- a/monstra/helpers/request.php +++ /dev/null @@ -1,161 +0,0 @@ - - * Request::redirect('test'); - * - * - * @param string $url The URL - * @param integer $status Status - * @param integer $delay Delay - */ - public static function redirect($url, $status = 302, $delay = null){ - - // Redefine vars - $url = (string) $url; - $status = (int) $status; - - // Status codes - $messages = array(); - $messages[301] = '301 Moved Permanently'; - $messages[302] = '302 Found'; - - // Is Headers sent ? - if (headers_sent()) { - - echo "\n"; - - } else { - - // Redirect headers - Request::setHeaders('HTTP/1.1 ' . $status . ' ' . Arr::get($messages, $status, 302)); - - // Delay execution - if ($delay !== null) sleep((int) $delay); - - // Redirect - Request::setHeaders("Location: $url"); - - // Shutdown request - Request::shutdown(); - - } - - } - - - /** - * Set one or multiple headers. - * - * - * Request::setHeaders('Location: http://site.com/'); - * - * - * @param mixed $headers String or array with headers to send. - */ - public static function setHeaders($headers) { - - // Loop elements - foreach ((array) $headers as $header) { - - // Set header - header((string) $header); - - } - - } - - - /** - * Get - * - * - * $action = Request::get('action'); - * - * - * @param string $key Key - * @param mixed - */ - public static function get($key) { - return Arr::get($_GET, $key); - } - - - /** - * Post - * - * - * $login = Request::post('login'); - * - * - * @param string $key Key - * @param mixed - */ - public static function post($key) { - return Arr::get($_POST, $key); - } - - - /** - * Returns whether this is an ajax request or not - * - * - * if (Request::isAjax()) { - * // do something... - * } - * - * - * @return boolean - */ - public static function isAjax() { - return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'; - } - - - /** - * Terminate request - * - * - * Request::shutdown(); - * - * - */ - public static function shutdown() { - exit(0); - } - - } \ No newline at end of file diff --git a/monstra/helpers/response.php b/monstra/helpers/response.php deleted file mode 100644 index a006deb..0000000 --- a/monstra/helpers/response.php +++ /dev/null @@ -1,109 +0,0 @@ - 'Continue', - 101 => 'Switching Protocols', - - // Success 2xx - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authoritative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - - // Redirection 3xx - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', // 1.1 - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - // 306 is deprecated but reserved - 307 => 'Temporary Redirect', - - // Client Error 4xx - 400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - - // Server Error 5xx - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported', - 509 => 'Bandwidth Limit Exceeded' - ); - - - /** - * Protected constructor since this is a static class. - * - * @access protected - */ - protected function __construct() { - // Nothing here - } - - - /** - * Set header status - * - * - * Response::status(404); - * - * - * @param integer $status Status code - */ - public static function status($status) { - if (array_key_exists($status, Response::$messages)) header('HTTP/1.1 ' . $status . ' ' . Response::$messages[$status]); - } - - - } \ No newline at end of file diff --git a/monstra/helpers/security.php b/monstra/helpers/security.php deleted file mode 100644 index 5446ede..0000000 --- a/monstra/helpers/security.php +++ /dev/null @@ -1,250 +0,0 @@ - - * $token = Security::token(); - * - * - * You can insert this token into your forms as a hidden field: - * - * - * echo Form::hidden('csrf', Security::token()); - * - * - * This provides a basic, but effective, method of preventing CSRF attacks. - * - * @param boolean $new force a new token to be generated?. Default is false - * @return string - */ - public static function token($new = false) { - - // Get the current token - $token = Session::get(Security::$token_name); - - // Create a new unique token - if ($new === true or ! $token) { - - // Generate a new unique token - $token = sha1(uniqid(mt_rand(), true)); - - // Store the new token - Session::set(Security::$token_name, $token); - } - - // Return token - return $token; - } - - - /** - * Check that the given token matches the currently stored security token. - * - * - * if (Security::check($token)) { - * // Pass - * } - * - * - * @param string $token token to check - * @return boolean - */ - public static function check($token) { - return Security::token() === $token; - } - - - - /** - * Encrypt password - * - * - * $encrypt_password = Security::encryptPassword('password'); - * - * - * @param string $password Password to encrypt - */ - public static function encryptPassword($password) { - return md5(md5(trim($password) . MONSTRA_PASSWORD_SALT)); - } - - - /** - * Create safe name. Use to create safe username, filename, pagename. - * - * - * $safe_name = Security::safeName('hello world'); - * - * - * @param string $str String - * @param string $delimiter String delimiter - * @param boolean $lowercase String Lowercase - * @return string - */ - public static function safeName($str, $delimiter = '-', $lowercase = false) { - - // Redefine vars - $str = (string) $str; - $delimiter = (string) $delimiter; - $lowercase = (bool) $lowercase; - $delimiter = (string) $delimiter; - - // Remove tags - $str = filter_var($str, FILTER_SANITIZE_STRING); - - // Decode all entities to their simpler forms - $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8'); - - // Reserved characters (RFC 3986) - $reserved_characters = array( - '/', '?', ':', '@', '#', '[', ']', - '!', '$', '&', '\'', '(', ')', '*', - '+', ',', ';', '=' - ); - - // Remove reserved characters - $str = str_replace($reserved_characters, ' ', $str); - - // Set locale to en_US.UTF8 - setlocale(LC_ALL, 'en_US.UTF8'); - - // Translit ua,ru => latin - $str = Text::translitIt($str); - - // Convert string - $str = iconv('UTF-8', 'ASCII//TRANSLIT', $str); - - // Remove characters - $str = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str ); - $str = preg_replace("/[\/_|+ -]+/", $delimiter, $str ); - $str = trim($str, $delimiter); - - // Lowercase - if ($lowercase === true) $str = Text::lowercase($str); - - // Return safe name - return $str; - } - - - /** - * Create safe url. - * - * - * $url = Security::sanitizeURL('http://test.com'); - * - * - * @param string $url Url to sanitize - * @return string - */ - public static function sanitizeURL($url) { - - $url = trim($url); - $url = rawurldecode($url); - $url = str_replace(array('--','"','!','@','#','$','%','^','*','(',')','+','{','}','|',':','"','<','>', - '[',']','\\',';',"'",',','*','+','~','`','laquo','raquo',']>','‘','’','“','”','–','—'), - array('-','-','','','','','','','','','','','','','','','','','','','','','','','','','','',''), - $url); - $url = str_replace('--', '-', $url); - $url = rtrim($url, "-"); - - $url = str_replace('..', '', $url); - $url = str_replace('//', '', $url); - $url = preg_replace('/^\//', '', $url); - $url = preg_replace('/^\./', '', $url); - - return $url; - } - - - /** - * Sanitize URL to prevent XSS - Cross-site scripting - */ - public static function runSanitizeURL() { - $_GET = array_map('Security::sanitizeURL', $_GET); - } - - - /** - * That prevents null characters between ascii characters. - * - * @param string $str String - */ - public static function removeInvisibleCharacters($str) { - - // Redefine vars - $str = (string) $str; - - // Thanks to ci for this tip :) - $non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/'); - - do { - $cleaned = $str; - $str = preg_replace($non_displayables, '', $str); - } while ($cleaned != $str); - - // Return safe string - return $str; - } - - - /** - * Sanitize data to prevent XSS - Cross-site scripting - * - * @param string $str String - */ - public static function xssClean($str) { - - // Remove invisible characters - $str = Security::removeInvisibleCharacters($str); - - // Convert html to plain text - $str = Html::toText($str); - - // Return safe string - return $str; - } - - } diff --git a/monstra/helpers/session.php b/monstra/helpers/session.php deleted file mode 100644 index ed66ab8..0000000 --- a/monstra/helpers/session.php +++ /dev/null @@ -1,197 +0,0 @@ - - * Session::start(); - * - * - */ - public static function start() { - - // Is session already started? - if ( ! session_id()) { - - // Start the session - return @session_start(); - } - - // If already started - return true; - } - - - /** - * Deletes one or more session variables. - * - * - * Session::delete('user'); - * - * - */ - public static function delete() { - - // Loop all arguments - foreach (func_get_args() as $argument) { - - // Array element - if (is_array($argument)) { - - // Loop the keys - foreach ($argument as $key) { - - // Unset session key - unset($_SESSION[(string) $key]); - } - } else { - - // Remove from array - unset($_SESSION[(string) $argument]); - } - } - } - - - /** - * Destroys the session. - * - * - * Session::destroy(); - * - * - */ - public static function destroy() { - - // Destroy - if (session_id()) { - session_unset(); - session_destroy(); - $_SESSION = array(); - } - - } - - - /** - * Checks if a session variable exists. - * - * - * if (Session::exists('user')) { - * // Do something... - * } - * - * - * @return boolean - */ - public static function exists() { - - // Start session if needed - if ( ! session_id()) Session::start(); - - // Loop all arguments - foreach (func_get_args() as $argument) { - - // Array element - if (is_array($argument)) { - - // Loop the keys - foreach ($argument as $key) { - - // Does NOT exist - if ( ! isset($_SESSION[(string) $key])) return false; - } - } else { - - // Does NOT exist - if ( ! isset($_SESSION[(string) $argument])) return false; - } - } - - return true; - } - - - /** - * Gets a variable that was stored in the session. - * - * - * echo Session::get('user'); - * - * - * @param string $key The key of the variable to get. - * @return mixed - */ - public static function get($key) { - - // Start session if needed - if ( ! session_id()) self::start(); - - // Redefine key - $key = (string) $key; - - // Fetch key - if (Session::exists((string) $key)) return $_SESSION[(string) $key]; - - // Key doesn't exist - return null; - } - - - /** - * Returns the sessionID. - * - * - * echo Session::getSessionId(); - * - * - * @return string - */ - public static function getSessionId() { - if ( ! session_id()) Session::start(); - return session_id(); - } - - - /** - * Stores a variable in the session. - * - * - * Session::set('user', 'Awilum'); - * - * - * @param string $key The key for the variable. - * @param mixed $value The value to store. - */ - public static function set($key, $value) { - - // Start session if needed - if ( ! session_id()) self::start(); - - // Set key - $_SESSION[(string) $key] = $value; - } - - } diff --git a/monstra/helpers/text.php b/monstra/helpers/text.php deleted file mode 100644 index 4fad4b8..0000000 --- a/monstra/helpers/text.php +++ /dev/null @@ -1,488 +0,0 @@ - latin - * - * - * echo Text::translitIt('Привет'); - * - * - * @param string $str [ua,ru] string - * @return string $str - */ - public static function translitIt($str) { - - // Redefine vars - $str = (string) $str; - - $patern = array( - "А" => "A", "Б" => "B", "В" => "V", "Г" => "G", - "Д" => "D", "Е" => "E", "Ж" => "J", "З" => "Z", - "И" => "I", "Й" => "Y", "К" => "K", "Л" => "L", - "М" => "M", "Н" => "N", "О" => "O", "П" => "P", - "Р" => "R", "С" => "S", "Т" => "T", "У" => "U", - "Ф" => "F", "Х" => "H", "Ц" => "TS", "Ч" => "CH", - "Ш" => "SH", "Щ" => "SCH", "Ъ" => "", "Ы" => "YI", - "Ь" => "", "Э" => "E", "Ю" => "YU", "Я" => "YA", - "а" => "a", "б" => "b", "в" => "v", "г" => "g", - "д" => "d", "е" => "e", "ж" => "j", "з" => "z", - "и" => "i", "й" => "y", "к" => "k", "л" => "l", - "м" => "m", "н" => "n", "о" => "o","п" => "p", - "р" => "r", "с" => "s", "т" => "t", "у" => "u", - "ф" => "f", "х" => "h", "ц" => "ts", "ч" => "ch", - "ш" => "sh", "щ" => "sch", "ъ" => "y", "ї" => "i", - "Ї" => "Yi", "є" => "ie", "Є" => "Ye", "ы" => "yi", - "ь" => "", "э" => "e", "ю" => "yu", "я" => "ya", "ё" => "yo" - ); - - return strtr($str, $patern); - } - - - /** - * Removes any leading and traling slashes from a string - * - * - * echo Text::trimSlashes('some text here/'); - * - * - * @param string $str String with slashes - * @return string - */ - public static function trimSlashes($str) { - - // Redefine vars - $str = (string) $str; - - return trim($str, '/'); - } - - - /** - * Removes slashes contained in a string or in an array - * - * - * echo Text::strpSlashes('some \ text \ here'); - * - * - * @param 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 - * - * - * echo Text::stripQuotes('some "text" here'); - * - * - * @param string $str String with single and double quotes - * @return string - */ - public static function stripQuotes($str) { - - // Redefine vars - $str = (string) $str; - - return str_replace(array('"', "'"), '', $str); - } - - - /** - * Convert single and double quotes to entities - * - * - * echo Text::quotesToEntities('some "text" here'); - * - * - * @param string $str String with single and double quotes - * @return string - */ - public static function quotesToEntities($str) { - - // Redefine vars - $str = (string) $str; - - return str_replace(array("\'", "\"", "'", '"'), array("'", """, "'", """), $str); - } - - - /** - * Creates a random string of characters - * - * - * echo Text::random(); - * - * - * @param string $type The type of string. Default is 'alnum' - * @param integer $length The number of characters. Default is 16 - * @return string - */ - public static function random($type = 'alnum', $length = 16) { - - // Redefine vars - $type = (string) $type; - $length = (int) $length; - - switch($type) { - - case 'basic': - return mt_rand(); - break; - - default: - case 'alnum': - case 'numeric': - case 'nozero': - case 'alpha': - case 'distinct': - case 'hexdec': - switch ($type) { - case 'alpha': - $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - break; - - default: - case 'alnum': - $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - break; - - case 'numeric': - $pool = '0123456789'; - break; - - case 'nozero': - $pool = '123456789'; - break; - - case 'distinct': - $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; - break; - - case 'hexdec': - $pool = '0123456789abcdef'; - break; - } - - $str = ''; - for ($i=0; $i < $length; $i++) { - $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); - } - return $str; - break; - - case 'unique': - return md5(uniqid(mt_rand())); - break; - - case 'sha1' : - return sha1(uniqid(mt_rand(), true)); - break; - } - } - - - /** - * Add's _1 to a string or increment the ending number to allow _2, _3, etc - * - * - * $str = Text::increment($str); - * - * - * @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 - * - * - * echo Text::cut('Some text here', 5); - * - * - * @param string $str Input string - * @param integer $length Length after cut - * @param string $cut_msg Message after cut string - * @return string - */ - public static function cut($str, $length, $cut_msg = null) { - - // Redefine vars - $str = (string) $str; - $length = (int) $length; - - if (isset($cut_msg)) $msg = $cut_msg; else $msg = '...'; - - return function_exists('mb_substr') ? mb_substr($str, 0, $length, 'utf-8') . $msg : substr($str, 0, $length) . $msg; - } - - - /** - * Lowercase - * - * - * echo Text::lowercase('Some text here'); - * - * - * @param string $str String - * @return string - */ - public static function lowercase($str) { - - // Redefine vars - $str = (string) $str; - - return function_exists('mb_strtolower') ? mb_strtolower($str, 'utf-8') : strtolower($str); - } - - - /** - * Uppercase - * - * - * echo Text::uppercase('some text here'); - * - * - * @param string $str String - * @return string - */ - public static function uppercase($str) { - - // Redefine vars - $str = (string) $str; - - return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'utf-8') : strtoupper($str); - } - - - /** - * Get length - * - * - * echo Text::length('Some text here'); - * - * - * @param string $str String - * @return string - */ - public static function length($str) { - - // Redefine vars - $str = (string) $str; - - return function_exists('mb_strlen') ? mb_strlen($str, 'utf-8') : strlen($str); - } - - - /** - * Create a lorem ipsum text - * - * - * echo Text::lorem(2); - * - * - * @param integer $num Count - * @return string - */ - public static function lorem($num = 1) { - - // Redefine vars - $num = (int) $num; - - return str_repeat('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', (int)$num); - } - - - /** - * Extract the last `$num` characters from a string. - * - * - * echo Text::right('Some text here', 4); - * - * - * @param string $str The string to extract the characters from. - * @param integer $num The number of characters to extract. - * @return string - */ - public static function right($str, $num){ - - // Redefine vars - $str = (string) $str; - $num = (int) $num; - - return substr($str, Text::length($str)-$num, $num); - } - - - /** - * Extract the first `$num` characters from a string. - * - * - * echo Text::left('Some text here', 4); - * - * - * @param string $str The string to extract the characters from. - * @param integer $num The number of characters to extract. - * @return string - */ - public static function left($str, $num){ - - // Redefine vars - $str = (string) $str; - $num = (int) $num; - - return substr($str, 0, $num); - } - - - /** - * Replaces newline with
    or
    . - * - * - * echo Text::nl2br("Some \n text \n here"); - * - * - * @param string $str The input string - * @param boolean $xhtml Xhtml or not - * @return string - */ - public static function nl2br($str, $xhtml = true) { - - // Redefine vars - $str = (string) $str; - $xhtml = (bool) $xhtml; - - return str_replace(array("\r\n", "\n\r", "\n", "\r"), (($xhtml) ? '
    ' : '
    '), $str); - } - - - /** - * Replaces
    and
    with newline. - * - * - * echo Text::br2nl("Some
    text
    here"); - *
    - * - * @param string $str The input string - * @return string - */ - public static function br2nl($str) { - - // Redefine vars - $str = (string) $str; - - return str_replace(array('
    ', '
    ', '
    '), "\n", $str); - } - - - /** - * Converts & to &. - * - * - * echo Text::ampEncode("M&CMS"); - * - * - * @param string $str The input string - * @return string - */ - public static function ampEncode($str) { - - // Redefine vars - $str = (string) $str; - - return str_replace('&', '&', $str); - } - - - /** - * Converts & to &. - * - * - * echo Text::ampEncode("M&CMS"); - * - * - * @param string $str The input string - * @return string - */ - public static function ampDecode($str) { - - // Redefine vars - $str = (string) $str; - - return str_replace('&', '&', $str); - } - - - /** - * Convert plain text to html - * - * - * echo Text::toHtml('test'); - * - * - * @param string $str String - * @return string - */ - public static function toHtml($str) { - - // Redefine vars - $str = (string) $str; - - return html_entity_decode($str, ENT_QUOTES, 'utf-8'); - } - - } \ No newline at end of file diff --git a/monstra/helpers/uri.php b/monstra/helpers/uri.php deleted file mode 100644 index cf551f9..0000000 --- a/monstra/helpers/uri.php +++ /dev/null @@ -1,171 +0,0 @@ - - * $segments = Uri::segments(); - * - * - * @return array - */ - public static function segments() { - - // Get request uri and current script path - $request_uri = explode('/', $_SERVER['REQUEST_URI']); - $script_name = explode('/', $_SERVER['SCRIPT_NAME']); - - // Delete script name - for ($i = 0; $i < sizeof($script_name); $i++) { - if ($request_uri[$i] == $script_name[$i]) { - unset($request_uri[$i]); - } - } - - // Get all the values of an array - $uri = array_values($request_uri); - - // Ability to pass parameters - foreach ($uri as $i => $u) { - if (isset($uri[$i])) { $pos = strrpos($uri[$i], "?"); if ($pos === false) { $uri[$i] = Security::sanitizeURL($uri[$i]); } else { $uri[$i] = Security::sanitizeURL(substr($uri[$i], 0, $pos)); } } - } - - // Return uri segments - return $uri; - } - - - /** - * Get uri segment - * - * - * $segment = Uri::segment(1); - * - * - * @param integer $segment Segment - * @return mixed - */ - public static function segment($segment) { - $segments = Uri::segments(); - return isset($segments[$segment]) ? $segments[$segment] : null; - } - - - /** - * Get command/component from registed components - * - * - * $command = Uri::command(); - * - * - * @return array - */ - public static function command() { - - // Get uri segments - $uri = Uri::segments(); - - if ( ! isset($uri[0])) { - $uri[0] = Uri::$default_component; - } else { - if ( ! in_array($uri[0], Plugin::$components) ) { - $uri[0] = Uri::$default_component; - } else { - $uri[0] = $uri[0]; - } - } - return $uri[0]; - } - - - /** - * Get uri parammeters - * - * - * $params = Uri::params(); - * - * - * @return array - */ - public static function params() { - - //Init data array - $data = array(); - - // Get URI - $uri = Uri::segments(); - - // http://site.com/ and http://site.com/index.php same main home pages - if ( ! isset($uri[0])) { - $uri[0] = ''; - } - - // param1/param2 - if ($uri[0] !== Uri::$default_component) { - if (isset($uri[1])) { - $data[0] = $uri[0]; - $data[1] = $uri[1]; - // Some more uri parts :) - // site.ru/part1/part2/part3/part4/part5/part6/ - if (isset($uri[2])) $data[2] = $uri[2]; - if (isset($uri[3])) $data[3] = $uri[3]; - if (isset($uri[4])) $data[4] = $uri[4]; - if (isset($uri[5])) $data[5] = $uri[5]; - } else { // default - $data[0] = $uri[0]; - } - } else { - // This is good for box plugin Pages - // parent/child - if (isset($uri[2])) { - $data[0] = $uri[1]; - $data[1] = $uri[2]; - } else { // default - $data[0] = $uri[1]; - } - } - return $data; - } - - } \ No newline at end of file diff --git a/monstra/helpers/url.php b/monstra/helpers/url.php deleted file mode 100644 index 277ff5a..0000000 --- a/monstra/helpers/url.php +++ /dev/null @@ -1,131 +0,0 @@ - - * echo Url::tiny('http:://sitename.com'); - * - * - * @param string $url Long url - * @return string - */ - public static function tiny($url) { - return file_get_contents('http://tinyurl.com/api-create.php?url='.(string)$url); - } - - - /** - * Check is url exists - * - * - * if(Url::exists('http:://sitename.com')) { - * // Do something... - * } - * - * - * @param string $url Url - * @return boolean - */ - public static function exists($url) { - $a_url = parse_url($url); - if ( ! isset($a_url['port'])) $a_url['port'] = 80; - $errno = 0; - $errstr = ''; - $timeout = 30; - if (isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){ - $fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout); - if ( ! $fid) return false; - $page = isset($a_url['path']) ? $a_url['path'] : ''; - $page .= isset($a_url['query']) ? '?'.$a_url['query'] : ''; - fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n"); - $head = fread($fid, 4096); - fclose($fid); - return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head); - } else { - return false; - } - } - - - /** - * Find url - * - * - * // Outputs: http://sitename.com/home - * echo Url::find('home'); - * - * - * @global string $site_url Site url - * @param string $url URL - Uniform Resource Locator - * @return string - */ - public static function find($url) { - $https = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://'; - $pos = strpos($url, $https); - if ($pos === false) { $url_output = Option::get('siteurl') . $url; } else { $url_output = $url; } - return $url_output; - } - - - /** - * Gets the base URL - * - * - * echo Url::base(); - * - * - * @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 - * - * - * echo Url::current(); - * - * - * @return string - */ - public static function current() { - return (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; - } - - } diff --git a/monstra/helpers/valid.php b/monstra/helpers/valid.php deleted file mode 100644 index 61399dc..0000000 --- a/monstra/helpers/valid.php +++ /dev/null @@ -1,208 +0,0 @@ - - * if (Valid::email('test@test.com')) { - * // Do something... - * } - * - * - * @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. - * - * - * if (Valid::ip('127.0.0.1') || Valid::ip('0:0:0:0:0:0:7f00:1')) { - * // Do something... - * } - * - * - * @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. - * - * - * if (Valid::creditCard(7711111111111111, 'Visa')) { - * // Do something... - * } - * - * - * @param integer $num Credit card num - * @param string $type Credit card type: - * American - American Express - * Dinners - Diner's Club - * Discover - Discover Card - * Master - Mastercard - * Visa - Visa - * @return boolean - */ - public static function creditCard($num, $type) { - - // Redefine vars - $num = (int) $num; - $type = (string) $type; - - switch($type) { - case "American": return (bool) preg_match("/^([34|37]{2})([0-9]{13})$/", $num); - case "Dinners": return (bool) preg_match("/^([30|36|38]{2})([0-9]{12})$/", $num); - case "Discover": return (bool) preg_match("/^([6011]{4})([0-9]{12})$/", $num); - case "Master": return (bool) preg_match("/^([51|52|53|54|55]{2})([0-9]{14})$/", $num); - case "Visa": return (bool) preg_match("/^([4]{1})([0-9]{12,15})$/", $num); - } - } - - - /** - * Check an phone number for correct format. - * - * - * if (Valid::phone(0661111117)) { - * // Do something... - * } - * - * - * @param string $num Phone number - * @return boolean - */ - public static function phone($num) { - return (bool) preg_match("/^([0-9\(\)\/\+ \-]*)$/", (string)$num); - } - - - /** - * Check an url for correct format. - * - * - * if (Valid::url('http://site.com/')) { - * // Do something... - * } - * - * - * @param string $url Url - * @return boolean - */ - public static function url($url) { - return (bool) filter_var((string)$url, FILTER_VALIDATE_URL); - } - - - /** - * Check an date for correct format. - * - * - * if (Valid::date('12/12/12')) { - * // Do something... - * } - * - * - * @param string $str Date - * @return boolean - */ - public static function date($str) { - return (strtotime($str) !== false); - } - - - /** - * Checks whether a string consists of digits only (no dots or dashes). - * - * - * if (Valid::digit('12')) { - * // Do something... - * } - * - * - * @param string $str String - * @return boolean - */ - public static function digit($str) { - return (bool) preg_match ("/[^0-9]/", $str); - } - - - /** - * Checks whether a string is a valid number (negative and decimal numbers allowed). - * - * - * if (Valid::numeric('3.14')) { - * // Do something... - * } - * - * - * Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion} - * to allow decimal point to be locale specific. - * - * @param string $str String - * @return boolean - */ - public static function numeric($str) { - $locale = localeconv(); - return (bool) preg_match('/^-?[0-9'.$locale['decimal_point'].']++$/D', (string)$str); - } - - - /** - * Checks if the given regex statement is valid. - * - * @param string $regexp The value to validate. - * @return boolean - */ - public static function regexp($regexp) { - - // dummy string - $dummy = 'Monstra - fast and simple cms'; - - // validate - return (@preg_match((string) $regexp, $dummy) !== false); - - } - - } \ No newline at end of file diff --git a/monstra/helpers/zip.php b/monstra/helpers/zip.php deleted file mode 100644 index 89b78c6..0000000 --- a/monstra/helpers/zip.php +++ /dev/null @@ -1,385 +0,0 @@ -now = time(); - } - - - /** - * Zip factory - * - * - * Zip::factory(); - * - * - * @return Zip - */ - public static function factory() { - return new Zip(); - } - - - /** - * Add Directory - * - * - * Zip::factory()->addDir('test'); - * - * - * @param mixed $directory The directory name. Can be string or array - */ - public function addDir($directory) { - - foreach ((array)$directory as $dir) { - - if ( ! preg_match("|.+/$|", $dir)) { - $dir .= '/'; - } - - $dir_time = $this->_get_mod_time($dir); - - $this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']); - } - - return $this; - } - - - /** - * Get file/directory modification time - * - * @param string $dir Full path to the dir - * @return array - */ - protected function _get_mod_time($dir) { - - // If this is a newly created file/dir, we will set the time to 'now' - $date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now); - - $time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2; - $time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday']; - - return $time; - } - - - /** - * Add Directory - * - * @param string $dir The directory name - * @param integer $file_mtime File mtime - * @param integer $file_mdate File mdate - */ - private function _add_dir($dir, $file_mtime, $file_mdate) { - - $dir = str_replace("\\", "/", $dir); - - $this->zipdata .= - "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00" - .pack('v', $file_mtime) - .pack('v', $file_mdate) - .pack('V', 0) // crc32 - .pack('V', 0) // compressed filesize - .pack('V', 0) // uncompressed filesize - .pack('v', strlen($dir)) // length of pathname - .pack('v', 0) // extra field length - .$dir - // below is "data descriptor" segment - .pack('V', 0) // crc32 - .pack('V', 0) // compressed filesize - .pack('V', 0); // uncompressed filesize - - $this->directory .= - "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00" - .pack('v', $file_mtime) - .pack('v', $file_mdate) - .pack('V',0) // crc32 - .pack('V',0) // compressed filesize - .pack('V',0) // uncompressed filesize - .pack('v', strlen($dir)) // length of pathname - .pack('v', 0) // extra field length - .pack('v', 0) // file comment length - .pack('v', 0) // disk number start - .pack('v', 0) // internal file attributes - .pack('V', 16) // external file attributes - 'directory' bit set - .pack('V', $this->offset) // relative offset of local header - .$dir; - - $this->offset = strlen($this->zipdata); - $this->entries++; - } - - - /** - * Add Data to Zip - * - * - * Zip::factory()->addData('test.txt', 'Some test text here'); - * - * - * Lets you add files to the archive. If the path is included - * in the filename it will be placed within a directory. Make - * sure you use add_dir() first to create the folder. - * - * @param mixed $filepath Full path to the file - * @param string $data Data - */ - public function addData($filepath, $data = null) { - - if (is_array($filepath)) { - foreach ($filepath as $path => $data) { - $file_data = $this->_get_mod_time($path); - $this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']); - } - } else { - $file_data = $this->_get_mod_time($filepath); - $this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']); - } - - return $this; - } - - - /** - * Add Data to Zip - * - * @param string $filepath Full path to the file - * @param string $data The data to be encoded - * @param integer $file_mtime File mtime - * @param integer $file_mdate File mdate - */ - private function _add_data($filepath, $data, $file_mtime, $file_mdate) { - - $filepath = str_replace("\\", "/", $filepath); - - $uncompressed_size = strlen($data); - $crc32 = crc32($data); - - $gzdata = gzcompress($data); - $gzdata = substr($gzdata, 2, -4); - $compressed_size = strlen($gzdata); - - $this->zipdata .= - "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00" - .pack('v', $file_mtime) - .pack('v', $file_mdate) - .pack('V', $crc32) - .pack('V', $compressed_size) - .pack('V', $uncompressed_size) - .pack('v', strlen($filepath)) // length of filename - .pack('v', 0) // extra field length - .$filepath - .$gzdata; // "file data" segment - - $this->directory .= - "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00" - .pack('v', $file_mtime) - .pack('v', $file_mdate) - .pack('V', $crc32) - .pack('V', $compressed_size) - .pack('V', $uncompressed_size) - .pack('v', strlen($filepath)) // length of filename - .pack('v', 0) // extra field length - .pack('v', 0) // file comment length - .pack('v', 0) // disk number start - .pack('v', 0) // internal file attributes - .pack('V', 32) // external file attributes - 'archive' bit set - .pack('V', $this->offset) // relative offset of local header - .$filepath; - - $this->offset = strlen($this->zipdata); - $this->entries++; - $this->file_num++; - } - - - /** - * Read the contents of a file and add it to the zip - * - * - * Zip::factory()->readFile('test.txt'); - * - * - * @param string $path Path - * @param boolean $preserve_filepath Preserve filepath - * @return mixed - */ - function readFile($path, $preserve_filepath = false) { - - if ( ! file_exists($path)) { - return false; - } - - if (false !== ($data = file_get_contents($path))) { - - $name = str_replace("\\", "/", $path); - - if ($preserve_filepath === false) { - $name = preg_replace("|.*/(.+)|", "\\1", $name); - } - - $this->addData($name, $data); - - return $this; - } - - return false; - } - - - /** - * Read a directory and add it to the zip. - * - * - * Zip::factory()->readDir('test/'); - * - * - * This function recursively reads a folder and everything it contains (including - * sub-folders) and creates a zip based on it. Whatever directory structure - * is in the original file path will be recreated in the zip file. - * - * @param string $path Path to source - * @param boolean $preserve_filepath Preserve filepath - * @param string $root_path Root path - * @return mixed - */ - function readDir($path, $preserve_filepath = true, $root_path = null) { - - if ( ! $fp = @opendir($path)) { - return false; - } - - // Set the original directory root for child dir's to use as relative - if ($root_path === null) { - $root_path = dirname($path) . '/'; - } - - while (false !== ($file = readdir($fp))) { - - if (substr($file, 0, 1) == '.') { - continue; - } - - if (@is_dir($path.$file)) { - $this->readDir($path.$file."/", $preserve_filepath, $root_path); - } else { - if (false !== ($data = file_get_contents($path.$file))) { - $name = str_replace("\\", "/", $path); - - if ($preserve_filepath === false) { - $name = str_replace($root_path, '', $name); - } - - $this->addData($name.$file, $data); - } - } - } - - return $this; - } - - - /** - * Get the Zip file - * - * - * Zip::factory()->getZip(); - * - * - * @return string - */ - public function getZip() { - - // Is there any data to return? - if ($this->entries == 0) { - return false; - } - - $zip_data = $this->zipdata; - $zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00"; - $zip_data .= pack('v', $this->entries); // total # of entries "on this disk" - $zip_data .= pack('v', $this->entries); // total # of entries overall - $zip_data .= pack('V', strlen($this->directory)); // size of central dir - $zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir - $zip_data .= "\x00\x00"; // .zip file comment length - - return $zip_data; - } - - - /** - * Write File to the specified directory - * - * - * Zip::factory()->readDir('test1/')->readDir('test2/')->archive('test.zip'); - * - * - * @param string $filepath The file name - * @return boolean - */ - public function archive($filepath) { - - if ( ! ($fp = @fopen($filepath, "w"))) { - return false; - } - - flock($fp, LOCK_EX); - fwrite($fp, $this->getZip()); - flock($fp, LOCK_UN); - fclose($fp); - - return true; - } - - - /** - * Initialize Data - * - * - * Zip::factory()->clearData(); - * - * - * Lets you clear current zip data. Useful if you need to create - * multiple zips with different data. - */ - public function clearData() { - $this->zipdata = ''; - $this->directory = ''; - $this->entries = 0; - $this->file_num = 0; - $this->offset = 0; - } - - } diff --git a/plugins/box/backup/backup.admin.php b/plugins/box/backup/backup.admin.php index d8bae18..410db5b 100755 --- a/plugins/box/backup/backup.admin.php +++ b/plugins/box/backup/backup.admin.php @@ -1,74 +1,73 @@ readDir(STORAGE . DS, false); - $zip = Zip::factory(); + // Add public folder + if (Request::post('add_public_folder')) $zip->readDir(ROOT . DS . 'public' . DS, false); - // Add storage folder - $zip->readDir(STORAGE . DS, false); + // Add plugins folder + if (Request::post('add_plugins_folder')) $zip->readDir(PLUGINS . DS, false); - // Add public folder - if (Request::post('add_public_folder')) $zip->readDir(ROOT . DS . 'public' . DS, false); - - // Add plugins folder - if (Request::post('add_plugins_folder')) $zip->readDir(PLUGINS . DS, false); + $zip->archive($backups_path . DS . Date::format(time(), "Y-m-d-H-i-s").'.zip'); - $zip->archive($backups_path . DS . Date::format(time(), "Y-m-d-H-i-s").'.zip'); - - } else { die('csrf detected!'); } - } - - // Delete backup - // ------------------------------------- - if (Request::get('id') == 'backup' && Request::get('delete_file')) { - - if (Security::check(Request::get('token'))) { - - File::delete($backups_path . DS . Request::get('delete_file')); - Request::redirect(Option::get('siteurl').'admin/index.php?id=backup'); - - } else { die('csrf detected!'); } - } - - // Download backup - // ------------------------------------- - if (Request::get('download')) { - if (Security::check(Request::get('token'))) { - File::download($backups_path . DS . Request::get('download')); - } else { die('csrf detected!'); } - } - - // Get backup list - $backups_list = File::scan($backups_path, '.zip'); - - // Display view - View::factory('box/backup/views/backend/index') - ->assign('backups_list', $backups_list) - ->display(); + } else { die('csrf detected!'); } } - } \ No newline at end of file + + // Delete backup + // ------------------------------------- + if (Request::get('id') == 'backup' && Request::get('delete_file')) { + + if (Security::check(Request::get('token'))) { + + File::delete($backups_path . DS . Request::get('delete_file')); + Request::redirect(Option::get('siteurl').'admin/index.php?id=backup'); + + } else { die('csrf detected!'); } + } + + // Download backup + // ------------------------------------- + if (Request::get('download')) { + if (Security::check(Request::get('token'))) { + File::download($backups_path . DS . Request::get('download')); + } else { die('csrf detected!'); } + } + + // Get backup list + $backups_list = File::scan($backups_path, '.zip'); + + // Display view + View::factory('box/backup/views/backend/index') + ->assign('backups_list', $backups_list) + ->display(); + } +} diff --git a/plugins/box/backup/backup.plugin.php b/plugins/box/backup/backup.plugin.php index fafe560..5970b06 100644 --- a/plugins/box/backup/backup.plugin.php +++ b/plugins/box/backup/backup.plugin.php @@ -1,32 +1,29 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/backup/languages/de.lang.php b/plugins/box/backup/languages/de.lang.php index 5c47903..9d543ed 100644 --- a/plugins/box/backup/languages/de.lang.php +++ b/plugins/box/backup/languages/de.lang.php @@ -1,17 +1,17 @@ - array( - 'Backups' => 'Backups', - 'Backup date' => 'Backup Datum', - 'Create backup' => 'Erstelle Backup', - 'Delete' => 'Löschen', - 'storage' => 'Speicher', - 'public' => 'Öffentliche', - 'plugins' => 'Plugins', - 'Size' => 'Größe', - 'Actions' => 'Aktionen', - 'Delete backup: :backup' => 'Lösche Backup: :backup', - 'Creating...' => 'Erstellen...', - ) - ); \ No newline at end of file + array( + 'Backups' => 'Backups', + 'Backup date' => 'Backup Datum', + 'Create backup' => 'Erstelle Backup', + 'Delete' => 'Löschen', + 'storage' => 'Speicher', + 'public' => 'Öffentliche', + 'plugins' => 'Plugins', + 'Size' => 'Größe', + 'Actions' => 'Aktionen', + 'Delete backup: :backup' => 'Lösche Backup: :backup', + 'Creating...' => 'Erstellen...', + ) + ); diff --git a/plugins/box/backup/languages/en.lang.php b/plugins/box/backup/languages/en.lang.php index 33f5da0..9f275dd 100644 --- a/plugins/box/backup/languages/en.lang.php +++ b/plugins/box/backup/languages/en.lang.php @@ -2,10 +2,10 @@ return array( 'backup' => array( - 'Backups' => 'Backups', + 'Backups' => 'Backups', 'Backup date' => 'Backup date', - 'Create backup' => 'Create backup', - 'Delete' => 'Delete', + 'Create backup' => 'Create backup', + 'Delete' => 'Delete', 'storage' => 'storage', 'public' => 'public', 'plugins' => 'plugins', @@ -14,4 +14,4 @@ 'Delete backup: :backup' => 'Delete backup: :backup', 'Creating...' => 'Creating...', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/backup/languages/it.lang.php b/plugins/box/backup/languages/it.lang.php index c60a6c0..d0942fd 100644 --- a/plugins/box/backup/languages/it.lang.php +++ b/plugins/box/backup/languages/it.lang.php @@ -8,10 +8,10 @@ 'Delete' => 'Elimina', 'storage' => 'dati', 'public' => 'pubblica', - 'plugins' => 'plugin', - 'Size' => 'Dimensione', + 'plugins' => 'plugin', + 'Size' => 'Dimensione', 'Actions' => 'Azioni', 'Delete backup: :backup' => 'Elimina backup: :backup', 'Creating...' => 'Creazione...', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/backup/languages/lt.lang.php b/plugins/box/backup/languages/lt.lang.php index 8221c34..5d87331 100644 --- a/plugins/box/backup/languages/lt.lang.php +++ b/plugins/box/backup/languages/lt.lang.php @@ -14,4 +14,4 @@ 'Delete backup: :backup' => 'Ištrinti: :backup', 'Creating...' => 'Kuriama...', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/backup/languages/pt-br.lang.php b/plugins/box/backup/languages/pt-br.lang.php index cd371e9..476156c 100644 --- a/plugins/box/backup/languages/pt-br.lang.php +++ b/plugins/box/backup/languages/pt-br.lang.php @@ -2,10 +2,10 @@ return array( 'backup' => array( - 'Backups' => 'Backups', + 'Backups' => 'Backups', 'Backup date' => 'Data do backup', - 'Create backup' => 'Criar', - 'Delete' => 'Deletar', + 'Create backup' => 'Criar', + 'Delete' => 'Deletar', 'storage' => 'storage', 'public' => 'public', 'plugins' => 'plugins', @@ -14,4 +14,4 @@ 'Delete backup: :backup' => 'Deletar o backup: :backup', 'Creating...' => 'Criando backup...', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/backup/languages/ru.lang.php b/plugins/box/backup/languages/ru.lang.php index 6c0162f..de2b280 100644 --- a/plugins/box/backup/languages/ru.lang.php +++ b/plugins/box/backup/languages/ru.lang.php @@ -8,10 +8,10 @@ 'Delete' => 'Удалить', 'storage' => 'данные', 'public' => 'публичная', - 'plugins' => 'плагины', - 'Size' => 'Размер', + 'plugins' => 'плагины', + 'Size' => 'Размер', 'Actions' => 'Действия', 'Delete backup: :backup' => 'Удалить бекап: :backup', 'Creating...' => 'Создание...', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/backup/languages/uk.lang.php b/plugins/box/backup/languages/uk.lang.php index 8b0ddc0..b7e318d 100644 --- a/plugins/box/backup/languages/uk.lang.php +++ b/plugins/box/backup/languages/uk.lang.php @@ -8,10 +8,10 @@ 'Delete' => 'Видалити', 'storage' => 'дані', 'public' => 'публічна', - 'plugins' => 'плагіни', - 'Size' => 'Розмір', + 'plugins' => 'плагіни', + 'Size' => 'Розмір', 'Actions' => 'Дії', 'Delete backup: :backup' => 'Видалити бекап: :backup', 'Creating...' => 'Створення...', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/backup/views/backend/index.view.php b/plugins/box/backup/views/backend/index.view.php index eb01a9e..fb4ab08 100755 --- a/plugins/box/backup/views/backend/index.view.php +++ b/plugins/box/backup/views/backend/index.view.php @@ -13,11 +13,11 @@ $().ready(function(){$('[name=create_backup]').click(function(){$(this).button(' Form::hidden('csrf', Security::token()). Form::checkbox('add_storage_folder', null, true, array('disabled' => 'disabled')) . ' ' . __('storage', 'backup') . ' ' . Html::nbsp(2) . Form::checkbox('add_public_folder') . ' ' . __('public', 'backup') . ' ' . Html::nbsp(2) . - Form::checkbox('add_plugins_folder') . ' ' . __('plugins', 'backup') . ' ' . Html::nbsp(2) . + Form::checkbox('add_plugins_folder') . ' ' . __('plugins', 'backup') . ' ' . Html::nbsp(2) . Form::submit('create_backup', __('Create backup', 'backup'), array('class' => 'btn', 'data-loading-text' => __('Creating...', 'backup'))). - Form::close() + Form::close() ); -?> +?> @@ -34,18 +34,18 @@ $().ready(function(){$('[name=create_backup]').click(function(){$(this).button(' + - +
    - +
    'btn btn-small', 'onclick' => "return confirmDelete('".__('Delete backup: :backup', 'backup', array(':backup' => Date::format($name, 'F jS, Y - g:i A')))."')")); ?>
    -
    - \ No newline at end of file + diff --git a/plugins/box/blocks/blocks.admin.php b/plugins/box/blocks/blocks.admin.php index 87ca148..bd92dd7 100755 --- a/plugins/box/blocks/blocks.admin.php +++ b/plugins/box/blocks/blocks.admin.php @@ -1,149 +1,146 @@ :name have been saved.', 'blocks', array(':name' => Security::safeName(Request::post('name'))))); + if (count($errors) == 0) { - if (Request::post('add_blocks_and_exit')) { - Request::redirect('index.php?id=blocks'); - } else { - Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name'))); - } + // Save block + File::setContent($blocks_path.Security::safeName(Request::post('name')).'.block.html', XML::safe(Request::post('editor'))); + + Notification::set('success', __('Your changes to the block :name have been saved.', 'blocks', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_blocks_and_exit')) { + Request::redirect('index.php?id=blocks'); + } else { + Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name'))); } + } - } else { die('csrf detected!'); } - } - - // Save fields - if (Request::post('name')) $name = Request::post('name'); else $name = ''; - if (Request::post('editor')) $content = Request::post('editor'); else $content = ''; - - // Display view - View::factory('box/blocks/views/backend/add') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->display(); - break; + } else { die('csrf detected!'); } + } - // Edit block - // ------------------------------------- - case "edit_block": - // Save current block action - if (Request::post('edit_blocks') || Request::post('edit_blocks_and_exit') ) { + // Save fields + if (Request::post('name')) $name = Request::post('name'); else $name = ''; + if (Request::post('editor')) $content = Request::post('editor'); else $content = ''; - if (Security::check(Request::post('csrf'))) { + // Display view + View::factory('box/blocks/views/backend/add') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->display(); + break; - if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('Required field', 'blocks'); - if ((file_exists($blocks_path.Security::safeName(Request::post('name')).'.block.html')) and (Security::safeName(Request::post('blocks_old_name')) !== Security::safeName(Request::post('name')))) $errors['blocks_exists'] = __('This block already exists', 'blocks'); + // Edit block + // ------------------------------------- + case "edit_block": + // Save current block action + if (Request::post('edit_blocks') || Request::post('edit_blocks_and_exit') ) { - // Save fields - if (Request::post('editor')) $content = Request::post('editor'); else $content = ''; - if (count($errors) == 0) { + if (Security::check(Request::post('csrf'))) { - $block_old_filename = $blocks_path.Request::post('blocks_old_name').'.block.html'; - $block_new_filename = $blocks_path.Security::safeName(Request::post('name')).'.block.html'; - if ( ! empty($block_old_filename)) { - if ($block_old_filename !== $block_new_filename) { - rename($block_old_filename, $block_new_filename); - $save_filename = $block_new_filename; - } else { - $save_filename = $block_new_filename; - } + if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('Required field', 'blocks'); + if ((file_exists($blocks_path.Security::safeName(Request::post('name')).'.block.html')) and (Security::safeName(Request::post('blocks_old_name')) !== Security::safeName(Request::post('name')))) $errors['blocks_exists'] = __('This block already exists', 'blocks'); + + // Save fields + if (Request::post('editor')) $content = Request::post('editor'); else $content = ''; + if (count($errors) == 0) { + + $block_old_filename = $blocks_path.Request::post('blocks_old_name').'.block.html'; + $block_new_filename = $blocks_path.Security::safeName(Request::post('name')).'.block.html'; + if ( ! empty($block_old_filename)) { + if ($block_old_filename !== $block_new_filename) { + rename($block_old_filename, $block_new_filename); + $save_filename = $block_new_filename; } else { $save_filename = $block_new_filename; } - - // Save block - File::setContent($save_filename, XML::safe(Request::post('editor'))); - - Notification::set('success', __('Your changes to the block :name have been saved.', 'blocks', array(':name' => basename($save_filename, '.block.html')))); - - if (Request::post('edit_blocks_and_exit')) { - Request::redirect('index.php?id=blocks'); - } else { - Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name'))); - } + } else { + $save_filename = $block_new_filename; } - } else { die('csrf detected!'); } - } - if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); - if (Request::post('editor')) $content = Request::post('editor'); else $content = File::getContent($blocks_path.Request::get('filename').'.block.html'); + // Save block + File::setContent($save_filename, XML::safe(Request::post('editor'))); - - // Display view - View::factory('box/blocks/views/backend/edit') - ->assign('content', Text::toHtml($content)) - ->assign('name', $name) - ->assign('errors', $errors) - ->display(); - break; - case "delete_block": + Notification::set('success', __('Your changes to the block :name have been saved.', 'blocks', array(':name' => basename($save_filename, '.block.html')))); - if (Security::check(Request::get('token'))) { + if (Request::post('edit_blocks_and_exit')) { + Request::redirect('index.php?id=blocks'); + } else { + Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name'))); + } + } - File::delete($blocks_path.Request::get('filename').'.block.html'); - Notification::set('success', __('Block :name deleted', 'blocks', array(':name' => File::name(Request::get('filename'))))); - Request::redirect('index.php?id=blocks'); + } else { die('csrf detected!'); } + } + if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); + if (Request::post('editor')) $content = Request::post('editor'); else $content = File::getContent($blocks_path.Request::get('filename').'.block.html'); - } else { die('csrf detected!'); } - - break; - } - } else { + // Display view + View::factory('box/blocks/views/backend/edit') + ->assign('content', Text::toHtml($content)) + ->assign('name', $name) + ->assign('errors', $errors) + ->display(); + break; + case "delete_block": + if (Security::check(Request::get('token'))) { - // Get blocks - $blocks_list = File::scan($blocks_path, '.block.html'); + File::delete($blocks_path.Request::get('filename').'.block.html'); + Notification::set('success', __('Block :name deleted', 'blocks', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=blocks'); - // Display view - View::factory('box/blocks/views/backend/index') - ->assign('blocks_list', $blocks_list) - ->display(); + } else { die('csrf detected!'); } + break; } + } else { + + // Get blocks + $blocks_list = File::scan($blocks_path, '.block.html'); + + // Display view + View::factory('box/blocks/views/backend/index') + ->assign('blocks_list', $blocks_list) + ->display(); + } - - } \ No newline at end of file + } + +} diff --git a/plugins/box/blocks/blocks.plugin.php b/plugins/box/blocks/blocks.plugin.php index 094456b..2ce30d3 100644 --- a/plugins/box/blocks/blocks.plugin.php +++ b/plugins/box/blocks/blocks.plugin.php @@ -1,118 +1,115 @@ (string) $content, + ); + } } - // Add Plugin Javascript - Javascript::add('plugins/box/blocks/js/blocks.js', 'backend'); - - // Add shortcode {block get="blockname"} - Shortcode::add('block', 'Block::_content'); - - // Add shortcode {block_inline name="blockname"} - Shortcode::add('block_inline', 'Block::_inlineBlock'); - - // Add shortcode {block_inline_create name="blockname"} Block content here {/block_inline_create} - Shortcode::add('block_inline_create', 'Block::_createInlineBlock'); - - /** - * Block Class + * Draw Inline Block */ - class Block { + public static function _inlineBlock($attributes) + { + if (isset($attributes['name']) && isset(Block::$inline_blocks[$attributes['name']])) { + $content = Filter::apply('content', Text::toHtml(Block::$inline_blocks[$attributes['name']]['content'])); + return $content; + } else { + return ''; + } + } - /** - * Inline Blocks - * - * @var array - */ - public static $inline_blocks = array(); + /** + * Get block + * + * @param string $name Block file name + */ + public static function get($name) + { + return Block::_content(array('get' => $name)); + } + /** + * Returns block content for shortcode {block get="blockname"} + * + * @param array $attributes block filename + */ + public static function _content($attributes) + { + if (isset($attributes['get'])) $name = (string) $attributes['get']; else $name = ''; - /** - * Create Inline Block - */ - public static function _createInlineBlock($attributes, $content) { - if (isset($attributes['name'])) { - Block::$inline_blocks[Security::safeName($attributes['name'], '_', true)] = array( - 'content' => (string)$content, - ); + $block_path = STORAGE . DS . 'blocks' . DS . $name . '.block.html'; + + if (File::exists($block_path)) { + ob_start(); + include $block_path; + $block_contents = ob_get_contents(); + ob_end_clean(); + + return Filter::apply('content', Text::toHtml($block_contents)); + } else { + if (Session::exists('admin') && Session::get('admin') == true) { + return __('Block :name is not found!', 'blocks', array(':name' => $name)); } } - - - /** - * Draw Inline Block - */ - public static function _inlineBlock($attributes) { - if (isset($attributes['name']) && isset(Block::$inline_blocks[$attributes['name']])) { - $content = Filter::apply('content', Text::toHtml(Block::$inline_blocks[$attributes['name']]['content'])); - return $content; - } else { - return ''; - } - } - - - /** - * Get block - * - * @param string $name Block file name - */ - public static function get($name) { - return Block::_content(array('get' => $name)); - } - - - /** - * Returns block content for shortcode {block get="blockname"} - * - * @param array $attributes block filename - */ - public static function _content($attributes) { - - if (isset($attributes['get'])) $name = (string)$attributes['get']; else $name = ''; - - $block_path = STORAGE . DS . 'blocks' . DS . $name . '.block.html'; - - if (File::exists($block_path)) { - ob_start(); - include $block_path; - $block_contents = ob_get_contents(); - ob_end_clean(); - return Filter::apply('content', Text::toHtml($block_contents)); - } else { - if (Session::exists('admin') && Session::get('admin') == true) { - return __('Block :name is not found!', 'blocks', array(':name' => $name)); - } - } - } - } \ No newline at end of file + } +} diff --git a/plugins/box/blocks/install/blocks.manifest.xml b/plugins/box/blocks/install/blocks.manifest.xml index 001ca2c..562be0d 100644 --- a/plugins/box/blocks/install/blocks.manifest.xml +++ b/plugins/box/blocks/install/blocks.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/blocks/languages/de.lang.php b/plugins/box/blocks/languages/de.lang.php index d513e18..f46790c 100644 --- a/plugins/box/blocks/languages/de.lang.php +++ b/plugins/box/blocks/languages/de.lang.php @@ -1,29 +1,29 @@ - array( - 'Blocks' => 'Blöcke', - 'Blocks manager' => 'Block-Manager', - 'Delete' => 'Löschen', - 'Edit' => 'Bearbeiten', - 'Name' => 'Name', - 'Create new block' => 'Erstelle einen neuen Block', - 'New block' => 'Neuer Block', - 'Edit block' => 'Bearbeite Block', - 'Save' => 'Save', - 'Save and exit' => 'Speichern und Schließen', - 'Actions' => 'Aktionen', - 'Required field' => 'Erforderliches Feld', - 'This block already exists' => 'Dieser Block existiert bereits', - 'This block does not exist' => 'Dieser Block existiert nicht', - 'Delete block: :block' => 'Lösche Block: :block', - 'Block content' => 'Block-Inhalt', - 'Block :name deleted' => 'Block :name gelöscht', - 'Your changes to the block :name have been saved.' => 'Deine Änderungen für den Block :name wurden übernommen.', - 'Delete block: :block' => 'Lösche Block: :block', - 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', - 'Shortcode' => 'Shortcode', - 'PHP Code' => 'PHP Code', - ) - ); \ No newline at end of file + array( + 'Blocks' => 'Blöcke', + 'Blocks manager' => 'Block-Manager', + 'Delete' => 'Löschen', + 'Edit' => 'Bearbeiten', + 'Name' => 'Name', + 'Create new block' => 'Erstelle einen neuen Block', + 'New block' => 'Neuer Block', + 'Edit block' => 'Bearbeite Block', + 'Save' => 'Save', + 'Save and exit' => 'Speichern und Schließen', + 'Actions' => 'Aktionen', + 'Required field' => 'Erforderliches Feld', + 'This block already exists' => 'Dieser Block existiert bereits', + 'This block does not exist' => 'Dieser Block existiert nicht', + 'Delete block: :block' => 'Lösche Block: :block', + 'Block content' => 'Block-Inhalt', + 'Block :name deleted' => 'Block :name gelöscht', + 'Your changes to the block :name have been saved.' => 'Deine Änderungen für den Block :name wurden übernommen.', + 'Delete block: :block' => 'Lösche Block: :block', + 'View Embed Code' => 'View Embed Code', + 'Embed Code' => 'Embed Code', + 'Shortcode' => 'Shortcode', + 'PHP Code' => 'PHP Code', + ) + ); diff --git a/plugins/box/blocks/languages/en.lang.php b/plugins/box/blocks/languages/en.lang.php index aab5381..3658494 100644 --- a/plugins/box/blocks/languages/en.lang.php +++ b/plugins/box/blocks/languages/en.lang.php @@ -3,16 +3,16 @@ return array( 'blocks' => array( 'Blocks' => 'Blocks', - 'Blocks manager' => 'Blocks manager', + 'Blocks manager' => 'Blocks manager', 'Delete' => 'Delete', 'Edit' => 'Edit', 'Name' => 'Name', 'Create new block' => 'Create new block', 'New block' => 'New block', - 'Edit block' => 'Edit block', - 'Save' => 'Save', - 'Save and exit' => 'Save and exit', - 'Actions' => 'Actions', + 'Edit block' => 'Edit block', + 'Save' => 'Save', + 'Save and exit' => 'Save and exit', + 'Actions' => 'Actions', 'Required field' => 'Required field', 'This block already exists' => 'This block already exists', 'This block does not exist' => 'This block does not exist', @@ -22,8 +22,8 @@ 'Your changes to the block :name have been saved.' => 'Your changes to the block :name have been saved.', 'Delete block: :block' => 'Delete block: :block', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/blocks/languages/it.lang.php b/plugins/box/blocks/languages/it.lang.php index c919cf6..bf67260 100644 --- a/plugins/box/blocks/languages/it.lang.php +++ b/plugins/box/blocks/languages/it.lang.php @@ -3,16 +3,16 @@ return array( 'blocks' => array( 'Blocks' => 'Blocchi', - 'Blocks manager' => 'Gestione blocchi', + 'Blocks manager' => 'Gestione blocchi', 'Delete' => 'Elimina', 'Edit' => 'Modifica', - 'New block' => 'Nuovo blocco', - 'Create new block' => 'Crea nuovo blocco', + 'New block' => 'Nuovo blocco', + 'Create new block' => 'Crea nuovo blocco', 'Name' => 'Nome', 'Edit block' => 'Modifica blocco', - 'Save' => 'Salva', + 'Save' => 'Salva', 'Actions' => 'Azioni', - 'Save and exit' => 'Salva ed esci', + 'Save and exit' => 'Salva ed esci', 'Required field' => 'Campo obbligatorio', 'This block already exists' => 'Tale blocco già esistente', 'This block does not exist' => 'Tale blocco non esiste', @@ -22,8 +22,8 @@ 'Your changes to the block :name have been saved.' => 'Le modifiche al blocco: nome sono state salvate.', 'Delete block: :block' => 'Elimina blocco: :block', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/blocks/languages/lt.lang.php b/plugins/box/blocks/languages/lt.lang.php index ec1bf94..817e320 100644 --- a/plugins/box/blocks/languages/lt.lang.php +++ b/plugins/box/blocks/languages/lt.lang.php @@ -12,7 +12,7 @@ 'Edit block' => 'Redaguoti bloką', 'Save' => 'Išsaugoti', 'Save and exit' => 'Išsaugoti ir išeiti', - 'Actions' => 'Veiksmai', + 'Actions' => 'Veiksmai', 'Required field' => 'Privalomas laukas', 'This block already exists' => 'Toks blokas jau yra', 'This block does not exist' => 'Tokio bloko nėra', @@ -22,8 +22,8 @@ 'Your changes to the block :name have been saved.' => 'Bloko :name pakeitimai išsaugoti.', 'Delete block: :block' => 'Delete block: :block', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/blocks/languages/pt-br.lang.php b/plugins/box/blocks/languages/pt-br.lang.php index b02de89..74e12ee 100644 --- a/plugins/box/blocks/languages/pt-br.lang.php +++ b/plugins/box/blocks/languages/pt-br.lang.php @@ -9,7 +9,7 @@ 'Name' => 'Nome', 'Create new block' => 'Criar novo bloco', 'New block' => 'Novo bloco', - 'Edit block' => 'Editar bloco', + 'Edit block' => 'Editar bloco', 'Save' => 'Salvar', 'Save and exit' => 'Salvar e sair', 'Actions' => 'Ações', @@ -22,8 +22,8 @@ 'Your changes to the block :name have been saved.' => 'Suas mudanças no bloco :name foram salvas', 'Delete block: :block' => 'Delete block: :block', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/blocks/languages/ru.lang.php b/plugins/box/blocks/languages/ru.lang.php index ebc4bcf..8ac05c7 100644 --- a/plugins/box/blocks/languages/ru.lang.php +++ b/plugins/box/blocks/languages/ru.lang.php @@ -3,16 +3,16 @@ return array( 'blocks' => array( 'Blocks' => 'Блоки', - 'Blocks manager' => 'Менеджер блоков', + 'Blocks manager' => 'Менеджер блоков', 'Delete' => 'Удалить', 'Edit' => 'Редактировать', - 'New block' => 'Новый блок', - 'Create new block' => 'Создать новый блок', + 'New block' => 'Новый блок', + 'Create new block' => 'Создать новый блок', 'Name' => 'Название', 'Edit block' => 'Редактирование блока', - 'Save' => 'Сохранить', + 'Save' => 'Сохранить', 'Actions' => 'Действия', - 'Save and exit' => 'Сохранить и выйти', + 'Save and exit' => 'Сохранить и выйти', 'Required field' => 'Обязательное поле', 'This block already exists' => 'Такой блок уже существует', 'This block does not exist' => 'Такого блока не существует', @@ -22,8 +22,8 @@ 'Your changes to the block :name have been saved.' => 'Ваши изменения к блоку :name были сохранены.', 'Delete block: :block' => 'Удалить блок: :block', 'View Embed Code' => 'Код для вставки', - 'Embed Code' => 'Код для вставки', + 'Embed Code' => 'Код для вставки', 'Shortcode' => 'Шорткод', 'PHP Code' => 'PHP код', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/blocks/languages/uk.lang.php b/plugins/box/blocks/languages/uk.lang.php index 434e5e0..8283d95 100644 --- a/plugins/box/blocks/languages/uk.lang.php +++ b/plugins/box/blocks/languages/uk.lang.php @@ -3,16 +3,16 @@ return array( 'blocks' => array( 'Blocks' => 'Блоки', - 'Blocks manager' => 'Менеджер блоків', + 'Blocks manager' => 'Менеджер блоків', 'Delete' => 'Видалити', 'Edit' => 'Редагувати', - 'New block' => 'Новий блок', - 'Create new block' => 'Створити новий блок', + 'New block' => 'Новий блок', + 'Create new block' => 'Створити новий блок', 'Name' => 'Назва', 'Edit block' => 'Редагування блоку', - 'Save' => 'Зберегти', + 'Save' => 'Зберегти', 'Actions' => 'Дії', - 'Save and exit' => 'Зберегти та вийти', + 'Save and exit' => 'Зберегти та вийти', 'Required field' => 'Обов′язкове поле', 'This block already exists' => 'Такий блок вже існує', 'This block does not exist' => 'Такого блоку не існує', @@ -22,8 +22,8 @@ 'Your changes to the block :name have been saved.' => 'Ваші зміни до блоку :name були збережені.', 'Delete block: :block' => 'Видалити блок: :block', 'View Embed Code' => 'Код для вставки', - 'Embed Code' => 'Код для вставки', + 'Embed Code' => 'Код для вставки', 'Shortcode' => 'Шорткод', 'PHP Code' => 'PHP код', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/blocks/views/backend/add.view.php b/plugins/box/blocks/views/backend/add.view.php index 4ac4811..a6ddfb8 100644 --- a/plugins/box/blocks/views/backend/add.view.php +++ b/plugins/box/blocks/views/backend/add.view.php @@ -5,12 +5,10 @@ - - (isset($errors['blocks_empty_name']) || isset($errors['blocks_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?> @@ -33,4 +31,3 @@ ); ?> - diff --git a/plugins/box/blocks/views/backend/edit.view.php b/plugins/box/blocks/views/backend/edit.view.php index b1fbaa1..82da094 100644 --- a/plugins/box/blocks/views/backend/edit.view.php +++ b/plugins/box/blocks/views/backend/edit.view.php @@ -16,7 +16,6 @@ ?> - (isset($errors['blocks_empty_name']) || isset($errors['blocks_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?> @@ -28,7 +27,7 @@

    'btn default')). Html::nbsp(). Form::close() ); - + } else { echo '
    '.__('This block does not exist', 'blocks').'
    '; } -?> \ No newline at end of file +?> diff --git a/plugins/box/blocks/views/backend/index.view.php b/plugins/box/blocks/views/backend/index.view.php index 0382b47..3ffe544 100755 --- a/plugins/box/blocks/views/backend/index.view.php +++ b/plugins/box/blocks/views/backend/index.view.php @@ -4,9 +4,9 @@ __('Create new block', 'blocks'), 'class' => 'btn default btn-small')). Html::nbsp(3) - ); + ); ?>

    @@ -31,7 +31,7 @@ + 'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete block: :block', 'blocks', array(':block' => basename($block, '.block.html')))."')")); @@ -60,4 +60,4 @@

    - \ No newline at end of file + diff --git a/plugins/box/editor/editor.plugin.php b/plugins/box/editor/editor.plugin.php index d44805c..0edbe0b 100644 --- a/plugins/box/editor/editor.plugin.php +++ b/plugins/box/editor/editor.plugin.php @@ -1,43 +1,42 @@
    '); + } - - // Register plugin - Plugin::register( __FILE__, - __('Editor', 'editor'), - __('Editor plugin', 'editor'), - '1.0.0', - 'Awilum', - 'http://monstra.org/', - null, - 'box'); - - // Add action - Action::add('admin_editor', 'Editor::render', 10, array()); - - - /** - * Editor class - */ - class Editor { - - /** - * Render editor - * - * @param string $val editor data - */ - public static function render($val = null) { - echo ('
    '); - } - - } \ No newline at end of file +} diff --git a/plugins/box/editor/install/editor.manifest.xml b/plugins/box/editor/install/editor.manifest.xml index f131b06..9fe3558 100644 --- a/plugins/box/editor/install/editor.manifest.xml +++ b/plugins/box/editor/install/editor.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/editor/languages/de.lang.php b/plugins/box/editor/languages/de.lang.php index 8a6a5f4..30794e7 100644 --- a/plugins/box/editor/languages/de.lang.php +++ b/plugins/box/editor/languages/de.lang.php @@ -1,8 +1,8 @@ - array( - 'Editor' => 'Editor', - 'Editor plugin' => 'Editor Plugin', - ) - ); \ No newline at end of file + array( + 'Editor' => 'Editor', + 'Editor plugin' => 'Editor Plugin', + ) + ); diff --git a/plugins/box/editor/languages/en.lang.php b/plugins/box/editor/languages/en.lang.php index d6501d6..fdce2ed 100644 --- a/plugins/box/editor/languages/en.lang.php +++ b/plugins/box/editor/languages/en.lang.php @@ -3,6 +3,6 @@ return array( 'Editor' => array( 'Editor' => 'Editor', - 'Editor plugin' => 'Editor plugin', + 'Editor plugin' => 'Editor plugin', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/editor/languages/it.lang.php b/plugins/box/editor/languages/it.lang.php index d6501d6..fdce2ed 100644 --- a/plugins/box/editor/languages/it.lang.php +++ b/plugins/box/editor/languages/it.lang.php @@ -3,6 +3,6 @@ return array( 'Editor' => array( 'Editor' => 'Editor', - 'Editor plugin' => 'Editor plugin', + 'Editor plugin' => 'Editor plugin', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/editor/languages/lt.lang.php b/plugins/box/editor/languages/lt.lang.php index 07fc69c..ee97e58 100644 --- a/plugins/box/editor/languages/lt.lang.php +++ b/plugins/box/editor/languages/lt.lang.php @@ -3,6 +3,6 @@ return array( 'Editor' => array( 'Editor' => 'Redaktorius', - 'Editor plugin' => 'Redaktoriaus papildinys', + 'Editor plugin' => 'Redaktoriaus papildinys', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/editor/languages/pt-br.lang.php b/plugins/box/editor/languages/pt-br.lang.php index 961fba6..ecbf493 100644 --- a/plugins/box/editor/languages/pt-br.lang.php +++ b/plugins/box/editor/languages/pt-br.lang.php @@ -5,4 +5,4 @@ 'Editor' => 'Editor', 'Editor plugin' => 'Plugin do editor', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/editor/languages/ru.lang.php b/plugins/box/editor/languages/ru.lang.php index 03781e7..bdc4e90 100644 --- a/plugins/box/editor/languages/ru.lang.php +++ b/plugins/box/editor/languages/ru.lang.php @@ -3,6 +3,6 @@ return array( 'Editor' => array( 'Editor' => 'Редактор', - 'Editor plugin' => 'Редактор плагин', + 'Editor plugin' => 'Редактор плагин', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/editor/languages/uk.lang.php b/plugins/box/editor/languages/uk.lang.php index 81e043f..90f25cd 100644 --- a/plugins/box/editor/languages/uk.lang.php +++ b/plugins/box/editor/languages/uk.lang.php @@ -3,6 +3,6 @@ return array( 'Editor' => array( 'Editor' => 'Редактор', - 'Editor plugin' => 'Редактор плагіну', + 'Editor plugin' => 'Редактор плагіну', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/filesmanager.admin.php b/plugins/box/filesmanager/filesmanager.admin.php index 51b1cf1..0b19b5a 100755 --- a/plugins/box/filesmanager/filesmanager.admin.php +++ b/plugins/box/filesmanager/filesmanager.admin.php @@ -1,162 +1,163 @@ assign('path', $path) + ->assign('current', $current) + ->assign('files_list', $files_list) + ->assign('dir_list', $dir_list) + ->assign('forbidden_types', $forbidden_types) + ->assign('image_types', $image_types) + ->assign('site_url', $site_url) + ->assign('files_path', $files_path) + ->display(); + + } /** - * Filesmanager Admin Class + * Get directories and files in current path */ - class FilesmanagerAdmin extends Backend { - - /** - * Main function - */ - public static function main() { - - // Array of forbidden types - $forbidden_types = array('html', 'htm', 'js', 'jsb', 'mhtml', 'mht', - 'php', 'phtml', 'php3', 'php4', 'php5', 'phps', - 'shtml', 'jhtml', 'pl', 'py', 'cgi', 'sh', 'ksh', 'bsh', 'c', 'htaccess', 'htpasswd', - 'exe', 'scr', 'dll', 'msi', 'vbs', 'bat', 'com', 'pif', 'cmd', 'vxd', 'cpl'); - - // Array of image types - $image_types = array('jpg', 'png', 'bmp', 'gif', 'tif'); - - // Get Site url - $site_url = Option::get('siteurl'); - - // Init vars - if (Request::get('path')) $path = Request::get('path'); else $path = 'uploads/'; - - // Add slash if not exists - if (substr($path, -1, 1) != '/') { - $path .= '/'; - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - } - - // Upload corectly! - if ($path == 'uploads' || $path == 'uploads//') { - $path = 'uploads/'; - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - } - - // Only 'uploads' folder! - if (strpos($path, 'uploads') === false) { - $path = 'uploads/'; - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - } - - // Set default path value if path is empty - if ($path == '') { - $path = 'uploads/'; - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - } - - $files_path = ROOT . DS . 'public' . DS . $path; - $files_list = array(); - - $current = explode('/', $path); - - // Get information about current path - $_list = FilesmanagerAdmin::fdir($files_path); - - $files_list = array(); - - // Get files - if (isset($_list['files'])) { - foreach ($_list['files'] as $files) { - $files_list[] = $files; - } - } - - $dir_list = array(); - - // Get dirs - if (isset($_list['dirs'])) { - foreach ($_list['dirs'] as $dirs) { - if (strpos($dirs, '.') === false) $dir_list[] = $dirs; - } - } - - // Delete file - // ------------------------------------- - if (Request::get('id') == 'filesmanager' && Request::get('delete_file')) { - - if (Security::check(Request::get('token'))) { - - File::delete($files_path.Request::get('delete_file')); - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - - } else { die('csrf detected!'); } - } - - // Delete dir - // ------------------------------------- - if (Request::get('id') == 'filesmanager' && Request::get('delete_dir')) { - - if (Security::check(Request::get('token'))) { - - Dir::delete($files_path.Request::get('delete_dir')); - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - - } else { die('csrf detected!'); } - } - - // Upload file - // ------------------------------------- - if (Request::post('upload_file')) { - - if (Security::check(Request::post('csrf'))) { - - if ($_FILES['file']) { - if ( ! in_array(File::ext($_FILES['file']['name']), $forbidden_types)) { - move_uploaded_file($_FILES['file']['tmp_name'], $files_path.Security::safeName(basename($_FILES['file']['name'], File::ext($_FILES['file']['name'])), '-', true).'.'.File::ext($_FILES['file']['name'])); - Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path); - } - } - - } else { die('csrf detected!'); } - } - - // Display view - View::factory('box/filesmanager/views/backend/index') - ->assign('path', $path) - ->assign('current', $current) - ->assign('files_list', $files_list) - ->assign('dir_list', $dir_list) - ->assign('forbidden_types', $forbidden_types) - ->assign('image_types', $image_types) - ->assign('site_url', $site_url) - ->assign('files_path', $files_path) - ->display(); - - } - - - /** - * Get directories and files in current path - */ - protected static function fdir($dir, $type = null) { - $files = array(); - $c = 0; - $_dir = $dir; - if (is_dir($dir)) { - $dir = opendir ($dir); - while (false !== ($file = readdir($dir))) { - if (($file !=".") && ($file !="..")) { - $c++; - if (is_dir($_dir.$file)) { - $files['dirs'][$c] = $file; - } else { - $files['files'][$c] = $file; - } + protected static function fdir($dir, $type = null) + { + $files = array(); + $c = 0; + $_dir = $dir; + if (is_dir($dir)) { + $dir = opendir ($dir); + while (false !== ($file = readdir($dir))) { + if (($file !=".") && ($file !="..")) { + $c++; + if (is_dir($_dir.$file)) { + $files['dirs'][$c] = $file; + } else { + $files['files'][$c] = $file; } } - closedir($dir); - return $files; - } else { - return false; } + closedir($dir); + + return $files; + } else { + return false; } - } + +} diff --git a/plugins/box/filesmanager/filesmanager.plugin.php b/plugins/box/filesmanager/filesmanager.plugin.php index 5820d47..4a5db57 100644 --- a/plugins/box/filesmanager/filesmanager.plugin.php +++ b/plugins/box/filesmanager/filesmanager.plugin.php @@ -1,34 +1,32 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/filesmanager/languages/de.lang.php b/plugins/box/filesmanager/languages/de.lang.php index be7f678..71fdb70 100644 --- a/plugins/box/filesmanager/languages/de.lang.php +++ b/plugins/box/filesmanager/languages/de.lang.php @@ -1,17 +1,17 @@ - array( - 'Files' => 'Dateien', - 'Files manager' => 'Datei-Manager', - 'Name' => 'Name', - 'Actions' => 'Aktionen', - 'Delete' => 'Löschen', - 'Upload' => 'Hochladen', - 'directory' => 'Ordner', - 'Delete directory: :dir' => 'Lösche Ordner: :dir', - 'Delete file: :file' => 'Lösche Datei: file', - 'Extension' => 'Dateiendung', - 'Size' => 'Größe', - ) - ); \ No newline at end of file + array( + 'Files' => 'Dateien', + 'Files manager' => 'Datei-Manager', + 'Name' => 'Name', + 'Actions' => 'Aktionen', + 'Delete' => 'Löschen', + 'Upload' => 'Hochladen', + 'directory' => 'Ordner', + 'Delete directory: :dir' => 'Lösche Ordner: :dir', + 'Delete file: :file' => 'Lösche Datei: file', + 'Extension' => 'Dateiendung', + 'Size' => 'Größe', + ) + ); diff --git a/plugins/box/filesmanager/languages/en.lang.php b/plugins/box/filesmanager/languages/en.lang.php index a8ed5f5..44a287b 100644 --- a/plugins/box/filesmanager/languages/en.lang.php +++ b/plugins/box/filesmanager/languages/en.lang.php @@ -4,14 +4,14 @@ 'filesmanager' => array( 'Files' => 'Files', 'Files manager' => 'Files manager', - 'Name' => 'Name', + 'Name' => 'Name', 'Actions' => 'Actions', 'Delete' => 'Delete', 'Upload' => 'Upload', 'directory' => 'directory', - 'Delete directory: :dir' => 'Delete directory: :dir', + 'Delete directory: :dir' => 'Delete directory: :dir', 'Delete file: :file' => 'Delete file :file', 'Extension' => 'Extension', 'Size' => 'Size', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/languages/it.lang.php b/plugins/box/filesmanager/languages/it.lang.php index f4f6073..d53b487 100644 --- a/plugins/box/filesmanager/languages/it.lang.php +++ b/plugins/box/filesmanager/languages/it.lang.php @@ -3,7 +3,7 @@ return array( 'filesmanager' => array( 'Files' => 'File', - 'Files manager' => 'Gestione file', + 'Files manager' => 'Gestione file', 'Name' => 'Nome', 'Actions' => 'Azioni', 'Delete' => 'Elimina', @@ -14,4 +14,4 @@ 'Extension' => 'Estensione', 'Size' => 'Dimensione', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/languages/lt.lang.php b/plugins/box/filesmanager/languages/lt.lang.php index 20af27a..e6eaf00 100644 --- a/plugins/box/filesmanager/languages/lt.lang.php +++ b/plugins/box/filesmanager/languages/lt.lang.php @@ -4,14 +4,14 @@ 'filesmanager' => array( 'Files' => 'Bylos', 'Files manager' => 'Bylų tvarkyklė', - 'Name' => 'Pavadinimas', + 'Name' => 'Pavadinimas', 'Actions' => 'Veiksmai', 'Delete' => 'Ištrinti', 'Upload' => 'Įkelti', 'directory' => 'aplankas', - 'Delete directory: :dir' => 'Ištrinti aplanką: :dir', + 'Delete directory: :dir' => 'Ištrinti aplanką: :dir', 'Delete file: :file' => 'Ištrinti bylą :file', 'Extension' => 'Plėtinys', 'Size' => 'Dydis', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/languages/pt-br.lang.php b/plugins/box/filesmanager/languages/pt-br.lang.php index f8a710e..03782d4 100644 --- a/plugins/box/filesmanager/languages/pt-br.lang.php +++ b/plugins/box/filesmanager/languages/pt-br.lang.php @@ -9,9 +9,9 @@ 'Delete' => 'Deletar', 'Upload' => 'Upload', 'directory' => 'directory', - 'Delete directory: :dir' => 'Deletar o diretório: :dir', + 'Delete directory: :dir' => 'Deletar o diretório: :dir', 'Delete file: :file' => 'Deletar o arquivo :file', 'Extension' => 'Extensão', 'Size' => 'Tamanho', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/languages/ru.lang.php b/plugins/box/filesmanager/languages/ru.lang.php index 2c879fe..bf680e6 100644 --- a/plugins/box/filesmanager/languages/ru.lang.php +++ b/plugins/box/filesmanager/languages/ru.lang.php @@ -3,7 +3,7 @@ return array( 'filesmanager' => array( 'Files' => 'Файлы', - 'Files manager' => 'Менеджер файлов', + 'Files manager' => 'Менеджер файлов', 'Name' => 'Название', 'Actions' => 'Действия', 'Delete' => 'Удалить', @@ -14,4 +14,4 @@ 'Extension' => 'Расширение', 'Size' => 'Размер', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/languages/uk.lang.php b/plugins/box/filesmanager/languages/uk.lang.php index 00eb895..1306a0e 100644 --- a/plugins/box/filesmanager/languages/uk.lang.php +++ b/plugins/box/filesmanager/languages/uk.lang.php @@ -3,7 +3,7 @@ return array( 'filesmanager' => array( 'Files' => 'Файли', - 'Files manager' => 'Менеджер файлів', + 'Files manager' => 'Менеджер файлів', 'Name' => 'Назва', 'Actions' => 'Дії', 'Delete' => 'Видалити', @@ -14,4 +14,4 @@ 'Extension' => 'Розширення', 'Size' => 'Розмір', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/filesmanager/views/backend/index.view.php b/plugins/box/filesmanager/views/backend/index.view.php index 7f05e0a..0dfd973 100755 --- a/plugins/box/filesmanager/views/backend/index.view.php +++ b/plugins/box/filesmanager/views/backend/index.view.php @@ -26,12 +26,12 @@ } $s = ''; - + foreach ($path_parts as $p) { $s .= $p.'/'; - if($p == $current[count($current)-2]) $active = ' class="active"'; else $active = ''; - echo ''.$p.' /'; - } + if($p == $current[count($current)-2]) $active = ' class="active"'; else $active = ''; + echo ''.$p.' /'; + } ?> @@ -47,12 +47,12 @@ - + - + @@ -66,10 +66,10 @@
    - + - + > '_blank'));?> @@ -84,11 +84,11 @@ 'btn btn-small', 'onclick' => "return confirmDelete('".__('Delete file: :file', 'filesmanager', array(':file' => $file))."')")); - ?> + ?>
    - - + + @@ -100,4 +100,4 @@ - \ No newline at end of file + diff --git a/plugins/box/information/information.admin.php b/plugins/box/information/information.admin.php index a2a8018..de7e757 100644 --- a/plugins/box/information/information.admin.php +++ b/plugins/box/information/information.admin.php @@ -6,25 +6,23 @@ /** * Information Admin Class */ - class InformationAdmin extends Backend { - - + class InformationAdmin extends Backend + { /** * Information main function */ - public static function main() { - + public static function main() + { // Init vars $php_modules = array(); // Get array with the names of all modules compiled and loaded $php_modules = get_loaded_extensions(); - // Display view + // Display view View::factory('box/information/views/backend/index') ->assign('php_modules', $php_modules) ->display(); } - } diff --git a/plugins/box/information/information.plugin.php b/plugins/box/information/information.plugin.php index 02e7eaa..02ddb02 100644 --- a/plugins/box/information/information.plugin.php +++ b/plugins/box/information/information.plugin.php @@ -11,21 +11,19 @@ * */ - // Register plugin - Plugin::register( __FILE__, + Plugin::register( __FILE__, __('Information', 'information'), - __('Information plugin', 'information'), + __('Information plugin', 'information'), '1.0.0', - 'Awilum', + 'Awilum', 'http://monstra.org/', null, 'box'); - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - + // Include Information Admin Plugin::Admin('information', 'box'); - } \ No newline at end of file + } diff --git a/plugins/box/information/install/information.manifest.xml b/plugins/box/information/install/information.manifest.xml index 2c67897..5e30226 100644 --- a/plugins/box/information/install/information.manifest.xml +++ b/plugins/box/information/install/information.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/information/languages/de.lang.php b/plugins/box/information/languages/de.lang.php index 63f5152..eb6316d 100644 --- a/plugins/box/information/languages/de.lang.php +++ b/plugins/box/information/languages/de.lang.php @@ -1,40 +1,40 @@ - array( - 'Information' => 'Informationen', - 'Debuging' => 'Debugging', - 'Name' => 'Name', - 'Value' => 'Wert', - 'Security' => 'Sicherheit', - 'System' => 'System', - 'on' => 'An', - 'off'=> 'Aus', - 'Server' => 'Server', - 'PHP version' => 'PHP Version', - 'SimpleXML module' => 'SimpleXML Modul', - 'DOM module' => 'DOM Modul', - 'Installed' => 'Installiert', - 'Not Installed' => 'Nicht Installiert', - 'Security check results' => 'Sicherheits-Check Ergebnisse', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => - 'Die Konfigurationsdatei wurde als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte für defines.php auf Produktionssystemen zu entfernen.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => - 'Das Monstra-Core-Verzeichnis (":path") und/oder Dateien unterhalb des Verzeichnisses wurden als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte zu entfernen.
    Du kannst dies auf Unix-Systemen ganz einfach mit: chmod -R a-w :path erledigen.', - 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => - 'Die Monstra .htaccess Datei wurde als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte zu entfernen.
    Du kannst dies auf Unix-Systemen ganz einfach mit: chmod a-w :path erledigen.', - 'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => - 'Die Monstra index.php Datei wurde als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte zu entfernen.
    Du kannst dies auf Unix-Systemen ganz einfach mit: chmod a-w :path erledigen.', - 'Due to the type and amount of information an error might give intruders when Core::$environment = Core::DEVELOPMENT, we strongly advise setting Core::PRODUCTION in production systems.' => - 'Aufgrund der Art und Menge der Informationen kann ein Fehler Eindringlinge ergeben wenn Core::$environment = Core::DEVELOPMENT, wir raten dringend dazu folgendermaßen Core::PRODUCTION in Produktionssystemen einzustellen.', - 'Monstra version' => 'Monstra version', - 'Directory Permissions' => 'Directory Berechtigungen', - 'Directory' => 'Verzeichnis', - 'Writable' => 'Writable', - 'Unwritable' => 'Nicht beschreibbar', - 'Status' => 'Status', - 'PHP Built On' => 'PHP Built On', - 'Web Server' => 'Web Server', - 'WebServer to PHP Interface' => 'WebServer to PHP Interface', - ) - ); \ No newline at end of file + array( + 'Information' => 'Informationen', + 'Debuging' => 'Debugging', + 'Name' => 'Name', + 'Value' => 'Wert', + 'Security' => 'Sicherheit', + 'System' => 'System', + 'on' => 'An', + 'off'=> 'Aus', + 'Server' => 'Server', + 'PHP version' => 'PHP Version', + 'SimpleXML module' => 'SimpleXML Modul', + 'DOM module' => 'DOM Modul', + 'Installed' => 'Installiert', + 'Not Installed' => 'Nicht Installiert', + 'Security check results' => 'Sicherheits-Check Ergebnisse', + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'Die Konfigurationsdatei wurde als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte für defines.php auf Produktionssystemen zu entfernen.', + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'Das Monstra-Core-Verzeichnis (":path") und/oder Dateien unterhalb des Verzeichnisses wurden als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte zu entfernen.
    Du kannst dies auf Unix-Systemen ganz einfach mit: chmod -R a-w :path erledigen.', + 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => + 'Die Monstra .htaccess Datei wurde als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte zu entfernen.
    Du kannst dies auf Unix-Systemen ganz einfach mit: chmod a-w :path erledigen.', + 'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => + 'Die Monstra index.php Datei wurde als beschreibbar entdeckt. Wir empfehlen alle Schreibrechte zu entfernen.
    Du kannst dies auf Unix-Systemen ganz einfach mit: chmod a-w :path erledigen.', + 'Due to the type and amount of information an error might give intruders when Core::$environment = Core::DEVELOPMENT, we strongly advise setting Core::PRODUCTION in production systems.' => + 'Aufgrund der Art und Menge der Informationen kann ein Fehler Eindringlinge ergeben wenn Core::$environment = Core::DEVELOPMENT, wir raten dringend dazu folgendermaßen Core::PRODUCTION in Produktionssystemen einzustellen.', + 'Monstra version' => 'Monstra version', + 'Directory Permissions' => 'Directory Berechtigungen', + 'Directory' => 'Verzeichnis', + 'Writable' => 'Writable', + 'Unwritable' => 'Nicht beschreibbar', + 'Status' => 'Status', + 'PHP Built On' => 'PHP Built On', + 'Web Server' => 'Web Server', + 'WebServer to PHP Interface' => 'WebServer to PHP Interface', + ) + ); diff --git a/plugins/box/information/languages/en.lang.php b/plugins/box/information/languages/en.lang.php index 408d35f..32e91b4 100644 --- a/plugins/box/information/languages/en.lang.php +++ b/plugins/box/information/languages/en.lang.php @@ -9,7 +9,7 @@ 'Security' => 'Security', 'System' => 'System', 'on' => 'on', - 'off'=> 'off', + 'off'=> 'off', 'Server' => 'Server', 'PHP version' => 'PHP version', 'SimpleXML module' => 'SimpleXML module', @@ -17,9 +17,9 @@ 'Installed' => 'Installed', 'Not Installed' => 'Not Installed', 'Security check results' => 'Security check results', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path', 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path', @@ -37,4 +37,4 @@ 'Web Server' => 'Web Server', 'WebServer to PHP Interface' => 'WebServer to PHP Interface', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/information/languages/it.lang.php b/plugins/box/information/languages/it.lang.php index db1f720..5aff31e 100644 --- a/plugins/box/information/languages/it.lang.php +++ b/plugins/box/information/languages/it.lang.php @@ -17,9 +17,9 @@ 'Installed' => 'Installato', 'Not Installed' => 'Non installato', 'Security check results' => 'Risultato del controllo di sicurezza', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => 'Il file di configurazione è scrivibile. Si consiglia di rimuovere le autorizzazioni di scrittura per defines.php file sul sito funzionante.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => 'Directory Monstra (":path") è scrivibile. Si consiglia di rimuovere le autorizzazioni di scrittura per la directory (":path") sul sito funzionante.
    È possibile eseguire questa operazione su sistemi UNIX così: chmod -R a-w :path', 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => 'Principale file .htaccess è scrivibile. Si consiglia di rimuovere le autorizzazioni di scrittura per il file principale .htaccess.
    È possibile eseguire questa operazione su sistemi UNIX così: chmod -R a-w :path', @@ -37,4 +37,4 @@ 'Web Server' => 'Web Server', 'WebServer to PHP Interface' => 'WebServer to PHP Interface', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/information/languages/lt.lang.php b/plugins/box/information/languages/lt.lang.php index 8d906f5..a5a82b2 100644 --- a/plugins/box/information/languages/lt.lang.php +++ b/plugins/box/information/languages/lt.lang.php @@ -9,7 +9,7 @@ 'Security' => 'Saugumas', 'System' => 'Systema', 'on' => 'Įjungta', - 'off'=> 'Išjungta', + 'off'=> 'Išjungta', 'Server' => 'Serveris', 'PHP version' => 'PHP versija', 'SimpleXML module' => 'SimpleXML modulis', @@ -17,9 +17,9 @@ 'Installed' => 'Įdiegta', 'Not Installed' => 'Neįdiegta', 'Security check results' => 'Saugumo patikrinimo rezultatai', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => 'Leidžiama perrašyti nustatymų bylą. Siūlome pašalinti visus rašymo leidimus sistemos bylai defines.php.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => 'Monstra pagrindinį aplanką (":path") ir/arba jo bylas leidžiama perrašyti. Siūlome pašalinti visus rašymo leidimus.
    Tai galite padaryti Unix sistemoje su: chmod -R a-w :path', 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => 'Monstra .htaccess bylą galima perrašyti. Siūlome pašalinti visus rašymo leidimus.
    Tai galite padaryti Unix sistemoje su: chmod a-w :path', @@ -37,4 +37,4 @@ 'Web Server' => 'Serverio prog. įranga', 'WebServer to PHP Interface' => 'PHP naudoja šį SAPI', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/information/languages/pt-br.lang.php b/plugins/box/information/languages/pt-br.lang.php index 69faa56..0b2c63f 100644 --- a/plugins/box/information/languages/pt-br.lang.php +++ b/plugins/box/information/languages/pt-br.lang.php @@ -17,9 +17,9 @@ 'Installed' => 'Instalado', 'Not Installed' => 'Não instalado', 'Security check results' => 'Resultados da verificação de segurança', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => 'O arquivo de configuração está com permissões de escrita. Para melhor segurança, você deve remover as permissões de escrita do arquivo defines.php em sistemas de produções.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => 'O diretório núcleo do Monstra (":path") e/ou arquivos dentro do diretório estão com permissões de escrita. Para melhor segurança, você deve remover as permissões de escritas.
    Você pode fazer isso em sistemas UNIX com: chmod -R a-w :path', 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => 'O arquivo .htaccess da pasta de instalação do Monstra está com permissões de escrita. Para sua melhor segurança, você deve remover as permissões de escritas.
    Você pode fazer isso em sistemas UNIX com: chmod a-w :path', @@ -37,4 +37,4 @@ 'Web Server' => 'Web Server', 'WebServer to PHP Interface' => 'WebServer to PHP Interface', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/information/languages/ru.lang.php b/plugins/box/information/languages/ru.lang.php index eadd566..2ac0df9 100644 --- a/plugins/box/information/languages/ru.lang.php +++ b/plugins/box/information/languages/ru.lang.php @@ -9,7 +9,7 @@ 'Security' => 'Безопасность', 'System' => 'Система', 'on' => 'включен', - 'off'=> 'выключен', + 'off'=> 'выключен', 'Server' => 'Сервер', 'PHP version' => 'Версия PHP', 'SimpleXML module' => 'SimpleXML модуль', @@ -17,9 +17,9 @@ 'Installed' => 'Установлен', 'Not Installed' => 'Не установлен', 'Security check results' => 'Результаты проверки безопасности', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => 'Конфигурационный файл доступен для записи. Мы рекомендуем вам удалить права записи на файл defines.php на живом сайте.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => 'Директория Monstra (":path") доступна для записи. Мы рекомендуем вам удалить права записи на директорию (":path") на живом сайте.
    Вы можете сделать это на UNIX системах так: chmod -R a-w :path', 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => 'Главный .htaccess доступен для записи. Мы рекомендуем вам удалить права записи на главный .htaccess файл.
    Вы можете сделать это на UNIX системах так: chmod -R a-w :path', @@ -37,4 +37,4 @@ 'Web Server' => 'Веб сервер', 'WebServer to PHP Interface' => 'Веб сервер для PHP интерфейса', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/information/languages/uk.lang.php b/plugins/box/information/languages/uk.lang.php index a536e48..daafc46 100644 --- a/plugins/box/information/languages/uk.lang.php +++ b/plugins/box/information/languages/uk.lang.php @@ -9,7 +9,7 @@ 'Security' => 'Безпека', 'System' => 'Система', 'on' => 'включений', - 'off'=> 'вимкнено', + 'off'=> 'вимкнено', 'Server' => 'Сервер', 'PHP version' => 'Версія PHP', 'SimpleXML module' => 'SimpleXML модуль', @@ -17,9 +17,9 @@ 'Installed' => 'Встановлено', 'Not Installed' => 'Не встановлено', 'Security check results' => 'Результати перевірки безпеки', - 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => + 'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' => 'Конфігураційний файл доступен для запису. Ми рекомендуємо вам видалити права запису на файл defines.php на живому сайті.', - 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => + 'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod -R a-w :path' => 'Директорія Monstra (":path") доступна для запису. Ми рекомендуємо вам видалити права запису на директорію (":path") на живому сайті.
    Ви можете зробити це на UNIX системах так: chmod -R a-w :path', 'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions.
    You can do this on unix systems with: chmod a-w :path' => 'Головный .htaccess доступен для запису. Ми рекомендуємо вам видалити права запису на головний .htaccess файл.
    Ви можете зробити це на UNIX системах так: chmod -R a-w :path', @@ -36,4 +36,4 @@ 'PHP Built On' => 'PHP построен на', 'Web Server' => 'Веб сервер', 'WebServer to PHP Interface' => 'Веб сервер для PHP интерфейса', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/information/views/backend/index.view.php b/plugins/box/information/views/backend/index.view.php index 2f245f6..d1666a5 100644 --- a/plugins/box/information/views/backend/index.view.php +++ b/plugins/box/information/views/backend/index.view.php @@ -4,13 +4,13 @@
    - +
    @@ -25,11 +25,11 @@ - + - + @@ -48,27 +48,27 @@ - + - + - + - + - + - + @@ -132,7 +132,7 @@
    - +
    @@ -144,33 +144,33 @@ - - ! + + ! You can do this on unix systems with: chmod -R a-w :path', 'information', array(':path' => MONSTRA . DS)); ?> - - ! + + ! You can do this on unix systems with: chmod a-w :path', 'information', array(':path' => ROOT . DS . '.htaccess')); ?> - - ! + + ! You can do this on unix systems with: chmod a-w :path', 'information', array(':path' => ROOT . DS . 'index.php')); ?> - + - ! + ! - +
    -
    \ No newline at end of file + diff --git a/plugins/box/menu/install/menu.manifest.xml b/plugins/box/menu/install/menu.manifest.xml index 303f589..295c47f 100644 --- a/plugins/box/menu/install/menu.manifest.xml +++ b/plugins/box/menu/install/menu.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/menu/languages/de.lang.php b/plugins/box/menu/languages/de.lang.php index 255b1cc..5daad4c 100644 --- a/plugins/box/menu/languages/de.lang.php +++ b/plugins/box/menu/languages/de.lang.php @@ -1,27 +1,27 @@ - array( - 'Menu' => 'Menü', - 'Menu manager' => 'Menü Manager', - 'Edit' => 'Bearbeiten', - 'Name' => 'Name', - 'Delete' => 'Löschen', - 'Order' => 'Reihenfolge', - 'Actions' => 'Aktionen', - 'Create new item' => 'Erstellen neuen Eintrag', - 'New item' => 'Neuer Eintrag', - 'Item name' => 'Eintrags Name', - 'Item order' => 'Eintrags Reihenfolge', - 'Item target' => 'Eintrags Ziel', - 'Item link' => 'Eintrags Link', - 'Item category' => 'Eintrags Kategorie', - 'Save' => 'Speichern', - 'Edit item' => 'Bearbeite Eintrag', - 'Delete item :name' => 'Lösche Eintrag :name', - 'Select page' => 'Seite auswählen', - 'Category' => 'Kategorie', - 'Select category' => 'Kategorie auswählen', - 'Required field' => 'Pflichtfeld', - ) - ); \ No newline at end of file + array( + 'Menu' => 'Menü', + 'Menu manager' => 'Menü Manager', + 'Edit' => 'Bearbeiten', + 'Name' => 'Name', + 'Delete' => 'Löschen', + 'Order' => 'Reihenfolge', + 'Actions' => 'Aktionen', + 'Create new item' => 'Erstellen neuen Eintrag', + 'New item' => 'Neuer Eintrag', + 'Item name' => 'Eintrags Name', + 'Item order' => 'Eintrags Reihenfolge', + 'Item target' => 'Eintrags Ziel', + 'Item link' => 'Eintrags Link', + 'Item category' => 'Eintrags Kategorie', + 'Save' => 'Speichern', + 'Edit item' => 'Bearbeite Eintrag', + 'Delete item :name' => 'Lösche Eintrag :name', + 'Select page' => 'Seite auswählen', + 'Category' => 'Kategorie', + 'Select category' => 'Kategorie auswählen', + 'Required field' => 'Pflichtfeld', + ) + ); diff --git a/plugins/box/menu/languages/en.lang.php b/plugins/box/menu/languages/en.lang.php index 2c1c10a..5649975 100644 --- a/plugins/box/menu/languages/en.lang.php +++ b/plugins/box/menu/languages/en.lang.php @@ -2,7 +2,7 @@ return array( 'menu' => array( - 'Menu' => 'Menu', + 'Menu' => 'Menu', 'Menu manager' => 'Menu manager', 'Edit' => 'Edit', 'Name' => 'Name', @@ -24,4 +24,4 @@ 'Select category' => 'Select category', 'Required field' => 'Required field', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/menu/languages/it.lang.php b/plugins/box/menu/languages/it.lang.php index 93b1b70..98f037c 100644 --- a/plugins/box/menu/languages/it.lang.php +++ b/plugins/box/menu/languages/it.lang.php @@ -2,7 +2,7 @@ return array( 'menu' => array( - 'Menu' => 'Menu', + 'Menu' => 'Menu', 'Menu manager' => 'Gestione menu', 'Edit' => 'Modifica', 'Name' => 'Nome', @@ -12,7 +12,7 @@ 'Create new item' => 'Crea nuova voce', 'New item' => 'Nuova voce', 'Item name' => 'Nome', - 'Item order' => 'Ordine', + 'Item order' => 'Ordine', 'Item target' => 'Target', 'Item link' => 'Collegamento', 'Item category' => 'Categoria', @@ -24,4 +24,4 @@ 'Select category' => 'Scegli categoria', 'Required field' => 'Campo obbligatorio', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/menu/languages/lt.lang.php b/plugins/box/menu/languages/lt.lang.php index df37db9..9d35728 100644 --- a/plugins/box/menu/languages/lt.lang.php +++ b/plugins/box/menu/languages/lt.lang.php @@ -25,4 +25,4 @@ 'Select category' => 'Pasirinkti kategoriją', 'Required field' => 'Privalomas laukas', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/menu/languages/pt-br.lang.php b/plugins/box/menu/languages/pt-br.lang.php index 65a1c58..be64fd7 100644 --- a/plugins/box/menu/languages/pt-br.lang.php +++ b/plugins/box/menu/languages/pt-br.lang.php @@ -2,7 +2,7 @@ return array( 'menu' => array( - 'Menu' => 'Menu', + 'Menu' => 'Menu', 'Menu manager' => 'Gerenciador do menu', 'Edit' => 'Editar', 'Name' => 'Nome', @@ -24,4 +24,4 @@ 'Select category' => 'Selecionar categoria', 'Required field' => 'Campo requerido', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/menu/languages/ru.lang.php b/plugins/box/menu/languages/ru.lang.php index be30221..b996832 100644 --- a/plugins/box/menu/languages/ru.lang.php +++ b/plugins/box/menu/languages/ru.lang.php @@ -2,7 +2,7 @@ return array( 'menu' => array( - 'Menu' => 'Меню', + 'Menu' => 'Меню', 'Menu manager' => 'Менеджер меню', 'Edit' => 'Редактировать', 'Name' => 'Название', @@ -12,7 +12,7 @@ 'Create new item' => 'Создать новый пункт меню', 'New item' => 'Новый пункт меню', 'Item name' => 'Название', - 'Item order' => 'Порядок', + 'Item order' => 'Порядок', 'Item target' => 'Цель', 'Item link' => 'Ссылка', 'Item category' => 'Категория', @@ -24,4 +24,4 @@ 'Select category' => 'Выбрать категорию', 'Required field' => 'Обязательное поле', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/menu/languages/uk.lang.php b/plugins/box/menu/languages/uk.lang.php index 739560e..1c6461a 100644 --- a/plugins/box/menu/languages/uk.lang.php +++ b/plugins/box/menu/languages/uk.lang.php @@ -2,7 +2,7 @@ return array( 'menu' => array( - 'Menu' => 'Меню', + 'Menu' => 'Меню', 'Menu manager' => 'Менеджер меню', 'Edit' => 'Редагувати', 'Name' => 'Назва', @@ -12,7 +12,7 @@ 'Create new item' => 'Створити новий пункт меню', 'New item' => 'Новий пункт меню', 'Item name' => 'Назва', - 'Item order' => 'Порядок', + 'Item order' => 'Порядок', 'Item target' => 'Ціль', 'Item link' => 'Ссылка', 'Item category' => 'Категорія', @@ -24,4 +24,4 @@ 'Select category' => 'Вибрати категорію', 'Required field' => 'Обов’язкове поле', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/menu/menu.admin.php b/plugins/box/menu/menu.admin.php index ecfd351..de7c30a 100644 --- a/plugins/box/menu/menu.admin.php +++ b/plugins/box/menu/menu.admin.php @@ -1,281 +1,273 @@ '', + '_blank' => '_blank', + '_parent' => '_parent', + '_top' => '_top'); + // Create order array + $menu_item_order_array = range(0, 20); - /** - * Main - */ - public static function main() { + // Check for get actions + // --------------------------------------------- + if (Request::get('action')) { - // Get menu table - MenuAdmin::$menu = new Table('menu'); + // Switch actions + // ----------------------------------------- + switch (Request::get('action')) { - // Get pages table - $pages = new Table('pages'); - - // Create target array - $menu_item_target_array = array( '' => '', - '_blank' => '_blank', - '_parent' => '_parent', - '_top' => '_top'); - - // Create order array - $menu_item_order_array = range(0, 20); - - - // Check for get actions - // --------------------------------------------- - if (Request::get('action')) { - - // Switch actions + // Edit menu item // ----------------------------------------- - switch (Request::get('action')) { + case "edit": - // Edit menu item - // ----------------------------------------- - case "edit": + // Select item + $item = MenuAdmin::$menu->select('[id="'.Request::get('item_id').'"]', null); - // Select item - $item = MenuAdmin::$menu->select('[id="'.Request::get('item_id').'"]', null); - - $menu_item_name = $item['name']; - $menu_item_link = $item['link']; - $menu_item_category = $item['category']; - $menu_item_target = $item['target']; - $menu_item_order = $item['order']; + $menu_item_name = $item['name']; + $menu_item_link = $item['link']; + $menu_item_category = $item['category']; + $menu_item_target = $item['target']; + $menu_item_order = $item['order']; - $errors = array(); + $errors = array(); - // Edit current menu item - if (Request::post('menu_add_item')) { + // Edit current menu item + if (Request::post('menu_add_item')) { - if (Security::check(Request::post('csrf'))) { - - if (trim(Request::post('menu_item_name')) == '') { + if (Security::check(Request::post('csrf'))) { - if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = $item['name']; - if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = $item['link']; - if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $item['category']; - if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = $item['target']; - if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = $item['order']; + if (trim(Request::post('menu_item_name')) == '') { - $errors['menu_item_name_empty'] = __('Required field', 'menu'); - } + if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = $item['name']; + if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = $item['link']; + if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $item['category']; + if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = $item['target']; + if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = $item['order']; - // Update menu item - if (count($errors) == 0) { - MenuAdmin::$menu->update(Request::get('item_id'), - array('name' => Request::post('menu_item_name'), - 'link' => Request::post('menu_item_link'), - 'category' => Security::safeName(Request::post('menu_item_category'), '-', true), - 'target' => Request::post('menu_item_target'), - 'order' => Request::post('menu_item_order'))); + $errors['menu_item_name_empty'] = __('Required field', 'menu'); + } - Request::redirect('index.php?id=menu'); - } + // Update menu item + if (count($errors) == 0) { + MenuAdmin::$menu->update(Request::get('item_id'), + array('name' => Request::post('menu_item_name'), + 'link' => Request::post('menu_item_link'), + 'category' => Security::safeName(Request::post('menu_item_category'), '-', true), + 'target' => Request::post('menu_item_target'), + 'order' => Request::post('menu_item_order'))); - } else { die('csrf detected!'); } + Request::redirect('index.php?id=menu'); + } - } + } else { die('csrf detected!'); } - // Display view - View::factory('box/menu/views/backend/edit') - ->assign('menu_item_name', $menu_item_name) - ->assign('menu_item_link', $menu_item_link) - ->assign('menu_item_category', $menu_item_category) - ->assign('menu_item_target', $menu_item_target) - ->assign('menu_item_order', $menu_item_order) - ->assign('menu_item_target_array', $menu_item_target_array) - ->assign('menu_item_order_array', $menu_item_order_array) - ->assign('errors', $errors) - ->assign('categories', MenuAdmin::getCategories()) - ->assign('pages_list', MenuAdmin::getPages()) - ->assign('components_list', MenuAdmin::getComponents()) - ->display(); - - - break; - - // Add menu item - // ----------------------------------------- - case "add": - - $menu_item_name = ''; - $menu_item_link = ''; - $menu_item_category = ''; - $menu_item_target = ''; - $menu_item_order = ''; - $errors = array(); - - // Get current category - $menu_item_category = $current_category = (Request::get('category')) ? Request::get('category') : '' ; - - // Add new menu item - if (Request::post('menu_add_item')) { - - if (Security::check(Request::post('csrf'))) { - - if (trim(Request::post('menu_item_name')) == '') { - - if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = ''; - if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = ''; - if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $current_category; - if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = ''; - if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = ''; - - $errors['menu_item_name_empty'] = __('Required field', 'menu'); - } - - // Insert new menu item - if (count($errors) == 0) { - MenuAdmin::$menu->insert(array('name' => Request::post('menu_item_name'), - 'link' => Request::post('menu_item_link'), - 'category' => Security::safeName(Request::post('menu_item_category'), '-', true), - 'target' => Request::post('menu_item_target'), - 'order' => Request::post('menu_item_order'))); - - Request::redirect('index.php?id=menu'); - } - - } else { die('csrf detected!'); } - } - - - // Display view - View::factory('box/menu/views/backend/add') - ->assign('menu_item_name', $menu_item_name) - ->assign('menu_item_link', $menu_item_link) - ->assign('menu_item_category', $menu_item_category) - ->assign('menu_item_target', $menu_item_target) - ->assign('menu_item_order', $menu_item_order) - ->assign('menu_item_target_array', $menu_item_target_array) - ->assign('menu_item_order_array', $menu_item_order_array) - ->assign('errors', $errors) - ->assign('categories', MenuAdmin::getCategories()) - ->assign('pages_list', MenuAdmin::getPages()) - ->assign('components_list', MenuAdmin::getComponents()) - ->display(); - - break; - } - - } else { - - // Delete menu item - if (Request::get('delete_item')) { - MenuAdmin::$menu->delete((int)Request::get('delete_item')); - } - - // Display view - View::factory('box/menu/views/backend/index') - ->assign('categories', MenuAdmin::getCategories()) - ->assign('menu', MenuAdmin::$menu) - ->display(); - - } - - } - - - /** - * Get categories - */ - public static function getCategories() { - - $categories = array(); - - $_categories = MenuAdmin::$menu->select(null, 'all', null, array('category')); - - foreach($_categories as $category) { - $categories[] = $category['category']; - } - - return array_unique($categories); - } - - - /** - * Get pages - */ - protected static function getPages() { - - // Init vars - $pages_array = array(); - $count = 0; - - // Get pages table - $pages = new Table('pages'); - - // Get Pages List - $pages_list = $pages->select('[slug!="error404" and status="published"]'); - - foreach ($pages_list as $page) { - - $pages_array[$count]['title'] = Html::toText($page['title']); - $pages_array[$count]['parent'] = $page['parent']; - $pages_array[$count]['date'] = $page['date']; - $pages_array[$count]['author'] = $page['author']; - $pages_array[$count]['slug'] = ($page['slug'] == Option::get('defaultpage')) ? '' : $page['slug'] ; - - if (isset($page['parent'])) { - $c_p = $page['parent']; - } else { - $c_p = ''; - } - - if ($c_p != '') { - $_page = $pages->select('[slug="'.$page['parent'].'"]', null); - - if (isset($_page['title'])) { - $_title = $_page['title']; - } else { - $_title = ''; } - $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; + + // Display view + View::factory('box/menu/views/backend/edit') + ->assign('menu_item_name', $menu_item_name) + ->assign('menu_item_link', $menu_item_link) + ->assign('menu_item_category', $menu_item_category) + ->assign('menu_item_target', $menu_item_target) + ->assign('menu_item_order', $menu_item_order) + ->assign('menu_item_target_array', $menu_item_target_array) + ->assign('menu_item_order_array', $menu_item_order_array) + ->assign('errors', $errors) + ->assign('categories', MenuAdmin::getCategories()) + ->assign('pages_list', MenuAdmin::getPages()) + ->assign('components_list', MenuAdmin::getComponents()) + ->display(); + + break; + + // Add menu item + // ----------------------------------------- + case "add": + + $menu_item_name = ''; + $menu_item_link = ''; + $menu_item_category = ''; + $menu_item_target = ''; + $menu_item_order = ''; + $errors = array(); + + // Get current category + $menu_item_category = $current_category = (Request::get('category')) ? Request::get('category') : '' ; + + // Add new menu item + if (Request::post('menu_add_item')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('menu_item_name')) == '') { + + if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = ''; + if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = ''; + if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $current_category; + if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = ''; + if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = ''; + + $errors['menu_item_name_empty'] = __('Required field', 'menu'); + } + + // Insert new menu item + if (count($errors) == 0) { + MenuAdmin::$menu->insert(array('name' => Request::post('menu_item_name'), + 'link' => Request::post('menu_item_link'), + 'category' => Security::safeName(Request::post('menu_item_category'), '-', true), + 'target' => Request::post('menu_item_target'), + 'order' => Request::post('menu_item_order'))); + + Request::redirect('index.php?id=menu'); + } + + } else { die('csrf detected!'); } + } + + // Display view + View::factory('box/menu/views/backend/add') + ->assign('menu_item_name', $menu_item_name) + ->assign('menu_item_link', $menu_item_link) + ->assign('menu_item_category', $menu_item_category) + ->assign('menu_item_target', $menu_item_target) + ->assign('menu_item_order', $menu_item_order) + ->assign('menu_item_target_array', $menu_item_target_array) + ->assign('menu_item_order_array', $menu_item_order_array) + ->assign('errors', $errors) + ->assign('categories', MenuAdmin::getCategories()) + ->assign('pages_list', MenuAdmin::getPages()) + ->assign('components_list', MenuAdmin::getComponents()) + ->display(); + + break; + } + + } else { + + // Delete menu item + if (Request::get('delete_item')) { + MenuAdmin::$menu->delete((int) Request::get('delete_item')); + } + + // Display view + View::factory('box/menu/views/backend/index') + ->assign('categories', MenuAdmin::getCategories()) + ->assign('menu', MenuAdmin::$menu) + ->display(); + + } + + } + + /** + * Get categories + */ + public static function getCategories() + { + $categories = array(); + + $_categories = MenuAdmin::$menu->select(null, 'all', null, array('category')); + + foreach ($_categories as $category) { + $categories[] = $category['category']; + } + + return array_unique($categories); + } + + /** + * Get pages + */ + protected static function getPages() + { + // Init vars + $pages_array = array(); + $count = 0; + + // Get pages table + $pages = new Table('pages'); + + // Get Pages List + $pages_list = $pages->select('[slug!="error404" and status="published"]'); + + foreach ($pages_list as $page) { + + $pages_array[$count]['title'] = Html::toText($page['title']); + $pages_array[$count]['parent'] = $page['parent']; + $pages_array[$count]['date'] = $page['date']; + $pages_array[$count]['author'] = $page['author']; + $pages_array[$count]['slug'] = ($page['slug'] == Option::get('defaultpage')) ? '' : $page['slug'] ; + + if (isset($page['parent'])) { + $c_p = $page['parent']; + } else { + $c_p = ''; + } + + if ($c_p != '') { + $_page = $pages->select('[slug="'.$page['parent'].'"]', null); + + if (isset($_page['title'])) { + $_title = $_page['title']; } else { - $pages_array[$count]['sort'] = $page['title']; + $_title = ''; } - $_title = ''; - $count++; + $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; + } else { + $pages_array[$count]['sort'] = $page['title']; } - - // Sort pages - $_pages_list = Arr::subvalSort($pages_array, 'sort'); - - // return - return $_pages_list; + $_title = ''; + $count++; } + // Sort pages + $_pages_list = Arr::subvalSort($pages_array, 'sort'); - /** - * Get components - */ - protected static function getComponents() { + // return + return $_pages_list; + } - $components = array(); - - if (count(Plugin::$components) > 0) { - foreach (Plugin::$components as $component) { - if ($component !== 'pages' && $component !== 'sitemap') $components[] = Text::lowercase($component); - } + /** + * Get components + */ + protected static function getComponents() + { + $components = array(); + + if (count(Plugin::$components) > 0) { + foreach (Plugin::$components as $component) { + if ($component !== 'pages' && $component !== 'sitemap') $components[] = Text::lowercase($component); } - - return $components; } - } \ No newline at end of file + return $components; + } + +} diff --git a/plugins/box/menu/menu.plugin.php b/plugins/box/menu/menu.plugin.php index f7db6c0..df60101 100644 --- a/plugins/box/menu/menu.plugin.php +++ b/plugins/box/menu/menu.plugin.php @@ -1,63 +1,58 @@ assign('items', $menu->select('[category="'.$category.'"]', 'all', null, array('id', 'name', 'link', 'target', 'order', 'category'), 'order', 'ASC')) + ->assign('uri', Uri::segments()) + ->assign('defpage', Option::get('defaultpage')) + ->display(); - // Register plugin - Plugin::register( __FILE__, - __('Menu', 'menu'), - __('Menu manager', 'menu'), - '1.0.0', - 'Awilum', - 'http://monstra.org/', - null, - 'box'); - - - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - - // Include Admin - Plugin::admin('menu', 'box'); - } - - // Add Plugin Javascript - Javascript::add('plugins/box/menu/js/menu.js', 'backend'); - - - /** - * Menu Class - */ - class Menu { - - - /** - * Get menu - * - * @param string $category Category name - */ - public static function get($category = '') { - - // Get menu table - $menu = new Table('menu'); - - // Display view - View::factory('box/menu/views/frontend/index') - ->assign('items', $menu->select('[category="'.$category.'"]', 'all', null, array('id', 'name', 'link', 'target', 'order', 'category'), 'order', 'ASC')) - ->assign('uri', Uri::segments()) - ->assign('defpage', Option::get('defaultpage')) - ->display(); - - } - - } \ No newline at end of file +} diff --git a/plugins/box/menu/views/backend/add.view.php b/plugins/box/menu/views/backend/add.view.php index f5dbff1..95b4cf2 100644 --- a/plugins/box/menu/views/backend/add.view.php +++ b/plugins/box/menu/views/backend/add.view.php @@ -7,10 +7,10 @@ - / + /

    - (isset($errors['menu_item_name_empty']) || isset($errors['menu_item_name_empty'])) ? 'input-xlarge error-field' : 'input-xlarge')); @@ -33,17 +33,17 @@ Html::br(). Form::label('menu_item_target', __('Item target', 'menu')). Form::select('menu_item_target', $menu_item_target_array, $menu_item_target, array('class' => 'input-xlarge')) - ); + ); echo ( Html::br(). Form::label('menu_item_order', __('Item order', 'menu')). Form::select('menu_item_order', $menu_item_order_array, $menu_item_order, array('class' => 'input-xlarge')) - ); + ); echo ( Html::br(2). - Form::submit('menu_add_item', __('Save', 'menu'), array('class' => 'btn')). + Form::submit('menu_add_item', __('Save', 'menu'), array('class' => 'btn')). Form::close() ); ?> @@ -56,10 +56,10 @@ \ No newline at end of file + diff --git a/plugins/box/menu/views/backend/edit.view.php b/plugins/box/menu/views/backend/edit.view.php index b73bbb5..26b9e29 100644 --- a/plugins/box/menu/views/backend/edit.view.php +++ b/plugins/box/menu/views/backend/edit.view.php @@ -7,10 +7,10 @@ - / + /

    - (isset($errors['menu_item_name_empty']) || isset($errors['menu_item_name_empty'])) ? 'input-xlarge error-field' : 'input-xlarge')); @@ -33,17 +33,17 @@ Html::br(). Form::label('menu_item_target', __('Item target', 'menu')). Form::select('menu_item_target', $menu_item_target_array, $menu_item_target, array('class' => 'input-xlarge')) - ); + ); echo ( Html::br(). Form::label('menu_item_order', __('Item order', 'menu')). Form::select('menu_item_order', $menu_item_order_array, $menu_item_order, array('class' => 'input-xlarge')) - ); + ); echo ( Html::br(2). - Form::submit('menu_add_item', __('Save', 'menu'), array('class' => 'btn')). + Form::submit('menu_add_item', __('Save', 'menu'), array('class' => 'btn')). Form::close() ); ?> @@ -56,10 +56,10 @@ - diff --git a/plugins/box/menu/views/backend/index.view.php b/plugins/box/menu/views/backend/index.view.php index d7dca46..4ad0886 100644 --- a/plugins/box/menu/views/backend/index.view.php +++ b/plugins/box/menu/views/backend/index.view.php @@ -2,18 +2,16 @@
    count() == 0) { ?> -

    :

    +

    :


    __('Create New Item', 'menu'), 'class' => 'btn btn-small')) - ); + Html::anchor(__('Create New Item', 'menu'), 'index.php?id=menu&action=add', array('title' => __('Create New Item', 'menu'), 'class' => 'btn btn-small')) + ); ?>

    - -

    :

    -
    +
    __('Create New Item', 'menu'), 'class' => 'btn btn-small')) - ); + Html::anchor(__('Create New Item', 'menu'), 'index.php?id=menu&action=add'.$category_to_add , array('title' => __('Create New Item', 'menu'), 'class' => 'btn btn-small')) + ); ?>

    - @@ -75,6 +72,6 @@ -
    +
    - \ No newline at end of file + diff --git a/plugins/box/menu/views/frontend/index.view.php b/plugins/box/menu/views/frontend/index.view.php index 838a1c0..5644908 100644 --- a/plugins/box/menu/views/frontend/index.view.php +++ b/plugins/box/menu/views/frontend/index.view.php @@ -1,5 +1,5 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/pages/languages/de.lang.php b/plugins/box/pages/languages/de.lang.php index 9173891..41a1e7e 100644 --- a/plugins/box/pages/languages/de.lang.php +++ b/plugins/box/pages/languages/de.lang.php @@ -1,54 +1,54 @@ - array( - 'Pages' => 'Seiten', - 'Pages manager' => 'Seiten Manager', - 'Content' => 'Inhalt', - 'Create New Page' => 'Neue Seite erstellen', - 'New Page' => 'Neue Seite', - 'Edit Page' => 'Seite bearbeiten', - 'Date' => 'Datum', - 'Clone' => 'Klonen', - 'Edit' => 'Bearbeiten', - 'Delete' => 'Löschen', - 'Delete page: :page' => 'Lösche Seite: :page', - 'Title' => 'Titel', - 'Name' => 'Name', - 'Author' => 'Author', - 'Name (slug)' => 'Name (slug)', - 'Description' => 'Beschreibung', - 'Keywords' => 'Schlagwörter', - 'Parent' => 'Übergeordnete', - 'Template' => 'Vorlage', - 'Year' => 'Jahr', - 'Day' => 'Tag', - 'Month' => 'Monat', - 'Hour' => 'Stunde', - 'Minute' => 'Minute', - 'Second' => 'Sekunde', - 'This field should not be empty' => 'Dieses Feld darf nicht leer sein', - 'This page already exists' => 'Diese Seite existiert bereits', - 'Extra' => 'Extra', - 'Save' => 'Speichern', - 'Save and Exit' => 'Speichern und Beenden', - 'Your changes to the page :page have been saved.' => 'Deine Änderungen an der Seite :page wurden gespeichert.', - 'The page :page cloned.' => 'Die Seite :page wurde gekloned.', - 'Status' => 'Status', - 'Actions' => 'Aktionen', - 'Add' => 'Hinzufügen', - 'Published' => 'Veröffentlicht', - 'Draft' => 'Entwurf', - 'Published on' => 'Veröffentlicht am', - 'Edit 404 Page' => 'Bearbeite 404-Fehler Seite', - 'Page :page deleted' => 'Seite :page wurde gelöscht', - 'Search Engines Robots' => 'Suchmaschinen-Roboter', - 'Page' => 'Seite', - 'Metadata' => 'Metadata', - 'Settings' => 'Einstellungen', - 'Required field' => 'Pflichtfeld', - 'Access' => 'Zugriff', - 'Public' => 'Öffentlichkeit', - 'Registered' => 'Eingetragen', - ) - ); \ No newline at end of file + array( + 'Pages' => 'Seiten', + 'Pages manager' => 'Seiten Manager', + 'Content' => 'Inhalt', + 'Create New Page' => 'Neue Seite erstellen', + 'New Page' => 'Neue Seite', + 'Edit Page' => 'Seite bearbeiten', + 'Date' => 'Datum', + 'Clone' => 'Klonen', + 'Edit' => 'Bearbeiten', + 'Delete' => 'Löschen', + 'Delete page: :page' => 'Lösche Seite: :page', + 'Title' => 'Titel', + 'Name' => 'Name', + 'Author' => 'Author', + 'Name (slug)' => 'Name (slug)', + 'Description' => 'Beschreibung', + 'Keywords' => 'Schlagwörter', + 'Parent' => 'Übergeordnete', + 'Template' => 'Vorlage', + 'Year' => 'Jahr', + 'Day' => 'Tag', + 'Month' => 'Monat', + 'Hour' => 'Stunde', + 'Minute' => 'Minute', + 'Second' => 'Sekunde', + 'This field should not be empty' => 'Dieses Feld darf nicht leer sein', + 'This page already exists' => 'Diese Seite existiert bereits', + 'Extra' => 'Extra', + 'Save' => 'Speichern', + 'Save and Exit' => 'Speichern und Beenden', + 'Your changes to the page :page have been saved.' => 'Deine Änderungen an der Seite :page wurden gespeichert.', + 'The page :page cloned.' => 'Die Seite :page wurde gekloned.', + 'Status' => 'Status', + 'Actions' => 'Aktionen', + 'Add' => 'Hinzufügen', + 'Published' => 'Veröffentlicht', + 'Draft' => 'Entwurf', + 'Published on' => 'Veröffentlicht am', + 'Edit 404 Page' => 'Bearbeite 404-Fehler Seite', + 'Page :page deleted' => 'Seite :page wurde gelöscht', + 'Search Engines Robots' => 'Suchmaschinen-Roboter', + 'Page' => 'Seite', + 'Metadata' => 'Metadata', + 'Settings' => 'Einstellungen', + 'Required field' => 'Pflichtfeld', + 'Access' => 'Zugriff', + 'Public' => 'Öffentlichkeit', + 'Registered' => 'Eingetragen', + ) + ); diff --git a/plugins/box/pages/languages/en.lang.php b/plugins/box/pages/languages/en.lang.php index f7b2e62..4b28cf6 100644 --- a/plugins/box/pages/languages/en.lang.php +++ b/plugins/box/pages/languages/en.lang.php @@ -2,15 +2,15 @@ return array( 'pages' => array( - 'Pages' => 'Pages', - 'Pages manager' => 'Pages manager', + 'Pages' => 'Pages', + 'Pages manager' => 'Pages manager', 'Content' => 'Content', 'Create New Page' => 'Create New Page', 'New Page' => 'New Page', - 'Edit Page' => 'Edit Page', + 'Edit Page' => 'Edit Page', 'Date' => 'Date', 'Clone' => 'Clone', - 'Edit' => 'Edit', + 'Edit' => 'Edit', 'Delete' => 'Delete', 'Delete page: :page' => 'Delete page: :page', 'Title' => 'Title', @@ -51,4 +51,4 @@ 'Public' => 'Public', 'Registered' => 'Registered', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/pages/languages/it.lang.php b/plugins/box/pages/languages/it.lang.php index 4594470..271aa5a 100644 --- a/plugins/box/pages/languages/it.lang.php +++ b/plugins/box/pages/languages/it.lang.php @@ -4,13 +4,13 @@ 'pages' => array( 'Pages' => 'Pagine', 'Pages manager' => 'Gestione pagine', - 'Content' => 'Contenuto', + 'Content' => 'Contenuto', 'Create New Page' => 'Crea Nuova Pagina', 'New Page' => 'Nuova Pagina', - 'Edit Page' => 'Modifica Pagina', + 'Edit Page' => 'Modifica Pagina', 'Date' => 'Data', 'Clone' => 'Clona', - 'Edit' => 'Modifica', + 'Edit' => 'Modifica', 'Delete' => 'Elimina', 'Delete page: :page' => 'Elimina pagina: :page', 'Title' => 'Titolo', @@ -51,4 +51,4 @@ 'Public' => 'Pubblico', 'Registered' => 'Registrato', ), - ); \ No newline at end of file + ); diff --git a/plugins/box/pages/languages/lt.lang.php b/plugins/box/pages/languages/lt.lang.php index 87d9367..74b2910 100644 --- a/plugins/box/pages/languages/lt.lang.php +++ b/plugins/box/pages/languages/lt.lang.php @@ -7,10 +7,10 @@ 'Content' => 'Turinys', 'Create New page' => 'Sukurti Naują Puslapį', 'New Page' => 'Naujas Puslapis', - 'Edit Page' => 'Redaguoti Puslapį', + 'Edit Page' => 'Redaguoti Puslapį', 'Date' => 'Data', 'Clone' => 'Klonuoti', - 'Edit' => 'Redaguoti', + 'Edit' => 'Redaguoti', 'Delete' => 'Ištrinti', 'Delete page: :page' => 'Ištrinti puslapį :page', 'Title' => 'Antraštė', @@ -51,4 +51,4 @@ 'Public' => 'Viešas', 'Registered' => 'Registruotas', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/pages/languages/pt-br.lang.php b/plugins/box/pages/languages/pt-br.lang.php index 53003e8..bf4ed52 100644 --- a/plugins/box/pages/languages/pt-br.lang.php +++ b/plugins/box/pages/languages/pt-br.lang.php @@ -7,10 +7,10 @@ 'Content' => 'Conteúdo', 'Create new page' => 'Criar nova página', 'New page' => 'Nova página', - 'Edit page' => 'Editar página', + 'Edit page' => 'Editar página', 'Date' => 'Data', 'Clone' => 'Clonar', - 'Edit' => 'Editar', + 'Edit' => 'Editar', 'Delete' => 'Deletar', 'Delete page: :page' => 'Deletar a página: :page', 'Title' => 'Título', @@ -51,4 +51,4 @@ 'Public' => 'Público', 'Registered' => 'Registrado', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/pages/languages/ru.lang.php b/plugins/box/pages/languages/ru.lang.php index b45febc..db3fb5d 100644 --- a/plugins/box/pages/languages/ru.lang.php +++ b/plugins/box/pages/languages/ru.lang.php @@ -4,13 +4,13 @@ 'pages' => array( 'Pages' => 'Страницы', 'Pages manager' => 'Менеджер страниц', - 'Content' => 'Контент', + 'Content' => 'Контент', 'Create New Page' => 'Создать новую страницу', 'New Page' => 'Новая страница', - 'Edit Page' => 'Редактирование страницы', + 'Edit Page' => 'Редактирование страницы', 'Date' => 'Дата', 'Clone' => 'Клонировать', - 'Edit' => 'Редактировать', + 'Edit' => 'Редактировать', 'Delete' => 'Удалить', 'Delete page: :page' => 'Удалить страницу: :page', 'Title' => 'Заголовок', @@ -51,4 +51,4 @@ 'Public' => 'Публичный', 'Registered' => 'Зарегистрированным', ), - ); \ No newline at end of file + ); diff --git a/plugins/box/pages/languages/uk.lang.php b/plugins/box/pages/languages/uk.lang.php index 9179ae1..345f1f8 100644 --- a/plugins/box/pages/languages/uk.lang.php +++ b/plugins/box/pages/languages/uk.lang.php @@ -4,13 +4,13 @@ 'pages' => array( 'Pages' => 'Сторінки', 'Pages manager' => 'Менеджер сторінок', - 'Content' => 'Контент', + 'Content' => 'Контент', 'Create New Page' => 'Створити нову сторінку', 'New Page' => 'Нова сторінка', - 'Edit Page' => 'Редагування сторінки', + 'Edit Page' => 'Редагування сторінки', 'Date' => 'Дата', 'Clone' => 'Клонувати', - 'Edit' => 'Редагувати', + 'Edit' => 'Редагувати', 'Delete' => 'Видалити', 'Delete page: :page' => 'Видалити сторінку: :page', 'Title' => 'Заголовок', @@ -51,4 +51,4 @@ 'Public' => 'Публічний', 'Registered' => 'Зареєстрованим', ), - ); \ No newline at end of file + ); diff --git a/plugins/box/pages/pages.admin.php b/plugins/box/pages/pages.admin.php index 7612a8e..1f34154 100755 --- a/plugins/box/pages/pages.admin.php +++ b/plugins/box/pages/pages.admin.php @@ -1,574 +1,562 @@ updateWhere('[slug="'.Request::post('slug').'"]', array('expand' => Request::post('expand'))); + Request::shutdown(); + } else { die('csrf detected!'); } + } + } + /** + * Pages admin function + */ + public static function main() + { + $current_theme = Option::get('theme_site_name'); + $site_url = Option::get('siteurl'); - /** - * Pages tables - * - * @var object - */ - public static $pages = null; + $templates_path = THEMES_SITE; + $errors = array(); - /** - * _pageExpandAjax - */ - public static function _pageExpandAjax() { - if (Request::post('slug')) { - if (Security::check(Request::post('token'))) { - $pages = new Table('pages'); - $pages->updateWhere('[slug="'.Request::post('slug').'"]', array('expand' => Request::post('expand'))); - Request::shutdown(); - } else { die('csrf detected!'); } - } + $pages = new Table('pages'); + PagesAdmin::$pages = $pages; + + $users = new Table('users'); + $user = $users->select('[id='.Session::get('user_id').']', null); + + $user['firstname'] = Html::toText($user['firstname']); + $user['lastname'] = Html::toText($user['lastname']); + + // Page author + if ( ! empty($user['firstname'])) { + $author = (empty($user['lastname'])) ? $user['firstname'] : $user['firstname'].' '.$user['lastname']; + } else { + $author = Session::get('user_login'); } - - /** - * Pages admin function - */ - public static function main() { + // Status array + $status_array = array('published' => __('Published', 'pages'), + 'draft' => __('Draft', 'pages')); - $current_theme = Option::get('theme_site_name'); - $site_url = Option::get('siteurl'); + // Access array + $access_array = array('public' => __('Public', 'pages'), + 'registered' => __('Registered', 'pages')); - $templates_path = THEMES_SITE; + // Check for get actions + // --------------------------------------------- + if (Request::get('action')) { - $errors = array(); + // Switch actions + // ----------------------------------------- + switch (Request::get('action')) { - $pages = new Table('pages'); - PagesAdmin::$pages = $pages; + // Clone page + // ------------------------------------- + case "clone_page": - $users = new Table('users'); - $user = $users->select('[id='.Session::get('user_id').']', null); + if (Security::check(Request::get('token'))) { - $user['firstname'] = Html::toText($user['firstname']); - $user['lastname'] = Html::toText($user['lastname']); + // Generate rand page name + $rand_page_name = Request::get('name').'_clone_'.date("Ymd_His"); - // Page author - if ( ! empty($user['firstname'])) { - $author = (empty($user['lastname'])) ? $user['firstname'] : $user['firstname'].' '.$user['lastname']; - } else { - $author = Session::get('user_login'); - } + // Get original page + $orig_page = $pages->select('[slug="'.Request::get('name').'"]', null); + // Generate rand page title + $rand_page_title = $orig_page['title'].' [copy]'; - // Status array - $status_array = array('published' => __('Published', 'pages'), - 'draft' => __('Draft', 'pages')); + // Clone page + if ($pages->insert(array('slug' => $rand_page_name, + 'template' => $orig_page['template'], + 'parent' => $orig_page['parent'], + 'robots_index' => $orig_page['robots_index'], + 'robots_follow'=> $orig_page['robots_follow'], + 'status' => $orig_page['status'], + 'access' => (isset($orig_page['access'])) ? $orig_page['access'] : 'public', + 'expand' => (isset($orig_page['expand'])) ? $orig_page['expand'] : '0', + 'title' => $rand_page_title, + 'description' => $orig_page['description'], + 'keywords' => $orig_page['keywords'], + 'date' => $orig_page['date'], + 'author' => $orig_page['author']))) { + // Get cloned page ID + $last_id = $pages->lastId(); - // Access array - $access_array = array('public' => __('Public', 'pages'), - 'registered' => __('Registered', 'pages')); + // Save cloned page content + File::setContent(STORAGE . DS . 'pages' . DS . $last_id . '.page.txt', + File::getContent(STORAGE . DS . 'pages' . DS . $orig_page['id'] . '.page.txt')); - - // Check for get actions - // --------------------------------------------- - if (Request::get('action')) { - - // Switch actions - // ----------------------------------------- - switch (Request::get('action')) { + // Send notification + Notification::set('success', __('The page :page cloned.', 'pages', array(':page' => Security::safeName(Request::get('name'), '-', true)))); + } - // Clone page - // ------------------------------------- - case "clone_page": + // Run add extra actions + Action::run('admin_pages_action_clone'); + // Redirect + Request::redirect('index.php?id=pages'); - if (Security::check(Request::get('token'))) { - - // Generate rand page name - $rand_page_name = Request::get('name').'_clone_'.date("Ymd_His"); + } else { die('csrf detected!'); } - // Get original page - $orig_page = $pages->select('[slug="'.Request::get('name').'"]', null); + break; - // Generate rand page title - $rand_page_title = $orig_page['title'].' [copy]'; + // Add page + // ------------------------------------- + case "add_page": - // Clone page - if ($pages->insert(array('slug' => $rand_page_name, - 'template' => $orig_page['template'], - 'parent' => $orig_page['parent'], - 'robots_index' => $orig_page['robots_index'], - 'robots_follow'=> $orig_page['robots_follow'], - 'status' => $orig_page['status'], - 'access' => (isset($orig_page['access'])) ? $orig_page['access'] : 'public', - 'expand' => (isset($orig_page['expand'])) ? $orig_page['expand'] : '0', - 'title' => $rand_page_title, - 'description' => $orig_page['description'], - 'keywords' => $orig_page['keywords'], - 'date' => $orig_page['date'], - 'author' => $orig_page['author']))) { - - // Get cloned page ID - $last_id = $pages->lastId(); + // Add page + if (Request::post('add_page') || Request::post('add_page_and_exit')) { - // Save cloned page content - File::setContent(STORAGE . DS . 'pages' . DS . $last_id . '.page.txt', - File::getContent(STORAGE . DS . 'pages' . DS . $orig_page['id'] . '.page.txt')); + if (Security::check(Request::post('csrf'))) { - // Send notification - Notification::set('success', __('The page :page cloned.', 'pages', array(':page' => Security::safeName(Request::get('name'), '-', true)))); + // Get parent page + if (Request::post('pages') == '0') { + $parent_page = ''; + } else { + $parent_page = Request::post('pages'); } - // Run add extra actions - Action::run('admin_pages_action_clone'); + // Validate + //-------------- + if (trim(Request::post('page_name')) == '') $errors['pages_empty_name'] = __('Required field', 'pages'); + if (trim(Request::post('page_title')) == '') $errors['pages_empty_title'] = __('Required field', 'pages'); + if (count($pages->select('[slug="'.Security::safeName(Request::post('page_name'), '-', true).'"]')) != 0) $errors['pages_exists'] = __('This page already exists', 'pages'); + + // Prepare date + if (Valid::date(Request::post('page_date'))) { + $date = strtotime(Request::post('page_date')); + } else { + $date = time(); + } + + if (Request::post('robots_index')) $robots_index = 'noindex'; else $robots_index = 'index'; + if (Request::post('robots_follow')) $robots_follow = 'nofollow'; else $robots_follow = 'follow'; + + // If no errors then try to save + if (count($errors) == 0) { + + // Insert new page + if ($pages->insert(array('slug' => Security::safeName(Request::post('page_name'), '-', true), + 'template' => Request::post('templates'), + 'parent' => $parent_page, + 'status' => Request::post('status'), + 'access' => Request::post('access'), + 'expand' => '0', + 'robots_index' => $robots_index, + 'robots_follow'=> $robots_follow, + 'title' => Request::post('page_title'), + 'description' => Request::post('page_description'), + 'keywords' => Request::post('page_keywords'), + 'date' => $date, + 'author' => $author))) { + + // Get inserted page ID + $last_id = $pages->lastId(); + + // Save content + File::setContent(STORAGE . DS . 'pages' . DS . $last_id . '.page.txt', XML::safe(Request::post('editor'))); + + // Send notification + Notification::set('success', __('Your changes to the page :page have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true)))); + } + + // Run add extra actions + Action::run('admin_pages_action_add'); + + // Redirect + if (Request::post('add_page_and_exit')) { + Request::redirect('index.php?id=pages'); + } else { + Request::redirect('index.php?id=pages&action=edit_page&name='.Security::safeName(Request::post('page_name'), '-', true)); + } + } + + } else { die('csrf detected!'); } + + } + + // Get all pages + $pages_list = $pages->select('[slug!="error404" and parent=""]'); + $pages_array[] = '-none-'; + foreach ($pages_list as $page) { + $pages_array[$page['slug']] = $page['title']; + } + + // Get all templates + $templates_list = File::scan($templates_path, '.template.php'); + foreach ($templates_list as $file) { + $templates_array[basename($file, '.template.php')] = basename($file, '.template.php'); + } + + // Save fields + if (Request::post('page_name')) $post_name = Request::post('page_name'); else $post_name = ''; + if (Request::post('page_title')) $post_title = Request::post('page_title'); else $post_title = ''; + if (Request::post('page_keywords')) $post_keywords = Request::post('page_keywords'); else $post_keywords = ''; + if (Request::post('page_description')) $post_description = Request::post('page_description'); else $post_description = ''; + if (Request::post('editor')) $post_content = Request::post('editor'); else $post_content = ''; + if (Request::post('templates')) $post_template = Request::post('templates'); else $post_template = 'index'; + if (Request::post('status')) $post_status = Request::post('status'); else $post_status = 'published'; + if (Request::post('access')) $post_access = Request::post('access'); else $post_access = 'public'; + if (Request::post('pages')) $parent_page = Request::post('pages'); else if(Request::get('parent_page')) $parent_page = Request::get('parent_page'); else $parent_page = ''; + if (Request::post('robots_index')) $post_robots_index = true; else $post_robots_index = false; + if (Request::post('robots_follow')) $post_robots_follow = true; else $post_robots_follow = false; + //-------------- + + // Generate date + $date = Date::format(time(), 'Y-m-d H:i:s'); + + // Set Tabs State - page + Notification::setNow('page', 'page'); + + // Display view + View::factory('box/pages/views/backend/add') + ->assign('post_name', $post_name) + ->assign('post_title', $post_title) + ->assign('post_description', $post_description) + ->assign('post_keywords', $post_keywords) + ->assign('post_content', $post_content) + ->assign('pages_array', $pages_array) + ->assign('parent_page', $parent_page) + ->assign('templates_array', $templates_array) + ->assign('post_template', $post_template) + ->assign('post_status', $post_status) + ->assign('post_access', $post_access) + ->assign('status_array', $status_array) + ->assign('access_array', $access_array) + ->assign('date', $date) + ->assign('post_robots_index', $post_robots_index) + ->assign('post_robots_follow', $post_robots_follow) + ->assign('errors', $errors) + ->display(); + + break; + + // Edit page + // ------------------------------------- + case "edit_page": + + if (Request::post('edit_page') || Request::post('edit_page_and_exit')) { + + if (Security::check(Request::post('csrf'))) { + + // Get pages parent + if (Request::post('pages') == '0') { + $parent_page = ''; + } else { + $parent_page = Request::post('pages'); + } + + // Save field + $post_parent = Request::post('pages'); + + // Validate + //-------------- + if (trim(Request::post('page_name')) == '') $errors['pages_empty_name'] = __('Required field', 'pages'); + if ((count($pages->select('[slug="'.Security::safeName(Request::post('page_name'), '-', true).'"]')) != 0) and (Security::safeName(Request::post('page_old_name'), '-', true) !== Security::safeName(Request::post('page_name'), '-', true))) $errors['pages_exists'] = __('This page already exists', 'pages'); + if (trim(Request::post('page_title')) == '') $errors['pages_empty_title'] = __('Required field', 'pages'); + + // Save fields + if (Request::post('page_name')) $post_name = Request::post('page_name'); else $post_name = ''; + if (Request::post('page_title')) $post_title = Request::post('page_title'); else $post_title = ''; + if (Request::post('page_keywords')) $post_keywords = Request::post('page_keywords'); else $post_keywords = ''; + if (Request::post('page_description')) $post_description = Request::post('page_description'); else $post_description = ''; + if (Request::post('editor')) $post_content = Request::post('editor'); else $post_content = ''; + if (Request::post('templates')) $post_template = Request::post('templates'); else $post_template = 'index'; + if (Request::post('status')) $post_status = Request::post('status'); else $post_status = 'published'; + if (Request::post('access')) $post_access = Request::post('access'); else $post_access = 'public'; + if (Request::post('robots_index')) $post_robots_index = true; else $post_robots_index = false; + if (Request::post('robots_follow')) $post_robots_follow = true; else $post_robots_follow = false; + //-------------- + + // Prepare date + if (Valid::date(Request::post('page_date'))) { + $date = strtotime(Request::post('page_date')); + } else { + $date = time(); + } + + if (Request::post('robots_index')) $robots_index = 'noindex'; else $robots_index = 'index'; + if (Request::post('robots_follow')) $robots_follow = 'nofollow'; else $robots_follow = 'follow'; + + if (count($errors) == 0) { + + // Update parents in all childrens + if ((Security::safeName(Request::post('page_name'), '-', true)) !== (Security::safeName(Request::post('page_old_name'), '-', true)) and (Request::post('old_parent') == '')) { + + $pages->updateWhere('[parent="'.Request::get('name').'"]', array('parent' => Text::translitIt(trim(Request::post('page_name'))))); + + if ($pages->updateWhere('[slug="'.Request::get('name').'"]', + array('slug' => Security::safeName(Request::post('page_name'), '-', true), + 'template' => Request::post('templates'), + 'parent' => $parent_page, + 'title' => Request::post('page_title'), + 'description' => Request::post('page_description'), + 'keywords' => Request::post('page_keywords'), + 'robots_index' => $robots_index, + 'robots_follow'=> $robots_follow, + 'status' => Request::post('status'), + 'access' => Request::post('ascess'), + 'date' => $date, + 'author' => $author))) { + + File::setContent(STORAGE . DS . 'pages' . DS . Request::post('page_id') . '.page.txt', XML::safe(Request::post('editor'))); + Notification::set('success', __('Your changes to the page :page have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true)))); + } + + // Run edit extra actions + Action::run('admin_pages_action_edit'); + + } else { + + if ($pages->updateWhere('[slug="'.Request::get('name').'"]', + array('slug' => Security::safeName(Request::post('page_name'), '-', true), + 'template' => Request::post('templates'), + 'parent' => $parent_page, + 'title' => Request::post('page_title'), + 'description' => Request::post('page_description'), + 'keywords' => Request::post('page_keywords'), + 'robots_index' => $robots_index, + 'robots_follow'=> $robots_follow, + 'status' => Request::post('status'), + 'access' => Request::post('access'), + 'date' => $date, + 'author' => $author))) { + + File::setContent(STORAGE . DS . 'pages' . DS . Request::post('page_id') . '.page.txt', XML::safe(Request::post('editor'))); + Notification::set('success', __('Your changes to the page :page have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true)))); + } + + // Run edit extra actions + Action::run('admin_pages_action_edit'); + } + + // Redirect + if (Request::post('edit_page_and_exit')) { + Request::redirect('index.php?id=pages'); + } else { + Request::redirect('index.php?id=pages&action=edit_page&name='.Security::safeName(Request::post('page_name'), '-', true)); + } + } + + } else { die('csrf detected!'); } + } + + // Get all pages + $pages_list = $pages->select(); + $pages_array[] = '-none-'; + // Foreach pages find page whithout parent + foreach ($pages_list as $page) { + if (isset($page['parent'])) { + $c_p = $page['parent']; + } else { + $c_p = ''; + } + if ($c_p == '') { + // error404 is system "constant" and no child for it + if ($page['slug'] !== 'error404' && $page['slug'] !== Request::get('name')) { + $pages_array[$page['slug']] = $page['title']; + } + } + } + + // Get all templates + $templates_list = File::scan($templates_path,'.template.php'); + foreach ($templates_list as $file) { + $templates_array[basename($file,'.template.php')] = basename($file, '.template.php'); + } + + $page = $pages->select('[slug="'.Request::get('name').'"]', null); + + if ($page) { + + $page_content = File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt'); + + // Safe fields or load fields + if (Request::post('page_name')) $slug_to_edit = Request::post('page_name'); else $slug_to_edit = $page['slug']; + if (Request::post('page_title')) $title_to_edit = Request::post('page_title'); else $title_to_edit = $page['title']; + if (Request::post('page_description')) $description_to_edit = Request::post('page_description'); else $description_to_edit = $page['description']; + if (Request::post('page_keywords')) $keywords_to_edit = Request::post('page_keywords'); else $keywords_to_edit = $page['keywords']; + if (Request::post('editor')) $to_edit = Request::post('editor'); else $to_edit = Text::toHtml($page_content); + + if (Request::post('robots_index')) $post_robots_index = true; else if ($page['robots_index'] == 'noindex') $post_robots_index = true; else $post_robots_index = false; + if (Request::post('robots_follow')) $post_robots_follow = true; else if ($page['robots_follow'] == 'nofollow') $post_robots_follow = true; else $post_robots_follow = false; + + if (Request::post('pages')) { + // Get pages parent + if (Request::post('pages') == '-none-') { + $parent_page = ''; + } else { + $parent_page = Request::post('pages'); + } + // Save field + $parent_page = Request::post('pages'); + } else { + $parent_page = $page['parent']; + } + if (Request::post('templates')) $template = Request::post('templates'); else $template = $page['template']; + if (Request::post('status')) $status = Request::post('status'); else $status = $page['status']; + if (Request::post('access')) $access = Request::post('access'); else $access = (isset($page['access'])) ? $page['access'] : 'public'; + + // Generate date + $date = Request::post('date') ? Request::post('date') : Date::format($page['date'], 'Y-m-d H:i:s'); + + Notification::setNow('page', 'page'); + + // Display view + View::factory('box/pages/views/backend/edit') + ->assign('slug_to_edit', $slug_to_edit) + ->assign('title_to_edit', $title_to_edit) + ->assign('description_to_edit', $description_to_edit) + ->assign('keywords_to_edit', $keywords_to_edit) + ->assign('page', $page) + ->assign('to_edit', $to_edit) + ->assign('pages_array', $pages_array) + ->assign('parent_page', $parent_page) + ->assign('templates_array', $templates_array) + ->assign('template', $template) + ->assign('status_array', $status_array) + ->assign('access_array', $access_array) + ->assign('status', $status) + ->assign('access', $access) + ->assign('date', $date) + ->assign('post_robots_index', $post_robots_index) + ->assign('post_robots_follow', $post_robots_follow) + ->assign('errors', $errors) + ->display(); + } + + break; + + // Delete page + // ------------------------------------- + case "delete_page": + + // Error 404 page can not be removed + if (Request::get('name') !== 'error404') { + + if (Security::check(Request::get('token'))) { + + // Get specific page + $page = $pages->select('[slug="'.Request::get('name').'"]', null); + + // Delete page and update fields + if ($pages->deleteWhere('[slug="'.$page['slug'].'" ]')) { + + $_pages = $pages->select('[parent="'.$page['slug'].'"]'); + + if ( ! empty($_pages)) { + foreach ($_pages as $_page) { + $pages->updateWhere('[slug="'.$_page['slug'].'"]', array('parent' => '')); + } + } + + File::delete(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt'); + Notification::set('success', __('Page :page deleted', 'pages', array(':page' => Html::toText($page['title'])))); + } + + // Run delete extra actions + Action::run('admin_pages_action_delete'); // Redirect Request::redirect('index.php?id=pages'); } else { die('csrf detected!'); } - - break; - - // Add page - // ------------------------------------- - case "add_page": - - // Add page - if (Request::post('add_page') || Request::post('add_page_and_exit')) { - - if (Security::check(Request::post('csrf'))) { - - // Get parent page - if (Request::post('pages') == '0') { - $parent_page = ''; - } else { - $parent_page = Request::post('pages'); - } - - - // Validate - //-------------- - if (trim(Request::post('page_name')) == '') $errors['pages_empty_name'] = __('Required field', 'pages'); - if (trim(Request::post('page_title')) == '') $errors['pages_empty_title'] = __('Required field', 'pages'); - if (count($pages->select('[slug="'.Security::safeName(Request::post('page_name'), '-', true).'"]')) != 0) $errors['pages_exists'] = __('This page already exists', 'pages'); - - - // Prepare date - if (Valid::date(Request::post('page_date'))) { - $date = strtotime(Request::post('page_date')); - } else { - $date = time(); - } - - if (Request::post('robots_index')) $robots_index = 'noindex'; else $robots_index = 'index'; - if (Request::post('robots_follow')) $robots_follow = 'nofollow'; else $robots_follow = 'follow'; - - // If no errors then try to save - if (count($errors) == 0) { - - // Insert new page - if ($pages->insert(array('slug' => Security::safeName(Request::post('page_name'), '-', true), - 'template' => Request::post('templates'), - 'parent' => $parent_page, - 'status' => Request::post('status'), - 'access' => Request::post('access'), - 'expand' => '0', - 'robots_index' => $robots_index, - 'robots_follow'=> $robots_follow, - 'title' => Request::post('page_title'), - 'description' => Request::post('page_description'), - 'keywords' => Request::post('page_keywords'), - 'date' => $date, - 'author' => $author))) { - - // Get inserted page ID - $last_id = $pages->lastId(); - - // Save content - File::setContent(STORAGE . DS . 'pages' . DS . $last_id . '.page.txt', XML::safe(Request::post('editor'))); - - // Send notification - Notification::set('success', __('Your changes to the page :page have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true)))); - } - - // Run add extra actions - Action::run('admin_pages_action_add'); - - // Redirect - if (Request::post('add_page_and_exit')) { - Request::redirect('index.php?id=pages'); - } else { - Request::redirect('index.php?id=pages&action=edit_page&name='.Security::safeName(Request::post('page_name'), '-', true)); - } - } - - } else { die('csrf detected!'); } - - } - - // Get all pages - $pages_list = $pages->select('[slug!="error404" and parent=""]'); - $pages_array[] = '-none-'; - foreach ($pages_list as $page) { - $pages_array[$page['slug']] = $page['title']; - } - - // Get all templates - $templates_list = File::scan($templates_path, '.template.php'); - foreach ($templates_list as $file) { - $templates_array[basename($file, '.template.php')] = basename($file, '.template.php'); - } - - // Save fields - if (Request::post('page_name')) $post_name = Request::post('page_name'); else $post_name = ''; - if (Request::post('page_title')) $post_title = Request::post('page_title'); else $post_title = ''; - if (Request::post('page_keywords')) $post_keywords = Request::post('page_keywords'); else $post_keywords = ''; - if (Request::post('page_description')) $post_description = Request::post('page_description'); else $post_description = ''; - if (Request::post('editor')) $post_content = Request::post('editor'); else $post_content = ''; - if (Request::post('templates')) $post_template = Request::post('templates'); else $post_template = 'index'; - if (Request::post('status')) $post_status = Request::post('status'); else $post_status = 'published'; - if (Request::post('access')) $post_access = Request::post('access'); else $post_access = 'public'; - if (Request::post('pages')) $parent_page = Request::post('pages'); else if(Request::get('parent_page')) $parent_page = Request::get('parent_page'); else $parent_page = ''; - if (Request::post('robots_index')) $post_robots_index = true; else $post_robots_index = false; - if (Request::post('robots_follow')) $post_robots_follow = true; else $post_robots_follow = false; - //-------------- - - // Generate date - $date = Date::format(time(), 'Y-m-d H:i:s'); - - // Set Tabs State - page - Notification::setNow('page', 'page'); - - // Display view - View::factory('box/pages/views/backend/add') - ->assign('post_name', $post_name) - ->assign('post_title', $post_title) - ->assign('post_description', $post_description) - ->assign('post_keywords', $post_keywords) - ->assign('post_content', $post_content) - ->assign('pages_array', $pages_array) - ->assign('parent_page', $parent_page) - ->assign('templates_array', $templates_array) - ->assign('post_template', $post_template) - ->assign('post_status', $post_status) - ->assign('post_access', $post_access) - ->assign('status_array', $status_array) - ->assign('access_array', $access_array) - ->assign('date', $date) - ->assign('post_robots_index', $post_robots_index) - ->assign('post_robots_follow', $post_robots_follow) - ->assign('errors', $errors) - ->display(); - - break; - - // Edit page - // ------------------------------------- - case "edit_page": - - if (Request::post('edit_page') || Request::post('edit_page_and_exit')) { - - if (Security::check(Request::post('csrf'))) { - - // Get pages parent - if (Request::post('pages') == '0') { - $parent_page = ''; - } else { - $parent_page = Request::post('pages'); - } - - // Save field - $post_parent = Request::post('pages'); - - - // Validate - //-------------- - if (trim(Request::post('page_name')) == '') $errors['pages_empty_name'] = __('Required field', 'pages'); - if ((count($pages->select('[slug="'.Security::safeName(Request::post('page_name'), '-', true).'"]')) != 0) and (Security::safeName(Request::post('page_old_name'), '-', true) !== Security::safeName(Request::post('page_name'), '-', true))) $errors['pages_exists'] = __('This page already exists', 'pages'); - if (trim(Request::post('page_title')) == '') $errors['pages_empty_title'] = __('Required field', 'pages'); - - // Save fields - if (Request::post('page_name')) $post_name = Request::post('page_name'); else $post_name = ''; - if (Request::post('page_title')) $post_title = Request::post('page_title'); else $post_title = ''; - if (Request::post('page_keywords')) $post_keywords = Request::post('page_keywords'); else $post_keywords = ''; - if (Request::post('page_description')) $post_description = Request::post('page_description'); else $post_description = ''; - if (Request::post('editor')) $post_content = Request::post('editor'); else $post_content = ''; - if (Request::post('templates')) $post_template = Request::post('templates'); else $post_template = 'index'; - if (Request::post('status')) $post_status = Request::post('status'); else $post_status = 'published'; - if (Request::post('access')) $post_access = Request::post('access'); else $post_access = 'public'; - if (Request::post('robots_index')) $post_robots_index = true; else $post_robots_index = false; - if (Request::post('robots_follow')) $post_robots_follow = true; else $post_robots_follow = false; - //-------------- - - // Prepare date - if (Valid::date(Request::post('page_date'))) { - $date = strtotime(Request::post('page_date')); - } else { - $date = time(); - } - - if (Request::post('robots_index')) $robots_index = 'noindex'; else $robots_index = 'index'; - if (Request::post('robots_follow')) $robots_follow = 'nofollow'; else $robots_follow = 'follow'; - - if (count($errors) == 0) { - - // Update parents in all childrens - if ((Security::safeName(Request::post('page_name'), '-', true)) !== (Security::safeName(Request::post('page_old_name'), '-', true)) and (Request::post('old_parent') == '')) { - - $pages->updateWhere('[parent="'.Request::get('name').'"]', array('parent' => Text::translitIt(trim(Request::post('page_name'))))); - - if ($pages->updateWhere('[slug="'.Request::get('name').'"]', - array('slug' => Security::safeName(Request::post('page_name'), '-', true), - 'template' => Request::post('templates'), - 'parent' => $parent_page, - 'title' => Request::post('page_title'), - 'description' => Request::post('page_description'), - 'keywords' => Request::post('page_keywords'), - 'robots_index' => $robots_index, - 'robots_follow'=> $robots_follow, - 'status' => Request::post('status'), - 'access' => Request::post('ascess'), - 'date' => $date, - 'author' => $author))) { - - File::setContent(STORAGE . DS . 'pages' . DS . Request::post('page_id') . '.page.txt', XML::safe(Request::post('editor'))); - Notification::set('success', __('Your changes to the page :page have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true)))); - } - - // Run edit extra actions - Action::run('admin_pages_action_edit'); - - } else { - - if ($pages->updateWhere('[slug="'.Request::get('name').'"]', - array('slug' => Security::safeName(Request::post('page_name'), '-', true), - 'template' => Request::post('templates'), - 'parent' => $parent_page, - 'title' => Request::post('page_title'), - 'description' => Request::post('page_description'), - 'keywords' => Request::post('page_keywords'), - 'robots_index' => $robots_index, - 'robots_follow'=> $robots_follow, - 'status' => Request::post('status'), - 'access' => Request::post('access'), - 'date' => $date, - 'author' => $author))) { - - File::setContent(STORAGE . DS . 'pages' . DS . Request::post('page_id') . '.page.txt', XML::safe(Request::post('editor'))); - Notification::set('success', __('Your changes to the page :page have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true)))); - } - - // Run edit extra actions - Action::run('admin_pages_action_edit'); - } - - // Redirect - if (Request::post('edit_page_and_exit')) { - Request::redirect('index.php?id=pages'); - } else { - Request::redirect('index.php?id=pages&action=edit_page&name='.Security::safeName(Request::post('page_name'), '-', true)); - } - } - - } else { die('csrf detected!'); } - } - - - // Get all pages - $pages_list = $pages->select(); - $pages_array[] = '-none-'; - // Foreach pages find page whithout parent - foreach ($pages_list as $page) { - if (isset($page['parent'])) { - $c_p = $page['parent']; - } else { - $c_p = ''; - } - if ($c_p == '') { - // error404 is system "constant" and no child for it - if ($page['slug'] !== 'error404' && $page['slug'] !== Request::get('name')) { - $pages_array[$page['slug']] = $page['title']; - } - } - } - - - // Get all templates - $templates_list = File::scan($templates_path,'.template.php'); - foreach ($templates_list as $file) { - $templates_array[basename($file,'.template.php')] = basename($file, '.template.php'); - } - - - $page = $pages->select('[slug="'.Request::get('name').'"]', null); - - if ($page) { - - $page_content = File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt'); - - // Safe fields or load fields - if (Request::post('page_name')) $slug_to_edit = Request::post('page_name'); else $slug_to_edit = $page['slug']; - if (Request::post('page_title')) $title_to_edit = Request::post('page_title'); else $title_to_edit = $page['title']; - if (Request::post('page_description')) $description_to_edit = Request::post('page_description'); else $description_to_edit = $page['description']; - if (Request::post('page_keywords')) $keywords_to_edit = Request::post('page_keywords'); else $keywords_to_edit = $page['keywords']; - if (Request::post('editor')) $to_edit = Request::post('editor'); else $to_edit = Text::toHtml($page_content); - - if (Request::post('robots_index')) $post_robots_index = true; else if ($page['robots_index'] == 'noindex') $post_robots_index = true; else $post_robots_index = false; - if (Request::post('robots_follow')) $post_robots_follow = true; else if ($page['robots_follow'] == 'nofollow') $post_robots_follow = true; else $post_robots_follow = false; - - if (Request::post('pages')) { - // Get pages parent - if (Request::post('pages') == '-none-') { - $parent_page = ''; - } else { - $parent_page = Request::post('pages'); - } - // Save field - $parent_page = Request::post('pages'); - } else { - $parent_page = $page['parent']; - } - if (Request::post('templates')) $template = Request::post('templates'); else $template = $page['template']; - if (Request::post('status')) $status = Request::post('status'); else $status = $page['status']; - if (Request::post('access')) $access = Request::post('access'); else $access = (isset($page['access'])) ? $page['access'] : 'public'; - - // Generate date - $date = Request::post('date') ? Request::post('date') : Date::format($page['date'], 'Y-m-d H:i:s'); - - Notification::setNow('page', 'page'); - - // Display view - View::factory('box/pages/views/backend/edit') - ->assign('slug_to_edit', $slug_to_edit) - ->assign('title_to_edit', $title_to_edit) - ->assign('description_to_edit', $description_to_edit) - ->assign('keywords_to_edit', $keywords_to_edit) - ->assign('page', $page) - ->assign('to_edit', $to_edit) - ->assign('pages_array', $pages_array) - ->assign('parent_page', $parent_page) - ->assign('templates_array', $templates_array) - ->assign('template', $template) - ->assign('status_array', $status_array) - ->assign('access_array', $access_array) - ->assign('status', $status) - ->assign('access', $access) - ->assign('date', $date) - ->assign('post_robots_index', $post_robots_index) - ->assign('post_robots_follow', $post_robots_follow) - ->assign('errors', $errors) - ->display(); - } - - break; - - // Delete page - // ------------------------------------- - case "delete_page": - - // Error 404 page can not be removed - if (Request::get('name') !== 'error404') { - - if (Security::check(Request::get('token'))) { - - // Get specific page - $page = $pages->select('[slug="'.Request::get('name').'"]', null); - - // Delete page and update fields - if ($pages->deleteWhere('[slug="'.$page['slug'].'" ]')) { - - $_pages = $pages->select('[parent="'.$page['slug'].'"]'); - - if ( ! empty($_pages)) { - foreach($_pages as $_page) { - $pages->updateWhere('[slug="'.$_page['slug'].'"]', array('parent' => '')); - } - } - - File::delete(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt'); - Notification::set('success', __('Page :page deleted', 'pages', array(':page' => Html::toText($page['title'])))); - } - - // Run delete extra actions - Action::run('admin_pages_action_delete'); - - // Redirect - Request::redirect('index.php?id=pages'); - - } else { die('csrf detected!'); } - } - - break; - } - - // Its mean that you can add your own actions for this plugin - Action::run('admin_pages_extra_actions'); - - } else { - - // Index action - // ------------------------------------- - - // Init vars - $pages_array = array(); - $count = 0; - - // Get pages - $pages_list = $pages->select(null, 'all', null, array('slug', 'title', 'status', 'date', 'author', 'expand', 'access', 'parent')); - - // Loop - foreach ($pages_list as $page) { - - $pages_array[$count]['title'] = $page['title']; - $pages_array[$count]['parent'] = $page['parent']; - $pages_array[$count]['status'] = $status_array[$page['status']]; - $pages_array[$count]['access'] = isset($access_array[$page['access']]) ? $access_array[$page['access']] : $access_array['public']; // hack for old Monstra Versions - $pages_array[$count]['date'] = $page['date']; - $pages_array[$count]['author'] = $page['author']; - $pages_array[$count]['expand'] = $page['expand']; - $pages_array[$count]['slug'] = $page['slug']; - - if (isset($page['parent'])) { - $c_p = $page['parent']; - } else { - $c_p = ''; } - if ($c_p != '') { - - $_page = $pages->select('[slug="'.$page['parent'].'"]', null); - - if (isset($_page['title'])) { - $_title = $_page['title']; - } else { - $_title = ''; - } - - $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; - - } else { - - $pages_array[$count]['sort'] = $page['title']; - - } - - $_title = ''; - $count++; - } - - // Sort pages - $pages = Arr::subvalSort($pages_array, 'sort'); - - // Display view - View::factory('box/pages/views/backend/index') - ->assign('pages', $pages) - ->assign('site_url', $site_url) - ->display(); + break; } - + + // Its mean that you can add your own actions for this plugin + Action::run('admin_pages_extra_actions'); + + } else { + + // Index action + // ------------------------------------- + + // Init vars + $pages_array = array(); + $count = 0; + + // Get pages + $pages_list = $pages->select(null, 'all', null, array('slug', 'title', 'status', 'date', 'author', 'expand', 'access', 'parent')); + + // Loop + foreach ($pages_list as $page) { + + $pages_array[$count]['title'] = $page['title']; + $pages_array[$count]['parent'] = $page['parent']; + $pages_array[$count]['status'] = $status_array[$page['status']]; + $pages_array[$count]['access'] = isset($access_array[$page['access']]) ? $access_array[$page['access']] : $access_array['public']; // hack for old Monstra Versions + $pages_array[$count]['date'] = $page['date']; + $pages_array[$count]['author'] = $page['author']; + $pages_array[$count]['expand'] = $page['expand']; + $pages_array[$count]['slug'] = $page['slug']; + + if (isset($page['parent'])) { + $c_p = $page['parent']; + } else { + $c_p = ''; + } + + if ($c_p != '') { + + $_page = $pages->select('[slug="'.$page['parent'].'"]', null); + + if (isset($_page['title'])) { + $_title = $_page['title']; + } else { + $_title = ''; + } + + $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; + + } else { + + $pages_array[$count]['sort'] = $page['title']; + + } + + $_title = ''; + $count++; + } + + // Sort pages + $pages = Arr::subvalSort($pages_array, 'sort'); + + // Display view + View::factory('box/pages/views/backend/index') + ->assign('pages', $pages) + ->assign('site_url', $site_url) + ->display(); } - } \ No newline at end of file + + } +} diff --git a/plugins/box/pages/pages.plugin.php b/plugins/box/pages/pages.plugin.php index 96261b0..c21f4b7 100644 --- a/plugins/box/pages/pages.plugin.php +++ b/plugins/box/pages/pages.plugin.php @@ -1,206 +1,195 @@ select('[slug="'.$requested_page.'"]', null); + } /** - * Pages Class + * Load current page + * + * @global string $defpage default page + * @param array $data uri + * @return string */ - class Pages extends Frontend { + public static function lowLoader($data) + { + $defpage = Option::get('defaultpage'); + // If data count 2 then it has Parent/Child + if (count($data) >= 2) { - /** - * Current page data - * - * @var object - */ - public static $page = null; + // If exists parent file + if (count(Pages::$pages->select('[slug="'.$data[0].'"]')) !== 0) { + // Get child file and get parent page name + $child_page = Pages::$pages->select('[slug="'.$data[1].'"]', null); - /** - * Pages tables - * - * @var object - */ - public static $pages = null; - - - /** - * Requested page - * - * @var string - */ - public static $requested_page = null; - - - /** - * Main function - */ - public static function main() { - Pages::$pages = new Table('pages'); - Pages::$page = Pages::pageLoader(); - } - - - /** - * Page loader - * - * @param boolean $return_data data - * @return array - */ - public static function pageLoader($return_data = true) { - $requested_page = Pages::lowLoader(Uri::segments()); - Pages::$requested_page = $requested_page; - return Pages::$pages->select('[slug="'.$requested_page.'"]', null); - } - - - /** - * Load current page - * - * @global string $defpage default page - * @param array $data uri - * @return string - */ - public static function lowLoader($data) { - - $defpage = Option::get('defaultpage'); - - // If data count 2 then it has Parent/Child - if (count($data) >= 2) { - - // If exists parent file - if (count(Pages::$pages->select('[slug="'.$data[0].'"]')) !== 0) { - - // Get child file and get parent page name - $child_page = Pages::$pages->select('[slug="'.$data[1].'"]', null); - - // If child page parent is not empty then get his parent - if (count($child_page) == 0) { - $c_p = ''; + // If child page parent is not empty then get his parent + if (count($child_page) == 0) { + $c_p = ''; + } else { + if ($child_page['parent'] != '') { + $c_p = $child_page['parent']; } else { - if ($child_page['parent'] != '') { - $c_p = $child_page['parent']; - } else { - $c_p = ''; - } + $c_p = ''; } + } - // Hack For old Monstra - $child_page['access'] = (isset($child_page['access'])) ? $child_page['access'] : 'public' ; - - // Check is child_parent -> request parent - if ($c_p == $data[0]) { - - if (count($data) < 3) { // Checking only for the parent and one child, the remaining issue 404 - - if ((($child_page['status'] == 'published') or - (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) and - ($child_page['access'] == 'public')) { + // Hack For old Monstra + $child_page['access'] = (isset($child_page['access'])) ? $child_page['access'] : 'public' ; - $id = $data[1]; + // Check is child_parent -> request parent + if ($c_p == $data[0]) { - } elseif (($child_page['access'] == 'registered') and - (Session::exists('user_id')) and - ($child_page['status'] == 'published')) { - - $id = $data[1]; + if (count($data) < 3) { // Checking only for the parent and one child, the remaining issue 404 + + if ((($child_page['status'] == 'published') or + (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) and + ($child_page['access'] == 'public')) { + + $id = $data[1]; + + } elseif (($child_page['access'] == 'registered') and + (Session::exists('user_id')) and + ($child_page['status'] == 'published')) { + + $id = $data[1]; - } else { - $id = 'error404'; - Response::status(404); - } } else { - $id = 'error404'; + $id = 'error404'; Response::status(404); } - } else { $id = 'error404'; Response::status(404); } + } else { $id = 'error404'; Response::status(404); } + } else { + $id = 'error404'; + Response::status(404); + } - } else { // Only parent page come - if(empty($data[0])) { - - $id = $defpage; + } else { // Only parent page come + if (empty($data[0])) { - } else { + $id = $defpage; - // Get current page - $current_page = Pages::$pages->select('[slug="'.$data[0].'"]', null); - - // Hack For old Monstra - $current_page['access'] = (isset($current_page['access'])) ? $current_page['access'] : 'public' ; + } else { - if (count($current_page) != 0) { - if ( ! empty($current_page['parent'])) { - $c_p = $current_page['parent']; - } else { - $c_p = ''; - } + // Get current page + $current_page = Pages::$pages->select('[slug="'.$data[0].'"]', null); + + // Hack For old Monstra + $current_page['access'] = (isset($current_page['access'])) ? $current_page['access'] : 'public' ; + + if (count($current_page) != 0) { + if ( ! empty($current_page['parent'])) { + $c_p = $current_page['parent']; } else { $c_p = ''; } + } else { + $c_p = ''; + } - // Check if this page has parent - if ($c_p !== '') { + // Check if this page has parent + if ($c_p !== '') { - if ($c_p == $data[0]) { - if (count(Pages::$pages->select('[slug="'.$data[0].'"]', null)) != 0) { + if ($c_p == $data[0]) { + if (count(Pages::$pages->select('[slug="'.$data[0].'"]', null)) != 0) { - if ((($current_page['status'] == 'published') or - (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) and - ($current_page['access'] == 'public')) { + if ((($current_page['status'] == 'published') or + (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) and + ($current_page['access'] == 'public')) { - $id = $data[0]; + $id = $data[0]; - } elseif (($current_page['access'] == 'registered') and - (Session::exists('user_id')) and - ($current_page['status'] == 'published')) { - - $id = $data[0]; + } elseif (($current_page['access'] == 'registered') and + (Session::exists('user_id')) and + ($current_page['status'] == 'published')) { + + $id = $data[0]; - } else { - $id = 'error404'; - Response::status(404); - } } else { $id = 'error404'; Response::status(404); @@ -210,284 +199,285 @@ Response::status(404); } } else { + $id = 'error404'; + Response::status(404); + } + } else { - if (count(Pages::$pages->select('[slug="'.$data[0].'"]', null)) != 0) { - if ((($current_page['status'] == 'published') or - (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) and - ($current_page['access'] == 'public')) { + if (count(Pages::$pages->select('[slug="'.$data[0].'"]', null)) != 0) { + if ((($current_page['status'] == 'published') or + (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) and + ($current_page['access'] == 'public')) { - $id = $data[0]; + $id = $data[0]; - } elseif (($current_page['access'] == 'registered') and - (Session::exists('user_id')) and - ($current_page['status'] == 'published')) { + } elseif (($current_page['access'] == 'registered') and + (Session::exists('user_id')) and + ($current_page['status'] == 'published')) { - $id = $data[0]; + $id = $data[0]; - } else { - $id = 'error404'; - Response::status(404); - } } else { $id = 'error404'; Response::status(404); } + } else { + $id = 'error404'; + Response::status(404); } } } - - // Return page name/id to load - return $id; } + // Return page name/id to load + return $id; + } - /** - * Get pages template - * - * @return string - */ - public static function template() { - if (Pages::$page['template'] == '') return 'index'; else return Pages::$page['template']; - } + /** + * Get pages template + * + * @return string + */ + public static function template() + { + if (Pages::$page['template'] == '') return 'index'; else return Pages::$page['template']; + } + /** + * Get pages contents + * + * @return string + */ + public static function content($slug = '') + { + if ( ! empty($slug)) { - /** - * Get pages contents - * - * @return string - */ - public static function content($slug = '') { + $page = Table::factory('pages')->select('[slug="'.$slug.'"]', null); - if ( ! empty($slug)) { + if ( ! empty($page)) { - $page = Table::factory('pages')->select('[slug="'.$slug.'"]', null); + $content = Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt')); - if ( ! empty($page)) { + $content = Filter::apply('content', $content); - $content = Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt')); - - $content = Filter::apply('content', $content); - - return $content; - - } else { - return ''; - } + return $content; } else { - return Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . Pages::$page['id'] . '.page.txt')); + return ''; } - } - - - /** - * Get pages title - * - * - * echo Page::title(); - * - * - * @return string - */ - public static function title() { - return Pages::$page['title']; - } - - - /** - * Get pages Description - * - * - * echo Page::description(); - * - * - * @return string - */ - public static function description() { - return Pages::$page['description']; - } - - - /** - * Get pages Keywords - * - * - * echo Page::keywords(); - * - * - * @return string - */ - public static function keywords() { - return Pages::$page['keywords']; + } else { + return Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . Pages::$page['id'] . '.page.txt')); } } + /** + * Get pages title + * + * + * echo Page::title(); + * + * + * @return string + */ + public static function title() + { + return Pages::$page['title']; + } /** - * Add new shortcodes {page_author} {page_slug} {page_url} {page_date} {page_content} + * Get pages Description + * + * + * echo Page::description(); + * + * + * @return string */ - Shortcode::add('page_author', 'Page::author'); - Shortcode::add('page_slug', 'Page::slug'); - Shortcode::add('page_url', 'Page::url'); - Shortcode::add('page_content', 'Page::_content'); - Shortcode::add('page_date', 'Page::_date'); - + public static function description() + { + return Pages::$page['description']; + } /** - * Page class + * Get pages Keywords + * + * + * echo Page::keywords(); + * + * + * @return string */ - class Page extends Pages { + public static function keywords() + { + return Pages::$page['keywords']; + } +} - /** - * Get date of current page - * - * - * echo Page::date(); - * - * - * @param string $format Date format - * @return string - */ - public static function date($format = 'Y-m-d') { - return Date::format(Pages::$page['date'], $format); - } +/** + * Add new shortcodes {page_author} {page_slug} {page_url} {page_date} {page_content} + */ +Shortcode::add('page_author', 'Page::author'); +Shortcode::add('page_slug', 'Page::slug'); +Shortcode::add('page_url', 'Page::url'); +Shortcode::add('page_content', 'Page::_content'); +Shortcode::add('page_date', 'Page::_date'); +/** + * Page class + */ +class Page extends Pages +{ + /** + * Get date of current page + * + * + * echo Page::date(); + * + * + * @param string $format Date format + * @return string + */ + public static function date($format = 'Y-m-d') + { + return Date::format(Pages::$page['date'], $format); + } - /** - * Get author of current page - * - * - * echo Page::author(); - * - * - * @return string - */ - public static function author() { - return Pages::$page['author']; - } + /** + * Get author of current page + * + * + * echo Page::author(); + * + * + * @return string + */ + public static function author() + { + return Pages::$page['author']; + } + /** + * Get children pages for a specific parent page + * + * + * $pages = Page::children('page'); + * + * + * @param string $parent Parent page + * @return array + */ + public static function children($parent) + { + return Pages::$pages->select('[parent="'.(string) $parent.'"]', 'all'); + } - /** - * Get children pages for a specific parent page - * - * - * $pages = Page::children('page'); - * - * - * @param string $parent Parent page - * @return array - */ - public static function children($parent) { - return Pages::$pages->select('[parent="'.(string)$parent.'"]', 'all'); - } + /** + * Get the available children pages for requested page. + * + * + * echo Page::available(); + * + * + */ + public static function available() + { + $pages = Pages::$pages->select('[parent="'.Pages::$requested_page.'"]', 'all'); + // Display view + View::factory('box/pages/views/frontend/available_pages') + ->assign('pages', $pages) + ->display(); + } + + /** + * Get page breadcrumbs + * + * + * echo Page::breadcrumbs(); + * + * + */ + public static function breadcrumbs() + { + $current_page = Pages::$requested_page; + $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; + } - /** - * Get the available children pages for requested page. - * - * - * echo Page::available(); - * - * - */ - public static function available() { - $pages = Pages::$pages->select('[parent="'.Pages::$requested_page.'"]', 'all'); - // Display view - View::factory('box/pages/views/frontend/available_pages') - ->assign('pages', $pages) + View::factory('box/pages/views/frontend/breadcrumbs') + ->assign('current_page', $current_page) + ->assign('page', $page) + ->assign('parent', $parent) + ->assign('parent_page', $parent_page) ->display(); } - + } - /** - * Get page breadcrumbs - * - * - * echo Page::breadcrumbs(); - * - * - */ - 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('box/pages/views/frontend/breadcrumbs') - ->assign('current_page', $current_page) - ->assign('page', $page) - ->assign('parent', $parent) - ->assign('parent_page', $parent_page) - ->display(); - } - } + /** + * Get page url + * + * + * echo Page::url(); + * + * + */ + public static function url() + { + return Option::get('siteurl').Pages::$page['slug']; + } + /** + * Get page slug + * + * + * echo Page::slug(); + * + * + */ + public static function slug() + { + return Pages::$page['slug']; + } - /** - * Get page url - * - * - * echo Page::url(); - * - * - */ - public static function url() { - return Option::get('siteurl').Pages::$page['slug']; + /** + * Get page meta robots + * + * + * echo Page::robots(); + * + * + */ + public static function robots() + { + if (Pages::$page !== null) { + $_index = (isset(Pages::$page['robots_index'])) ? Pages::$page['robots_index'] : ''; + $_follow = (isset(Pages::$page['robots_follow'])) ? Pages::$page['robots_follow'] : ''; + $robots = ( ! empty($_index) && ! empty($_follow)) ? $_index.', '.$_follow : ''; + } else { + $robots = ''; } + return $robots; + } - /** - * Get page slug - * - * - * echo Page::slug(); - * - * - */ - public static function slug() { - return Pages::$page['slug']; - } + public static function _date($attributes) + { + return Page::date((isset($attributes['format'])) ? $attributes['format'] : 'Y-m-d'); + } + public static function _content($attributes) + { + return Page::content((isset($attributes['name']) ? $attributes['name'] : '')); + } - /** - * Get page meta robots - * - * - * echo Page::robots(); - * - * - */ - public static function robots() { - - if (Pages::$page !== null) { - $_index = (isset(Pages::$page['robots_index'])) ? Pages::$page['robots_index'] : ''; - $_follow = (isset(Pages::$page['robots_follow'])) ? Pages::$page['robots_follow'] : ''; - $robots = ( ! empty($_index) && ! empty($_follow)) ? $_index.', '.$_follow : ''; - } else { - $robots = ''; - } - - return $robots; - } - - - public static function _date($attributes) { - return Page::date((isset($attributes['format'])) ? $attributes['format'] : 'Y-m-d'); - } - - public static function _content($attributes) { - return Page::content((isset($attributes['name']) ? $attributes['name'] : '')); - } - - } \ No newline at end of file +} diff --git a/plugins/box/pages/views/backend/add.view.php b/plugins/box/pages/views/backend/add.view.php index 1c5ad84..eb12848 100644 --- a/plugins/box/pages/views/backend/add.view.php +++ b/plugins/box/pages/views/backend/add.view.php @@ -3,7 +3,7 @@ -class="active">
  • class="active">
  • - +
    '.$errors['pages_empty_title'].''; - echo ( + echo ( Html::br(2). - Form::label('page_name', __('Name (slug)', 'pages')). + Form::label('page_name', __('Name (slug)', 'pages')). Form::input('page_name', $post_name, array('class' => (isset($errors['pages_empty_name'])) ? 'input-xxlarge error-field' : 'input-xxlarge')) ); if (isset($errors['pages_exists'])) echo Html::nbsp(3).''.$errors['pages_exists'].''; if (isset($errors['pages_empty_name'])) echo Html::nbsp(3).''.$errors['pages_empty_name'].''; ?> - +
    'input-xxlarge')). Html::br(2). Form::label('page_description', __('Description', 'pages')). - Form::textarea('page_description', $post_description, array('class' => 'input-xxlarge')) + Form::textarea('page_description', $post_description, array('class' => 'input-xxlarge')) ); ?> - active" id="settings">
    - -
    +
    -
    -
    -
    - +
    +
    +
    diff --git a/plugins/box/pages/views/backend/edit.view.php b/plugins/box/pages/views/backend/edit.view.php index 83ae4f1..3d9bd54 100644 --- a/plugins/box/pages/views/backend/edit.view.php +++ b/plugins/box/pages/views/backend/edit.view.php @@ -3,7 +3,7 @@ -class="active">
  • class="active">
  • - +
    - 'input-xxlarge')). Html::br(2). Form::label('page_description', __('Description', 'pages')). - Form::textarea('page_description', $description_to_edit, array('class' => 'input-xxlarge')) + Form::textarea('page_description', $description_to_edit, array('class' => 'input-xxlarge')) ); - echo ( - Html::br(2). - Form::label('robots', __('Search Engines Robots', 'pages')). + echo ( + Html::br(2). + Form::label('robots', __('Search Engines Robots', 'pages')). 'no Index'.Html::nbsp().Form::checkbox('robots_index', 'index', $post_robots_index).Html::nbsp(2). 'no Follow'.Html::nbsp().Form::checkbox('robots_follow', 'follow', $post_robots_follow) ); @@ -75,7 +74,7 @@ } else { ?>
    -
    -
    -
    -
    -
    -

    diff --git a/plugins/box/pages/views/backend/index.view.php b/plugins/box/pages/views/backend/index.view.php index 3a2c608..88d2ae7 100755 --- a/plugins/box/pages/views/backend/index.view.php +++ b/plugins/box/pages/views/backend/index.view.php @@ -4,10 +4,10 @@ __('Create New Page', 'pages'), 'class' => 'btn btn-small')). Html::nbsp(3). - Html::anchor(__('Edit 404 Page', 'pages'), 'index.php?id=pages&action=edit_page&name=error404', array('title' => __('Create New Page', 'pages'), 'class' => 'btn btn-small')) - ); + Html::anchor(__('Edit 404 Page', 'pages'), 'index.php?id=pages&action=edit_page&name=error404', array('title' => __('Create New Page', 'pages'), 'class' => 'btn btn-small')) + ); ?>

    @@ -26,33 +26,33 @@ select('[slug="'.(string)$page['parent'].'"]', null); + $expand = PagesAdmin::$pages->select('[slug="'.(string) $page['parent'].'"]', null); if ($page['parent'] !== '' && isset($expand['expand']) && $expand['expand'] == '1') { $visibility = 'style="display:none;"'; } else { $visibility = ''; } ?> - rel="children_" > - - select('[parent="'.(string)$page['slug'].'"]', 'all')) > 0) { + rel="children_" > + + select('[parent="'.(string) $page['slug'].'"]', 'all')) > 0) { if (isset($page['expand']) && $page['expand'] == '1') { echo '+'; } else { echo '-'; } } - ?> - + ?> + '_blank', 'rel' => 'children_'.$_parent)); + echo $dash.Html::anchor(Html::toText($page['title']), $site_url.$parent.$page['slug'], array('target' => '_blank', 'rel' => 'children_'.$_parent)); ?> @@ -67,7 +67,7 @@ - +
    'btn btn-small')); ?> @@ -77,19 +77,19 @@
  • __('Clone', 'pages'))); ?>
  • - + 'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__("Delete page: :page", 'pages', array(':page' => Html::toText($page['title'])))."')")); ?> -
    -
    +
    +
    - + diff --git a/plugins/box/pages/views/frontend/available_pages.view.php b/plugins/box/pages/views/frontend/available_pages.view.php index b904a0b..9e4aa86 100644 --- a/plugins/box/pages/views/frontend/available_pages.view.php +++ b/plugins/box/pages/views/frontend/available_pages.view.php @@ -1,5 +1,5 @@
      -
    • +
    • -
    \ No newline at end of file + diff --git a/plugins/box/pages/views/frontend/breadcrumbs.view.php b/plugins/box/pages/views/frontend/breadcrumbs.view.php index 998d2ae..4889b76 100644 --- a/plugins/box/pages/views/frontend/breadcrumbs.view.php +++ b/plugins/box/pages/views/frontend/breadcrumbs.view.php @@ -2,4 +2,4 @@    - \ No newline at end of file +1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/plugins/languages/de.lang.php b/plugins/box/plugins/languages/de.lang.php index dd8e830..dd6bbc0 100644 --- a/plugins/box/plugins/languages/de.lang.php +++ b/plugins/box/plugins/languages/de.lang.php @@ -1,20 +1,20 @@ - array( - 'Plugins' => 'Plugins', - 'Name' => 'Name', - 'Actions' => 'Aktionen', - 'Description' => 'Beschreibung', - 'Installed' => 'Installiert', - 'Install New' => 'Installiere Neue', - 'Delete' => 'Löschen', - 'Delete plugin :plugin' => 'Lösche Plugin :plugin', - 'This plugins does not exist' => 'Diese Plugins existiert nicht', - 'Version' => 'Version', - 'Author' => 'Author', - 'Get More Plugins' => 'Hole Weitere Plugins', - 'Install' => 'Installieren', - 'Uninstall' => 'Deinstallieren', - ) - ); \ No newline at end of file + array( + 'Plugins' => 'Plugins', + 'Name' => 'Name', + 'Actions' => 'Aktionen', + 'Description' => 'Beschreibung', + 'Installed' => 'Installiert', + 'Install New' => 'Installiere Neue', + 'Delete' => 'Löschen', + 'Delete plugin :plugin' => 'Lösche Plugin :plugin', + 'This plugins does not exist' => 'Diese Plugins existiert nicht', + 'Version' => 'Version', + 'Author' => 'Author', + 'Get More Plugins' => 'Hole Weitere Plugins', + 'Install' => 'Installieren', + 'Uninstall' => 'Deinstallieren', + ) + ); diff --git a/plugins/box/plugins/languages/en.lang.php b/plugins/box/plugins/languages/en.lang.php index f4d8585..7c5adf6 100644 --- a/plugins/box/plugins/languages/en.lang.php +++ b/plugins/box/plugins/languages/en.lang.php @@ -1,5 +1,5 @@ array( 'Plugins' => 'Plugins', @@ -17,4 +17,4 @@ 'Install' => 'Install', 'Uninstall' => 'Uninstall', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/plugins/languages/it.lang.php b/plugins/box/plugins/languages/it.lang.php index 6298628..4d0f0a6 100644 --- a/plugins/box/plugins/languages/it.lang.php +++ b/plugins/box/plugins/languages/it.lang.php @@ -1,5 +1,5 @@ array( 'Plugins' => 'Plugin', @@ -17,4 +17,4 @@ 'Install' => 'Installa', 'Uninstall' => 'Disinstalla', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/plugins/languages/lt.lang.php b/plugins/box/plugins/languages/lt.lang.php index d6256d2..ecfb8a4 100644 --- a/plugins/box/plugins/languages/lt.lang.php +++ b/plugins/box/plugins/languages/lt.lang.php @@ -1,5 +1,5 @@ array( 'Plugins' => 'Papildiniai', @@ -17,4 +17,4 @@ 'Install' => 'Įdiegti', 'Uninstall' => 'Išdiegti', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/plugins/languages/pt-br.lang.php b/plugins/box/plugins/languages/pt-br.lang.php index a772af8..91e5600 100644 --- a/plugins/box/plugins/languages/pt-br.lang.php +++ b/plugins/box/plugins/languages/pt-br.lang.php @@ -1,5 +1,5 @@ array( 'Plugins' => 'Plugins', @@ -17,4 +17,4 @@ 'Install' => 'Instalar', 'Uninstall' => 'Desinstalar', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/plugins/languages/ru.lang.php b/plugins/box/plugins/languages/ru.lang.php index 2f2d0b8..e0253d3 100644 --- a/plugins/box/plugins/languages/ru.lang.php +++ b/plugins/box/plugins/languages/ru.lang.php @@ -1,5 +1,5 @@ array( 'Plugins' => 'Плагины', @@ -17,4 +17,4 @@ 'Install' => 'Установить', 'Uninstall' => 'Удалить', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/plugins/languages/uk.lang.php b/plugins/box/plugins/languages/uk.lang.php index 9cc404e..464bee4 100644 --- a/plugins/box/plugins/languages/uk.lang.php +++ b/plugins/box/plugins/languages/uk.lang.php @@ -1,5 +1,5 @@ array( 'Plugins' => 'Плагіни', @@ -17,4 +17,4 @@ 'Install' => 'Установити', 'Uninstall' => 'Видалити', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/plugins/plugins.admin.php b/plugins/box/plugins/plugins.admin.php index a68c518..c624c0d 100755 --- a/plugins/box/plugins/plugins.admin.php +++ b/plugins/box/plugins/plugins.admin.php @@ -1,151 +1,148 @@ 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + // Nobody cant remove box plugins + if ($installed_plugins[Text::lowercase(str_replace("Plugin", "", Request::get('delete_plugin')))]['privilege'] !== 'box') { - // Clean i18n cache - Cache::clean('i18n'); - - // Delete plugin form plugins table - $plugins->deleteWhere('[name="'.Request::get('delete_plugin').'"]'); - - // Redirect - Request::redirect('index.php?id=plugins'); - } + // Run plugin uninstaller file + $plugin_name = Request::get('delete_plugin'); + if (File::exists(PLUGINS . DS . $plugin_name . DS .'install' . DS . $plugin_name . '.uninstall.php')) { + include PLUGINS . DS . $plugin_name . DS . 'install' . DS . $plugin_name . '.uninstall.php'; + } - } else { die('csrf detected!'); } - } - - - // Install new plugin - // ------------------------------------- - if (Request::get('install')) { - - if (Security::check(Request::get('token'))) { - - // Load plugin install xml file - $plugin_xml = XML::loadFile(PLUGINS . DS . basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . Request::get('install')); - - // Add plugin to plugins table - $plugins->insert(array('name' => basename(Request::get('install'), '.manifest.xml'), - 'location' => (string)$plugin_xml->plugin_location, - 'status' => (string)$plugin_xml->plugin_status, - 'priority' => (int)$plugin_xml->plugin_priority)); - - // Cleanup minify + // Cleanup minify if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); // Clean i18n cache - Cache::clean('i18n'); - - // Run plugin installer file - $plugin_name = str_replace(array("Plugin", ".manifest.xml"), "", Request::get('install')); - if (File::exists(PLUGINS . DS .basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . $plugin_name . '.install.php')) { - include PLUGINS . DS . basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . $plugin_name . '.install.php'; - } - - Request::redirect('index.php?id=plugins'); + Cache::clean('i18n'); - } else { die('csrf detected!'); } - } + // Delete plugin form plugins table + $plugins->deleteWhere('[name="'.Request::get('delete_plugin').'"]'); - - // Delete plugin from server - // ------------------------------------- - if (Request::get('delete_plugin_from_server')) { - - if (Security::check(Request::get('token'))) { - - Dir::delete(PLUGINS . DS . basename(Request::get('delete_plugin_from_server'), '.manifest.xml')); + // Redirect Request::redirect('index.php?id=plugins'); + } - } else { die('csrf detected!'); } - - } - - - // Installed plugins - $plugins_installed = array(); - - // New plugins - $plugins_new = array(); - - // Plugins to install - $plugins_to_intall = array(); - - // Scan plugins directory for .manifest.xml - $plugins_new = File::scan(PLUGINS, '.manifest.xml'); - - // Get installed plugins from plugins table - $plugins_installed = $plugins->select(null, 'all', null, array('location', 'priority'), 'priority', 'ASC'); - - // Update $plugins_installed array. extract plugins names - foreach ($plugins_installed as $plg) { - $_plg[] = basename($plg['location'], 'plugin.php').'manifest.xml'; - } - - // Diff - $plugins_to_install = array_diff($plugins_new, $_plg); - - // Create array of plugins to install - $count = 0; - foreach ($plugins_to_install as $plugin) { - $plg_path = PLUGINS . DS . Text::lowercase(basename($plugin, '.manifest.xml')) . DS . 'install' . DS . $plugin; - if (file_exists($plg_path)) { - $plugins_to_intall[$count]['path'] = $plg_path; - $plugins_to_intall[$count]['plugin'] = $plugin; - $count++; - } - } - - // Draw template - View::factory('box/plugins/views/backend/index') - ->assign('installed_plugins', $installed_plugins) - ->assign('plugins_to_intall', $plugins_to_intall) - ->assign('_users_plugins', $_users_plugins) - ->display(); + } else { die('csrf detected!'); } } - } \ No newline at end of file + + // Install new plugin + // ------------------------------------- + if (Request::get('install')) { + + if (Security::check(Request::get('token'))) { + + // Load plugin install xml file + $plugin_xml = XML::loadFile(PLUGINS . DS . basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . Request::get('install')); + + // Add plugin to plugins table + $plugins->insert(array('name' => basename(Request::get('install'), '.manifest.xml'), + 'location' => (string) $plugin_xml->plugin_location, + 'status' => (string) $plugin_xml->plugin_status, + 'priority' => (int) $plugin_xml->plugin_priority)); + + // Cleanup minify + if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + + // Clean i18n cache + Cache::clean('i18n'); + + // Run plugin installer file + $plugin_name = str_replace(array("Plugin", ".manifest.xml"), "", Request::get('install')); + if (File::exists(PLUGINS . DS .basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . $plugin_name . '.install.php')) { + include PLUGINS . DS . basename(Text::lowercase(Request::get('install')), '.manifest.xml') . DS . 'install' . DS . $plugin_name . '.install.php'; + } + + Request::redirect('index.php?id=plugins'); + + } else { die('csrf detected!'); } + } + + // Delete plugin from server + // ------------------------------------- + if (Request::get('delete_plugin_from_server')) { + + if (Security::check(Request::get('token'))) { + + Dir::delete(PLUGINS . DS . basename(Request::get('delete_plugin_from_server'), '.manifest.xml')); + Request::redirect('index.php?id=plugins'); + + } else { die('csrf detected!'); } + + } + + // Installed plugins + $plugins_installed = array(); + + // New plugins + $plugins_new = array(); + + // Plugins to install + $plugins_to_intall = array(); + + // Scan plugins directory for .manifest.xml + $plugins_new = File::scan(PLUGINS, '.manifest.xml'); + + // Get installed plugins from plugins table + $plugins_installed = $plugins->select(null, 'all', null, array('location', 'priority'), 'priority', 'ASC'); + + // Update $plugins_installed array. extract plugins names + foreach ($plugins_installed as $plg) { + $_plg[] = basename($plg['location'], 'plugin.php').'manifest.xml'; + } + + // Diff + $plugins_to_install = array_diff($plugins_new, $_plg); + + // Create array of plugins to install + $count = 0; + foreach ($plugins_to_install as $plugin) { + $plg_path = PLUGINS . DS . Text::lowercase(basename($plugin, '.manifest.xml')) . DS . 'install' . DS . $plugin; + if (file_exists($plg_path)) { + $plugins_to_intall[$count]['path'] = $plg_path; + $plugins_to_intall[$count]['plugin'] = $plugin; + $count++; + } + } + + // Draw template + View::factory('box/plugins/views/backend/index') + ->assign('installed_plugins', $installed_plugins) + ->assign('plugins_to_intall', $plugins_to_intall) + ->assign('_users_plugins', $_users_plugins) + ->display(); + } +} diff --git a/plugins/box/plugins/plugins.plugin.php b/plugins/box/plugins/plugins.plugin.php index 6a7d03f..ef9c649 100644 --- a/plugins/box/plugins/plugins.plugin.php +++ b/plugins/box/plugins/plugins.plugin.php @@ -1,31 +1,29 @@
    -
    +
    @@ -26,7 +26,7 @@ - + @@ -35,7 +35,7 @@ + @@ -50,11 +50,10 @@ -
    -
    +
    - -
    +
    @@ -66,9 +65,9 @@ - + - + @@ -93,10 +92,10 @@ -
    plugin_name; ?>
    +
    -
    \ No newline at end of file +
    diff --git a/plugins/box/sitemap/install/sitemap.manifest.xml b/plugins/box/sitemap/install/sitemap.manifest.xml index 9bc3d3a..126231c 100644 --- a/plugins/box/sitemap/install/sitemap.manifest.xml +++ b/plugins/box/sitemap/install/sitemap.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/sitemap/languages/de.lang.php b/plugins/box/sitemap/languages/de.lang.php index 3d77c8d..6c6d8aa 100644 --- a/plugins/box/sitemap/languages/de.lang.php +++ b/plugins/box/sitemap/languages/de.lang.php @@ -1,7 +1,7 @@ - array( - 'Sitemap' => 'Sitemap', - ) - ); \ No newline at end of file + array( + 'Sitemap' => 'Sitemap', + ) + ); diff --git a/plugins/box/sitemap/languages/en.lang.php b/plugins/box/sitemap/languages/en.lang.php index 75e369d..6c6d8aa 100644 --- a/plugins/box/sitemap/languages/en.lang.php +++ b/plugins/box/sitemap/languages/en.lang.php @@ -1,7 +1,7 @@ array( 'Sitemap' => 'Sitemap', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/sitemap/languages/it.lang.php b/plugins/box/sitemap/languages/it.lang.php index 75e369d..6c6d8aa 100644 --- a/plugins/box/sitemap/languages/it.lang.php +++ b/plugins/box/sitemap/languages/it.lang.php @@ -1,7 +1,7 @@ array( 'Sitemap' => 'Sitemap', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/sitemap/languages/lt.lang.php b/plugins/box/sitemap/languages/lt.lang.php index 75e369d..6c6d8aa 100644 --- a/plugins/box/sitemap/languages/lt.lang.php +++ b/plugins/box/sitemap/languages/lt.lang.php @@ -1,7 +1,7 @@ array( 'Sitemap' => 'Sitemap', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/sitemap/languages/pt-br.lang.php b/plugins/box/sitemap/languages/pt-br.lang.php index 917ffc2..549f360 100644 --- a/plugins/box/sitemap/languages/pt-br.lang.php +++ b/plugins/box/sitemap/languages/pt-br.lang.php @@ -1,7 +1,7 @@ array( 'Sitemap' => 'Mapa do site', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/sitemap/languages/ru.lang.php b/plugins/box/sitemap/languages/ru.lang.php index eda9c64..9f30327 100644 --- a/plugins/box/sitemap/languages/ru.lang.php +++ b/plugins/box/sitemap/languages/ru.lang.php @@ -1,7 +1,7 @@ array( 'Sitemap' => 'Карта сайта', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/sitemap/languages/uk.lang.php b/plugins/box/sitemap/languages/uk.lang.php index f543d01..cc081a4 100644 --- a/plugins/box/sitemap/languages/uk.lang.php +++ b/plugins/box/sitemap/languages/uk.lang.php @@ -1,7 +1,7 @@ array( 'Sitemap' => 'Карта сайту', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/sitemap/sitemap.plugin.php b/plugins/box/sitemap/sitemap.plugin.php index faaa0ae..1572305 100644 --- a/plugins/box/sitemap/sitemap.plugin.php +++ b/plugins/box/sitemap/sitemap.plugin.php @@ -1,180 +1,173 @@ assign('pages_list', Sitemap::getPages()) + ->assign('components', Sitemap::getComponents()) + ->render(); + } + /** + * Create sitemap + */ + public static function create() + { + // Get pages list + $pages_list = Sitemap::getPages(); - /** - * Sitemap Title - * - * @return string - */ - public static function title() { - return __('Sitemap', 'sitemap'); + // Create sitemap content + $map = ''."\n"; + $map .= ''."\n"; + foreach ($pages_list as $page) { + if ($page['parent'] != '') { $parent = $page['parent'].'/'; $priority = '0.5'; } else { $parent = ''; $priority = '1.0'; } + $map .= "\t".''."\n\t\t".''.Option::get('siteurl').$parent.$page['slug'].''."\n\t\t".''.date("Y-m-d", (int) $page['date']).''."\n\t\t".'weekly'."\n\t\t".''.$priority.''."\n\t".''."\n"; } + // Get list of components + $components = Sitemap::getComponents(); - /** - * Sitemap template - */ - public static function template() { - return 'index'; + // Add components to sitemap + if (count($components) > 0) { + foreach ($components as $component) { + $map .= "\t".''."\n\t\t".''.Option::get('siteurl').Text::lowercase($component).''."\n\t\t".''.date("Y-m-d", time()).''."\n\t\t".'weekly'."\n\t\t".'1.0'."\n\t".''."\n"; + } } + // Close sitemap + $map .= ''; - /** - * Get sitemap content - */ - public static function content() { + // Save sitemap + return File::setContent(ROOT . DS . 'sitemap.xml', $map); + } - // Display view - return View::factory('box/sitemap/views/frontend/index') - ->assign('pages_list', Sitemap::getPages()) - ->assign('components', Sitemap::getComponents()) - ->render(); - } - + /** + * Get pages + */ + protected static function getPages() + { + // Init vars + $pages_array = array(); + $count = 0; - /** - * Create sitemap - */ - public static function create() { + // Get pages table + $pages = new Table('pages'); - // Get pages list - $pages_list = Sitemap::getPages(); - - // Create sitemap content - $map = ''."\n"; - $map .= ''."\n"; - foreach ($pages_list as $page) { - if ($page['parent'] != '') { $parent = $page['parent'].'/'; $priority = '0.5'; } else { $parent = ''; $priority = '1.0'; } - $map .= "\t".''."\n\t\t".''.Option::get('siteurl').$parent.$page['slug'].''."\n\t\t".''.date("Y-m-d", (int)$page['date']).''."\n\t\t".'weekly'."\n\t\t".''.$priority.''."\n\t".''."\n"; + // Get Pages List + $pages_list = $pages->select('[slug!="error404" and status="published"]'); + + foreach ($pages_list as $page) { + + $pages_array[$count]['title'] = Html::toText($page['title']); + $pages_array[$count]['parent'] = $page['parent']; + $pages_array[$count]['date'] = $page['date']; + $pages_array[$count]['author'] = $page['author']; + $pages_array[$count]['slug'] = ($page['slug'] == Option::get('defaultpage')) ? '' : $page['slug'] ; + + if (isset($page['parent'])) { + $c_p = $page['parent']; + } else { + $c_p = ''; } - // Get list of components - $components = Sitemap::getComponents(); + if ($c_p != '') { + $_page = $pages->select('[slug="'.$page['parent'].'"]', null); - // Add components to sitemap - if (count($components) > 0) { - foreach ($components as $component) { - $map .= "\t".''."\n\t\t".''.Option::get('siteurl').Text::lowercase($component).''."\n\t\t".''.date("Y-m-d", time()).''."\n\t\t".'weekly'."\n\t\t".'1.0'."\n\t".''."\n"; - } - } - - // Close sitemap - $map .= ''; - - // Save sitemap - return File::setContent(ROOT . DS . 'sitemap.xml', $map); - } - - - /** - * Get pages - */ - protected static function getPages() { - - // Init vars - $pages_array = array(); - $count = 0; - - // Get pages table - $pages = new Table('pages'); - - // Get Pages List - $pages_list = $pages->select('[slug!="error404" and status="published"]'); - - foreach ($pages_list as $page) { - - $pages_array[$count]['title'] = Html::toText($page['title']); - $pages_array[$count]['parent'] = $page['parent']; - $pages_array[$count]['date'] = $page['date']; - $pages_array[$count]['author'] = $page['author']; - $pages_array[$count]['slug'] = ($page['slug'] == Option::get('defaultpage')) ? '' : $page['slug'] ; - - if (isset($page['parent'])) { - $c_p = $page['parent']; + if (isset($_page['title'])) { + $_title = $_page['title']; } else { - $c_p = ''; + $_title = ''; } - - if ($c_p != '') { - $_page = $pages->select('[slug="'.$page['parent'].'"]', null); - - if (isset($_page['title'])) { - $_title = $_page['title']; - } else { - $_title = ''; - } - $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; - } else { - $pages_array[$count]['sort'] = $page['title']; - } - $_title = ''; - $count++; + $pages_array[$count]['sort'] = $_title . ' ' . $page['title']; + } else { + $pages_array[$count]['sort'] = $page['title']; } - - // Sort pages - $_pages_list = Arr::subvalSort($pages_array, 'sort'); - - // return - return $_pages_list; + $_title = ''; + $count++; } + // Sort pages + $_pages_list = Arr::subvalSort($pages_array, 'sort'); - /** - * Get components - */ - protected static function getComponents() { + // return + return $_pages_list; + } - $components = array(); - - if (count(Plugin::$components) > 0) { - foreach (Plugin::$components as $component) { - if ( ! in_array($component, Sitemap::$forbidden_components)) $components[] = Text::lowercase($component); - } + /** + * Get components + */ + protected static function getComponents() + { + $components = array(); + + if (count(Plugin::$components) > 0) { + foreach (Plugin::$components as $component) { + if ( ! in_array($component, Sitemap::$forbidden_components)) $components[] = Text::lowercase($component); } - - return $components; } - } \ No newline at end of file + return $components; + } + +} diff --git a/plugins/box/sitemap/views/frontend/index.view.php b/plugins/box/sitemap/views/frontend/index.view.php index e06fd20..80a74cb 100644 --- a/plugins/box/sitemap/views/frontend/index.view.php +++ b/plugins/box/sitemap/views/frontend/index.view.php @@ -1,21 +1,21 @@


      - 0) { - foreach ($pages_list as $page) { - if (trim($page['parent']) !== '') $parent = $page['parent'].'/'; else $parent = ''; - if (trim($page['parent']) !== '') { echo ''; } - } + if (count($pages_list) > 0) { + foreach ($pages_list as $page) { + if (trim($page['parent']) !== '') $parent = $page['parent'].'/'; else $parent = ''; + if (trim($page['parent']) !== '') { echo ''; } + } if (count($components) == 0) { echo '
        '; } } // Display components - if (count($components) > 0) { + if (count($components) > 0) { if (count($pages_list) == 0) { echo '
          '; } foreach ($components as $component) { echo '
        • '.__(ucfirst($component), $component).'
        • '; diff --git a/plugins/box/snippets/install/snippets.manifest.xml b/plugins/box/snippets/install/snippets.manifest.xml index aa1bacb..8546642 100644 --- a/plugins/box/snippets/install/snippets.manifest.xml +++ b/plugins/box/snippets/install/snippets.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/snippets/languages/de.lang.php b/plugins/box/snippets/languages/de.lang.php index cf12611..20c328c 100644 --- a/plugins/box/snippets/languages/de.lang.php +++ b/plugins/box/snippets/languages/de.lang.php @@ -1,30 +1,30 @@ - array( - 'Snippets' => 'Snippets', - 'Snippets manager' => 'Snippet Manager', - 'Actions' => 'Aktionen', - 'Delete' => 'Löschen', - 'Edit' => 'Bearbeiten', - 'Name' => 'Name', - 'Create new snippet' => 'Erstelle neues Snippet', - 'New snippet' => 'Neues Snippet', - 'Edit snippet' => 'Bearbeite Snippet', - 'Save' => 'Save', - 'Save and exit' => 'Speichern und Schließen', - 'This field should not be empty' => 'Dieses Feld darf nicht leer sein', - 'This snippet already exists' => 'Dieses Snippet existiert bereits', - 'This snippet does not exist' => 'Dieses Snippet existiert nicht', - 'Delete snippet: :snippet' => 'Lösche Snippet: :snippet', - 'Snippet content' => 'Snippet Inhalt', - 'Snippet :name deleted' => 'Snippet :name wurde gelöscht', - 'Your changes to the snippet :name have been saved.' => 'Deine Änerungen für das Snippet :name wurden gespeichert.', - 'Delete snippet: :snippet' => 'Lösche Snippet: :snippet', - 'Required field' => 'Pflichtfeld', - 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', - 'Shortcode' => 'Shortcode', - 'PHP Code' => 'PHP Code', - ) - ); \ No newline at end of file + array( + 'Snippets' => 'Snippets', + 'Snippets manager' => 'Snippet Manager', + 'Actions' => 'Aktionen', + 'Delete' => 'Löschen', + 'Edit' => 'Bearbeiten', + 'Name' => 'Name', + 'Create new snippet' => 'Erstelle neues Snippet', + 'New snippet' => 'Neues Snippet', + 'Edit snippet' => 'Bearbeite Snippet', + 'Save' => 'Save', + 'Save and exit' => 'Speichern und Schließen', + 'This field should not be empty' => 'Dieses Feld darf nicht leer sein', + 'This snippet already exists' => 'Dieses Snippet existiert bereits', + 'This snippet does not exist' => 'Dieses Snippet existiert nicht', + 'Delete snippet: :snippet' => 'Lösche Snippet: :snippet', + 'Snippet content' => 'Snippet Inhalt', + 'Snippet :name deleted' => 'Snippet :name wurde gelöscht', + 'Your changes to the snippet :name have been saved.' => 'Deine Änerungen für das Snippet :name wurden gespeichert.', + 'Delete snippet: :snippet' => 'Lösche Snippet: :snippet', + 'Required field' => 'Pflichtfeld', + 'View Embed Code' => 'View Embed Code', + 'Embed Code' => 'Embed Code', + 'Shortcode' => 'Shortcode', + 'PHP Code' => 'PHP Code', + ) + ); diff --git a/plugins/box/snippets/languages/en.lang.php b/plugins/box/snippets/languages/en.lang.php index d3e1ac7..8e5044b 100644 --- a/plugins/box/snippets/languages/en.lang.php +++ b/plugins/box/snippets/languages/en.lang.php @@ -3,16 +3,16 @@ return array( 'snippets' => array( 'Snippets' => 'Snippets', - 'Snippets manager' => 'Snippets manager', + 'Snippets manager' => 'Snippets manager', 'Actions' => 'Actions', 'Delete' => 'Delete', 'Edit' => 'Edit', 'Name' => 'Name', 'Create new snippet' => 'Create new snippet', 'New snippet' => 'New snippet', - 'Edit snippet' => 'Edit snippet', - 'Save' => 'Save', - 'Save and exit' => 'Save and exit', + 'Edit snippet' => 'Edit snippet', + 'Save' => 'Save', + 'Save and exit' => 'Save and exit', 'This snippet already exists' => 'This snippet already exists', 'This snippet does not exist' => 'This snippet does not exist', 'Delete snippet: :snippet' => 'Delete snippet: :snippet', @@ -22,8 +22,8 @@ 'Delete snippet: :snippet' => 'Delete snippet: :snippet', 'Required field' => 'Required field', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/snippets/languages/it.lang.php b/plugins/box/snippets/languages/it.lang.php index d04a14a..fbdfab7 100644 --- a/plugins/box/snippets/languages/it.lang.php +++ b/plugins/box/snippets/languages/it.lang.php @@ -3,16 +3,16 @@ return array( 'snippets' => array( 'Snippets' => 'Snippet', - 'Snippets manager' => 'Gestione snippet', + 'Snippets manager' => 'Gestione snippet', 'Actions' => 'Azioni', 'Delete' => 'Elimina', 'Edit' => 'Modifica', - 'New snippet' => 'Nuovo snippet', - 'Create new snippet' => 'Crea nuovo snippet', + 'New snippet' => 'Nuovo snippet', + 'Create new snippet' => 'Crea nuovo snippet', 'Name' => 'Nome', 'Edit snippet' => 'Modifica snippet', - 'Save' => 'Salva', - 'Save and exit' => 'Salva ed esci', + 'Save' => 'Salva', + 'Save and exit' => 'Salva ed esci', 'This snippet already exists' => 'Tale snippet già esistente', 'This snippet does not exist' => 'Tale snippet non esiste', 'Delete snippet: :block' => 'Elimina snippet: :snippet', @@ -22,8 +22,8 @@ 'Delete snippet: :snippet' => 'Elimina snippet: :snippet', 'Required field' => 'Campo obbligatorio', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/snippets/languages/lt.lang.php b/plugins/box/snippets/languages/lt.lang.php index 0d14a8d..03fdc88 100644 --- a/plugins/box/snippets/languages/lt.lang.php +++ b/plugins/box/snippets/languages/lt.lang.php @@ -3,16 +3,16 @@ return array( 'snippets' => array( 'Snippets' => 'Fragmentai', - 'Snippets manager' => 'Fragmentų tvarkyklė', + 'Snippets manager' => 'Fragmentų tvarkyklė', 'Actions' => 'Veiksmai', 'Delete' => 'Ištrinti', 'Edit' => 'Redaguoti', 'Name' => 'Pavadinimas', 'Create new snippet' => 'Kurti naują fragmentą', 'New snippet' => 'Naujas fragmentas', - 'Edit snippet' => 'Redaguoti fragmentą', - 'Save' => 'Išsaugoti', - 'Save and exit' => 'Išsaugoti ir išeiti', + 'Edit snippet' => 'Redaguoti fragmentą', + 'Save' => 'Išsaugoti', + 'Save and exit' => 'Išsaugoti ir išeiti', 'Required field' => 'Privalomas laukas', 'This snippet already exists' => 'Toks fragmentas jau yra', 'This snippet does not exist' => 'Tokio fragmento nėra', @@ -21,8 +21,8 @@ 'Snippet :name deleted' => 'Fragmentas :name ištrintas', 'Your changes to the snippet :name have been saved.' => 'Fragmento :name pakeitimai išsaugoti.', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/snippets/languages/pt-br.lang.php b/plugins/box/snippets/languages/pt-br.lang.php index 9ddddb0..132d410 100644 --- a/plugins/box/snippets/languages/pt-br.lang.php +++ b/plugins/box/snippets/languages/pt-br.lang.php @@ -23,8 +23,8 @@ 'Delete snippet: :snippet' => 'Deletar o código: :snippet', 'Required field' => 'Campo requerido', 'View Embed Code' => 'View Embed Code', - 'Embed Code' => 'Embed Code', + 'Embed Code' => 'Embed Code', 'Shortcode' => 'Shortcode', 'PHP Code' => 'PHP Code', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/snippets/languages/ru.lang.php b/plugins/box/snippets/languages/ru.lang.php index e61d0b4..38f87e2 100644 --- a/plugins/box/snippets/languages/ru.lang.php +++ b/plugins/box/snippets/languages/ru.lang.php @@ -3,16 +3,16 @@ return array( 'snippets' => array( 'Snippets' => 'Сниппеты', - 'Snippets manager' => 'Менеджер сниппетов', + 'Snippets manager' => 'Менеджер сниппетов', 'Actions' => 'Действия', 'Delete' => 'Удалить', 'Edit' => 'Редактировать', - 'New snippet' => 'Новый сниппет', - 'Create new snippet' => 'Создать новый сниппет', + 'New snippet' => 'Новый сниппет', + 'Create new snippet' => 'Создать новый сниппет', 'Name' => 'Название', 'Edit snippet' => 'Редактирование сниппета', - 'Save' => 'Сохранить', - 'Save and exit' => 'Сохранить и выйти', + 'Save' => 'Сохранить', + 'Save and exit' => 'Сохранить и выйти', 'This snippet already exists' => 'Такой сниппет уже существует', 'This snippet does not exist' => 'Такого сниппета не существует', 'Delete snippet: :block' => 'Удалить сниппет: :snippet', @@ -22,8 +22,8 @@ 'Delete snippet: :snippet' => 'Удалить сниппет: :snippet', 'Required field' => 'Обязательное поле', 'View Embed Code' => 'Код для вставки', - 'Embed Code' => 'Код для вставки', + 'Embed Code' => 'Код для вставки', 'Shortcode' => 'Шорткод', 'PHP Code' => 'PHP код', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/snippets/languages/uk.lang.php b/plugins/box/snippets/languages/uk.lang.php index 95d8f0e..375f252 100644 --- a/plugins/box/snippets/languages/uk.lang.php +++ b/plugins/box/snippets/languages/uk.lang.php @@ -3,16 +3,16 @@ return array( 'snippets' => array( 'Snippets' => 'Сніппети', - 'Snippets manager' => 'Менеджер сніппетів', + 'Snippets manager' => 'Менеджер сніппетів', 'Actions' => 'Дії', 'Delete' => 'Видалити', 'Edit' => 'Редагувати', - 'New snippet' => 'Новий сніппет', - 'Create new snippet' => 'Створити новий сніппет', + 'New snippet' => 'Новий сніппет', + 'Create new snippet' => 'Створити новий сніппет', 'Name' => 'Назва', 'Edit snippet' => 'Редагування сніппета', - 'Save' => 'Зберегти', - 'Save and exit' => 'Зберегти та вийти', + 'Save' => 'Зберегти', + 'Save and exit' => 'Зберегти та вийти', 'This snippet already exists' => 'Такий сніппет вже існує', 'This snippet does not exist' => 'Такого сніппета не існує', 'Delete snippet: :block' => 'Видалити сніппет: :snippet', @@ -22,8 +22,8 @@ 'Delete snippet: :snippet' => 'Видалити сніппет: :snippet', 'Required field' => 'Обов’язкове поле', 'View Embed Code' => 'Код для вставки', - 'Embed Code' => 'Код для вставки', + 'Embed Code' => 'Код для вставки', 'Shortcode' => 'Шорткод', 'PHP Code' => 'PHP код', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/snippets/snippets.admin.php b/plugins/box/snippets/snippets.admin.php index a94149d..a3f08c0 100755 --- a/plugins/box/snippets/snippets.admin.php +++ b/plugins/box/snippets/snippets.admin.php @@ -1,144 +1,144 @@ :name
          have been saved.', 'snippets', array(':name' => Security::safeName(Request::post('name'))))); + if (count($errors) == 0) { - if (Request::post('add_snippets_and_exit')) { - Request::redirect('index.php?id=snippets'); - } else { - Request::redirect('index.php?id=snippets&action=edit_snippet&filename='.Security::safeName(Request::post('name'))); - } + // Save snippet + File::setContent($snippets_path.Security::safeName(Request::post('name')).'.snippet.php', Request::post('content')); + + Notification::set('success', __('Your changes to the snippet :name have been saved.', 'snippets', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_snippets_and_exit')) { + Request::redirect('index.php?id=snippets'); + } else { + Request::redirect('index.php?id=snippets&action=edit_snippet&filename='.Security::safeName(Request::post('name'))); } + } - } else { die('csrf detected!'); } - } - // Save fields - if (Request::post('name')) $name = Request::post('name'); else $name = ''; - if (Request::post('content')) $content = Request::post('content'); else $content = ''; - - // Display view - View::factory('box/snippets/views/backend/add') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->display(); - break; + } else { die('csrf detected!'); } + } + // Save fields + if (Request::post('name')) $name = Request::post('name'); else $name = ''; + if (Request::post('content')) $content = Request::post('content'); else $content = ''; - // Edit snippet - // ------------------------------------- - case "edit_snippet": - // Save current snippet action - if (Request::post('edit_snippets') || Request::post('edit_snippets_and_exit') ) { + // Display view + View::factory('box/snippets/views/backend/add') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->display(); + break; - if (Security::check(Request::post('csrf'))) { + // Edit snippet + // ------------------------------------- + case "edit_snippet": + // Save current snippet action + if (Request::post('edit_snippets') || Request::post('edit_snippets_and_exit') ) { - if (trim(Request::post('name')) == '') $errors['snippets_empty_name'] = __('Required field', 'snippets'); - if ((file_exists($snippets_path.Security::safeName(Request::post('name')).'.snippet.php')) and (Security::safeName(Request::post('snippets_old_name')) !== Security::safeName(Request::post('name')))) $errors['snippets_exists'] = __('This snippet already exists', 'snippets'); + if (Security::check(Request::post('csrf'))) { - // Save fields - if (Request::post('content')) $content = Request::post('content'); else $content = ''; - if (count($errors) == 0) { + if (trim(Request::post('name')) == '') $errors['snippets_empty_name'] = __('Required field', 'snippets'); + if ((file_exists($snippets_path.Security::safeName(Request::post('name')).'.snippet.php')) and (Security::safeName(Request::post('snippets_old_name')) !== Security::safeName(Request::post('name')))) $errors['snippets_exists'] = __('This snippet already exists', 'snippets'); - $snippet_old_filename = $snippets_path.Request::post('snippets_old_name').'.snippet.php'; - $snippet_new_filename = $snippets_path.Security::safeName(Request::post('name')).'.snippet.php'; - if ( ! empty($snippet_old_filename)) { - if ($snippet_old_filename !== $snippet_new_filename) { - rename($snippet_old_filename, $snippet_new_filename); - $save_filename = $snippet_new_filename; - } else { - $save_filename = $snippet_new_filename; - } + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $snippet_old_filename = $snippets_path.Request::post('snippets_old_name').'.snippet.php'; + $snippet_new_filename = $snippets_path.Security::safeName(Request::post('name')).'.snippet.php'; + if ( ! empty($snippet_old_filename)) { + if ($snippet_old_filename !== $snippet_new_filename) { + rename($snippet_old_filename, $snippet_new_filename); + $save_filename = $snippet_new_filename; } else { $save_filename = $snippet_new_filename; } + } else { + $save_filename = $snippet_new_filename; + } - // Save snippet - File::setContent($save_filename, Request::post('content')); + // Save snippet + File::setContent($save_filename, Request::post('content')); - Notification::set('success', __('Your changes to the snippet :name have been saved.', 'snippets', array(':name' => basename($save_filename, '.snippet.php')))); + Notification::set('success', __('Your changes to the snippet :name have been saved.', 'snippets', array(':name' => basename($save_filename, '.snippet.php')))); - if (Request::post('edit_snippets_and_exit')) { - Request::redirect('index.php?id=snippets'); - } else { - Request::redirect('index.php?id=snippets&action=edit_snippet&filename='.Security::safeName(Request::post('name'))); - } - } - - } else { die('csrf detected!'); } - } - if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); - $content = File::getContent($snippets_path.Request::get('filename').'.snippet.php'); - - // Display view - View::factory('box/snippets/views/backend/edit') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->display(); - break; - case "delete_snippet": - - if (Security::check(Request::get('token'))) { - - File::delete($snippets_path.Request::get('filename').'.snippet.php'); - Notification::set('success', __('Snippet :name deleted', 'snippets', array(':name' => File::name(Request::get('filename'))))); - Request::redirect('index.php?id=snippets'); + if (Request::post('edit_snippets_and_exit')) { + Request::redirect('index.php?id=snippets'); + } else { + Request::redirect('index.php?id=snippets&action=edit_snippet&filename='.Security::safeName(Request::post('name'))); + } + } } else { die('csrf detected!'); } + } + if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); + $content = File::getContent($snippets_path.Request::get('filename').'.snippet.php'); - break; - } - } else { + // Display view + View::factory('box/snippets/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->display(); + break; + case "delete_snippet": - // Get snippets - $snippets_list = File::scan($snippets_path, '.snippet.php'); + if (Security::check(Request::get('token'))) { - // Display view - View::factory('box/snippets/views/backend/index') - ->assign('snippets_list', $snippets_list) - ->display(); + File::delete($snippets_path.Request::get('filename').'.snippet.php'); + Notification::set('success', __('Snippet :name deleted', 'snippets', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=snippets'); + } else { die('csrf detected!'); } + + break; } + } else { + + // Get snippets + $snippets_list = File::scan($snippets_path, '.snippet.php'); + + // Display view + View::factory('box/snippets/views/backend/index') + ->assign('snippets_list', $snippets_list) + ->display(); + } - - } \ No newline at end of file + } + +} diff --git a/plugins/box/snippets/snippets.plugin.php b/plugins/box/snippets/snippets.plugin.php index 78f7cee..f3a9987 100644 --- a/plugins/box/snippets/snippets.plugin.php +++ b/plugins/box/snippets/snippets.plugin.php @@ -1,104 +1,101 @@ + * echo Snippet::get('snippetname'); + * echo Snippet::get('snippetname', array('message' => 'Hello World')); + * * + * @param string $name Snippet file name + * @param string $vars Vars + * @return string */ + public static function get($name, $vars = array()) + { + $vars['get'] = $name; - - // Register plugin - Plugin::register( __FILE__, - __('Snippets', 'snippets'), - __('Snippets manager plugin', 'snippets'), - '1.0.0', - 'Awilum', - 'http://monstra.org/', - null, - 'box'); - - - if (Session::exists('user_role') && in_array(Session::get('user_role'),array('admin'))) { - - // Include Admin - Plugin::admin('snippets', 'box'); - + return Snippet::_content($vars); } - // Add Plugin Javascript - Javascript::add('plugins/box/snippets/js/snippets.js', 'backend'); - - // Add shortcode {snippet} - Shortcode::add('snippet', 'Snippet::_content'); - - /** - * Snippet class + * Returns snippet content for shortcode {snippet get="snippetname"} + * + * + * {snippet get="snippetname"} + * {snippet get="snippetname" message="Hello World"} + * + * + * @param array $attributes Array of attributes + * @return string */ - class Snippet { + public static function _content($attributes) + { + // Extracst attributes + extract($attributes); + // Get snippet name + $name = (isset($get)) ? (string) $get : ''; - /** - * Get snippet - * - * - * echo Snippet::get('snippetname'); - * echo Snippet::get('snippetname', array('message' => 'Hello World')); - * - * - * @param string $name Snippet file name - * @param string $vars Vars - * @return string - */ - public static function get($name, $vars = array()) { - $vars['get'] = $name; - return Snippet::_content($vars); - } + // Get snippet path + $snippet_path = STORAGE . DS . 'snippets' . DS . $name . '.snippet.php'; + // Get snippet content + if (File::exists($snippet_path)) { - /** - * Returns snippet content for shortcode {snippet get="snippetname"} - * - * - * {snippet get="snippetname"} - * {snippet get="snippetname" message="Hello World"} - * - * - * @param array $attributes Array of attributes - * @return string - */ - public static function _content($attributes) { + // Turn on output buffering + ob_start(); - // Extracst attributes - extract($attributes); + // Include view file + include $snippet_path; - // Get snippet name - $name = (isset($get)) ? (string)$get : ''; - - // Get snippet path - $snippet_path = STORAGE . DS . 'snippets' . DS . $name . '.snippet.php'; + // Output... + return ob_get_clean(); - // Get snippet content - if (File::exists($snippet_path)) { - - // Turn on output buffering - ob_start(); - - // Include view file - include $snippet_path; - - // Output... - return ob_get_clean(); - - } else { - if (Session::exists('admin') && Session::get('admin') == true) { - return __('Snippet :name is not found!', 'snippets', array(':name' => $name)); - } + } else { + if (Session::exists('admin') && Session::get('admin') == true) { + return __('Snippet :name is not found!', 'snippets', array(':name' => $name)); } - } - } \ No newline at end of file + } + } +} diff --git a/plugins/box/snippets/views/backend/add.view.php b/plugins/box/snippets/views/backend/add.view.php index 0e7917a..ca97527 100644 --- a/plugins/box/snippets/views/backend/add.view.php +++ b/plugins/box/snippets/views/backend/add.view.php @@ -5,12 +5,10 @@ - 'form-horizontal'))); ?> -
          diff --git a/plugins/box/snippets/views/backend/edit.view.php b/plugins/box/snippets/views/backend/edit.view.php index ceb53b3..a39a42b 100644 --- a/plugins/box/snippets/views/backend/edit.view.php +++ b/plugins/box/snippets/views/backend/edit.view.php @@ -4,7 +4,7 @@ - - +
          (isset($errors['snippets_empty_name']) || isset($errors['snippets_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?>.snippet.php
          @@ -39,8 +38,8 @@ Form::submit('edit_snippets', __('Save', 'snippets'), array('class' => 'btn default')). Html::nbsp(). Form::close() ); - + } else { echo '
          '.__('This snippet does not exist').'
          '; } -?> \ No newline at end of file +?> diff --git a/plugins/box/snippets/views/backend/index.view.php b/plugins/box/snippets/views/backend/index.view.php index 979ff37..e8f7b93 100755 --- a/plugins/box/snippets/views/backend/index.view.php +++ b/plugins/box/snippets/views/backend/index.view.php @@ -4,9 +4,9 @@ __('Create New Snippet', 'snippets'), 'class' => 'btn btn-small')). Html::nbsp(3) - ); + ); ?>

          @@ -22,7 +22,7 @@ - +
          @@ -31,7 +31,7 @@ +
        'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete snippet: :snippet', 'snippets', array(':snippet' => basename($snippet, '.snippet.php')))."')")); @@ -60,4 +60,4 @@

    -
    \ No newline at end of file +
    diff --git a/plugins/box/system/install/system.manifest.xml b/plugins/box/system/install/system.manifest.xml index 36aa859..2a6a9ee 100644 --- a/plugins/box/system/install/system.manifest.xml +++ b/plugins/box/system/install/system.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/system/languages/de.lang.php b/plugins/box/system/languages/de.lang.php index 0af5f2e..25baf27 100644 --- a/plugins/box/system/languages/de.lang.php +++ b/plugins/box/system/languages/de.lang.php @@ -1,81 +1,81 @@ - array( - 'System' => 'System', - 'Published a new version of the :monstra' => 'Veröffentlicht eine neue Version von dem :monstra', - 'Sitemap created' => 'Sitemap wurde erstellt', - 'Create sitemap' => 'Erstelle Sitemap', - 'on' => 'An', - 'off'=> 'Aus', - 'Site url' => 'Seiten-URL', - 'Maintenance Mode' => 'Wartungsmodus', - 'Maintenance Mode On' => 'Wartungsmodus An', - 'Maintenance Mode Off' => 'Wartungsmodus Aus', - 'Site settings' => 'Seiteneinstellungen', - 'System settings' => 'Systemeinstellungen', - 'Site name' => 'Seiten-Name', - 'Site description' => 'Seiten-Beschreibung', - 'Site keywords' => 'Seiten-Schlagwörter', - 'Site slogan' => 'Seiten-Slogan', - 'Default page' => 'Standardseite', - 'Time zone' => 'Zeitzone', - 'Language' => 'Sprache', - 'Save' => 'Speichern', - 'Site' => 'Seite', - 'System version' => 'Systemversion', - 'System version ID' => 'Systemversions ID', - 'GZIP' => 'GZIP', - 'Debugging' => 'Fehlerbeseitigung', - 'Plugin API' => 'Plugin API', - 'Plugins active' => 'Plugins aktiv', - 'Actions registered' => 'Aktionen registriert', - 'Filters registered' => 'Filter registriert', - 'logout' => 'logout', - 'site' => 'seite', - 'Core' => 'Core', - 'Delete temporary files' => 'Temporäre Dateien löschen', - 'Download the latest version' => 'Lade die letzte Version herunter', - 'Powered by' => 'Powered by', - 'Administration' => 'Administration', - 'Settings' => 'Einstellungen', - 'Temporary files deleted' => 'Temporäre Dateien gelöscht', - 'Extends' => 'Erweitert', - 'View site' => 'Seite ansehen', - 'Welcome, :username' => 'Willkommen, :username', - 'Reset Password' => 'Password zurücksetzen', - '< Back to Website' => '< Zurück zur Webseite', - 'Forgot your password? >' => 'Passwort vergessen? >', - 'Administration >' => 'Administration >', - 'Send New Password' => 'Neues Passwort zusenden', - 'This user does not exist' => 'Dieser Benutzer existiert nicht', - 'Version' => 'Version', - - 'Install script writable' => 'Installationsskript beschreibbar', - 'Install script not writable' => 'Installationsskript nicht beschreibbar', - 'Directory: :dir writable' => 'Ordner: :dir beschreibbar', - 'Directory: :dir not writable' => 'Ordner: :dir nicht beschreibbar', - 'PHP Version' => 'PHP Version', - 'Module DOM is installed' => 'Modul DOM ist installiert', - 'Module DOM is required' => 'Modul DOM ist erforderlich', - 'Module Mod Rewrite is installed' => 'Modul Mod Rewrite ist installiert', - 'Module SimpleXML is installed' => 'Modul SimpleXML ist installiert', - 'PHP 5.2 or greater is required' => 'PHP 5.2 oder höher erforderlich', - 'Apache Mod Rewrite is required' => 'Apache Mod Rewrite ist erforderlich', - 'SimpleXML module is required' => 'SimpleXML-Modul ist erforderlich', - 'Field "Site name" is empty' => 'Feld "Seiten-Name" ist leer', - 'Field "Email" is empty' => 'Feld "Email" ist leer', - 'Field "Username" is empty' => 'Feld "Benutzername" ist leer', - 'Field "Password" is empty' => 'Feld "Passwort" ist leer', - 'Field "Site url" is empty' => 'Feld "Seiten-URL" ist leer', - 'Email not valid' => 'E-Mail ist ungültig', - 'Install' => 'Installieren', - '...Monstra says...' => '...Monstra sagt...', - 'Sitemap file writable' => 'Sitemap-Datei beschreibbar', - 'Sitemap file not writable' => 'Sitemap-Datei ist nicht beschreibbar', - 'Main .htaccess file writable' => 'Haupt .htaccess-Datei ist beschreibbar', - 'Main .htaccess file not writable' => 'Haupt .htaccess-Datei ist nicht beschreibbar', - 'Official Support Forum' => 'Official Support Forum', - 'Documentation' => 'Documentation', - ) - ); \ No newline at end of file + array( + 'System' => 'System', + 'Published a new version of the :monstra' => 'Veröffentlicht eine neue Version von dem :monstra', + 'Sitemap created' => 'Sitemap wurde erstellt', + 'Create sitemap' => 'Erstelle Sitemap', + 'on' => 'An', + 'off'=> 'Aus', + 'Site url' => 'Seiten-URL', + 'Maintenance Mode' => 'Wartungsmodus', + 'Maintenance Mode On' => 'Wartungsmodus An', + 'Maintenance Mode Off' => 'Wartungsmodus Aus', + 'Site settings' => 'Seiteneinstellungen', + 'System settings' => 'Systemeinstellungen', + 'Site name' => 'Seiten-Name', + 'Site description' => 'Seiten-Beschreibung', + 'Site keywords' => 'Seiten-Schlagwörter', + 'Site slogan' => 'Seiten-Slogan', + 'Default page' => 'Standardseite', + 'Time zone' => 'Zeitzone', + 'Language' => 'Sprache', + 'Save' => 'Speichern', + 'Site' => 'Seite', + 'System version' => 'Systemversion', + 'System version ID' => 'Systemversions ID', + 'GZIP' => 'GZIP', + 'Debugging' => 'Fehlerbeseitigung', + 'Plugin API' => 'Plugin API', + 'Plugins active' => 'Plugins aktiv', + 'Actions registered' => 'Aktionen registriert', + 'Filters registered' => 'Filter registriert', + 'logout' => 'logout', + 'site' => 'seite', + 'Core' => 'Core', + 'Delete temporary files' => 'Temporäre Dateien löschen', + 'Download the latest version' => 'Lade die letzte Version herunter', + 'Powered by' => 'Powered by', + 'Administration' => 'Administration', + 'Settings' => 'Einstellungen', + 'Temporary files deleted' => 'Temporäre Dateien gelöscht', + 'Extends' => 'Erweitert', + 'View site' => 'Seite ansehen', + 'Welcome, :username' => 'Willkommen, :username', + 'Reset Password' => 'Password zurücksetzen', + '< Back to Website' => '< Zurück zur Webseite', + 'Forgot your password? >' => 'Passwort vergessen? >', + 'Administration >' => 'Administration >', + 'Send New Password' => 'Neues Passwort zusenden', + 'This user does not exist' => 'Dieser Benutzer existiert nicht', + 'Version' => 'Version', + + 'Install script writable' => 'Installationsskript beschreibbar', + 'Install script not writable' => 'Installationsskript nicht beschreibbar', + 'Directory: :dir writable' => 'Ordner: :dir beschreibbar', + 'Directory: :dir not writable' => 'Ordner: :dir nicht beschreibbar', + 'PHP Version' => 'PHP Version', + 'Module DOM is installed' => 'Modul DOM ist installiert', + 'Module DOM is required' => 'Modul DOM ist erforderlich', + 'Module Mod Rewrite is installed' => 'Modul Mod Rewrite ist installiert', + 'Module SimpleXML is installed' => 'Modul SimpleXML ist installiert', + 'PHP 5.2 or greater is required' => 'PHP 5.2 oder höher erforderlich', + 'Apache Mod Rewrite is required' => 'Apache Mod Rewrite ist erforderlich', + 'SimpleXML module is required' => 'SimpleXML-Modul ist erforderlich', + 'Field "Site name" is empty' => 'Feld "Seiten-Name" ist leer', + 'Field "Email" is empty' => 'Feld "Email" ist leer', + 'Field "Username" is empty' => 'Feld "Benutzername" ist leer', + 'Field "Password" is empty' => 'Feld "Passwort" ist leer', + 'Field "Site url" is empty' => 'Feld "Seiten-URL" ist leer', + 'Email not valid' => 'E-Mail ist ungültig', + 'Install' => 'Installieren', + '...Monstra says...' => '...Monstra sagt...', + 'Sitemap file writable' => 'Sitemap-Datei beschreibbar', + 'Sitemap file not writable' => 'Sitemap-Datei ist nicht beschreibbar', + 'Main .htaccess file writable' => 'Haupt .htaccess-Datei ist beschreibbar', + 'Main .htaccess file not writable' => 'Haupt .htaccess-Datei ist nicht beschreibbar', + 'Official Support Forum' => 'Official Support Forum', + 'Documentation' => 'Documentation', + ) + ); diff --git a/plugins/box/system/languages/en.lang.php b/plugins/box/system/languages/en.lang.php index 85a69c8..60e7e7f 100644 --- a/plugins/box/system/languages/en.lang.php +++ b/plugins/box/system/languages/en.lang.php @@ -1,5 +1,5 @@ array( 'System' => 'System', @@ -7,7 +7,7 @@ 'Sitemap created' => 'Sitemap created', 'Create sitemap' => 'Create sitemap', 'on' => 'on', - 'off'=> 'off', + 'off'=> 'off', 'Site url' => 'Site url', 'Maintenance Mode' => 'Maintenance Mode', 'Maintenance Mode On' => 'Maintenance Mode On', @@ -22,13 +22,13 @@ 'Time zone' => 'Time zone', 'Language' => 'Language', 'Save' => 'Save', - 'Site' => 'Site', + 'Site' => 'Site', 'System version' => 'System version', 'System version ID' => 'System version ID', 'GZIP' => 'GZIP', 'Debugging' => 'Debugging', 'Plugin API' => 'Plugin API', - 'Plugins active' => 'Plugins active', + 'Plugins active' => 'Plugins active', 'Actions registered' => 'Actions registered', 'Filters registered' => 'Filters registered', 'logout' => 'logout', @@ -79,4 +79,4 @@ 'Official Support Forum' => 'Official Support Forum', 'Documentation' => 'Documentation', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/system/languages/it.lang.php b/plugins/box/system/languages/it.lang.php index 2abbc3d..11159ab 100644 --- a/plugins/box/system/languages/it.lang.php +++ b/plugins/box/system/languages/it.lang.php @@ -1,5 +1,5 @@ array( 'System' => 'Sistema', @@ -7,7 +7,7 @@ 'Sitemap created' => 'Sitemap è stata creata', 'Create sitemap' => 'Crea sitemap', 'on' => 'on', - 'off'=> 'off', + 'off'=> 'off', 'Site url' => 'URL del sito', 'Maintenance Mode' => 'Modalità manutenzione', 'Maintenance Mode On' => 'Abilita modalità manutenzione', @@ -28,7 +28,7 @@ 'GZIP' => 'Compressione GZIP', 'Debugging' => 'Debugging', 'Plugin API' => 'Plugin API', - 'Plugins active' => 'Plugin attivi', + 'Plugins active' => 'Plugin attivi', 'Actions registered' => 'Azioni registrati', 'Filters registered' => 'Filtri registrati', 'logout' => 'esci', @@ -51,7 +51,6 @@ 'This user does not exist' => 'Tale utente non esiste', 'Version' => 'Versione', - 'Install script writable' => 'Script d’installazione è scrivibile', 'Install script not writable' => 'Script d’installazione non è scrivibile', 'Directory: :dir writable' => 'Directory :dir è scrivibile', @@ -79,4 +78,4 @@ 'Official Support Forum' => 'Official Support Forum', 'Documentation' => 'Documentation', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/system/languages/lt.lang.php b/plugins/box/system/languages/lt.lang.php index 89b0225..5f06518 100644 --- a/plugins/box/system/languages/lt.lang.php +++ b/plugins/box/system/languages/lt.lang.php @@ -1,5 +1,5 @@ array( 'System' => 'Sistema', @@ -7,7 +7,7 @@ 'Sitemap created' => 'Sitemap sukurtas', 'Create sitemap' => 'Sukurti sitemap', 'on' => 'įjungti', - 'off'=> 'išjungti', + 'off'=> 'išjungti', 'Site url' => 'Tinklapio adresas (url)', 'Maintenance Mode' => 'Remonto režimas', 'Maintenance Mode On' => 'Įjungti remonto režimą', @@ -22,13 +22,13 @@ 'Time zone' => 'Laiko zona', 'Language' => 'Kalba', 'Save' => 'Išsaugoti', - 'Site' => 'Tinklapis', + 'Site' => 'Tinklapis', 'System version' => 'Sistemos versija', 'System version ID' => 'Sistemos versijos ID', 'GZIP' => 'GZIP', 'Debugging' => 'Derinimas', 'Plugin API' => 'Įskiepių API', - 'Plugins active' => 'Aktyvūs įskiepiai', + 'Plugins active' => 'Aktyvūs įskiepiai', 'Actions registered' => 'Veiksmai užregistruoti', 'Filters registered' => 'Filtrai užregistruoti', 'logout' => 'atsijungti', @@ -78,4 +78,4 @@ 'Official Support Forum' => 'Pagalbos forumas', 'Documentation' => 'Dokumentacija', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/system/languages/pt-br.lang.php b/plugins/box/system/languages/pt-br.lang.php index b1bb78b..616ecde 100644 --- a/plugins/box/system/languages/pt-br.lang.php +++ b/plugins/box/system/languages/pt-br.lang.php @@ -1,5 +1,5 @@ array( 'System' => 'Sistema', @@ -7,7 +7,7 @@ 'Sitemap created' => 'Mapa do site criado', 'Create sitemap' => 'Criar mapa do site', 'on' => 'on', - 'off'=> 'off', + 'off'=> 'off', 'Site url' => 'URL do site', 'Maintenance Mode' => 'Modo de manutenção', 'Maintenance Mode On' => 'Modo de manutenção online', @@ -22,7 +22,7 @@ 'Time zone' => 'Timezone padrão', 'Language' => 'Linguagem', 'Save' => 'Salvar', - 'Site' => 'Site', + 'Site' => 'Site', 'System version' => 'Versão do sistema', 'System version ID' => 'ID (longo) da versão do sistema', 'GZIP' => 'GZIP', @@ -77,4 +77,4 @@ 'Official Support Forum' => 'Official Support Forum', 'Documentation' => 'Documentation', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/system/languages/ru.lang.php b/plugins/box/system/languages/ru.lang.php index 6cabd47..17afa9c 100644 --- a/plugins/box/system/languages/ru.lang.php +++ b/plugins/box/system/languages/ru.lang.php @@ -1,5 +1,5 @@ array( 'System' => 'Система', @@ -7,7 +7,7 @@ 'Sitemap created' => 'Карта сайта создана', 'Create sitemap' => 'Создать карту сайта', 'on' => 'включен', - 'off'=> 'выключен', + 'off'=> 'выключен', 'Site url' => 'Адрес сайта', 'Maintenance Mode' => 'Тех. обслуживание', 'Maintenance Mode On' => 'Включить тех. обслуживание', @@ -28,7 +28,7 @@ 'GZIP' => 'Cжатие GZIP', 'Debugging' => 'Дебаггинг', 'Plugin API' => 'Plugin API', - 'Plugins active' => 'Подключенные плагины', + 'Plugins active' => 'Подключенные плагины', 'Actions registered' => 'Зарегистрированные экшны', 'Filters registered' => 'Зарегистрированные фильтры', 'logout' => 'выход', @@ -79,4 +79,4 @@ 'Official Support Forum' => 'Официальный Форум Поддержки', 'Documentation' => 'Документация', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/system/languages/uk.lang.php b/plugins/box/system/languages/uk.lang.php index 97a4698..fb396f1 100644 --- a/plugins/box/system/languages/uk.lang.php +++ b/plugins/box/system/languages/uk.lang.php @@ -1,5 +1,5 @@ array( 'System' => 'Система', @@ -7,7 +7,7 @@ 'Sitemap created' => 'Карта сайту створена', 'Create sitemap' => 'Створити карту сайту', 'on' => 'включено', - 'off'=> 'вимкнено', + 'off'=> 'вимкнено', 'Site url' => 'Адреса сайту', 'Maintenance Mode' => 'Тех. обслуговування', 'Maintenance Mode On' => 'Включити тех. обслуговування', @@ -28,7 +28,7 @@ 'GZIP' => 'Стиснення GZIP', 'Debugging' => 'Дебаггінг', 'Plugin API' => 'Плагін API', - 'Plugins active' => 'Підключені плагіни', + 'Plugins active' => 'Підключені плагіни', 'Actions registered' => 'Зареєстровані екшени', 'Filters registered' => 'Зареєстровані фітри', 'logout' => 'вихід', @@ -79,4 +79,4 @@ 'Official Support Forum' => 'Офіційний Форум Підтримки', 'Documentation' => 'Документація', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/system/system.admin.php b/plugins/box/system/system.admin.php index ea05fe0..588ccad 100755 --- a/plugins/box/system/system.admin.php +++ b/plugins/box/system/system.admin.php @@ -1,175 +1,169 @@ - $.getJSON("http://monstra.org/api/version.php?jsoncallback=?", - function(data){ - var current_monstra_version = "'.Core::VERSION.'"; - var stable_monstra_version = data.version; - if (current_monstra_version < stable_monstra_version) { - $("#update-monstra").addClass("alert").html("'.__("Published a new version of the :monstra", "system", array(":monstra" => "Monstra")).'"); - } +/** + * Check Monstra version + */ +function checkMonstraVersion() +{ + echo (' + - '); - } - - /** - * System Admin - */ - class SystemAdmin extends Backend { - - - /** - * System plugin admin - */ - public static function main() { - - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - - $filters = Filter::$filters; - $plugins = Plugin::$plugins; - $components = Plugin::$components; - $actions = Action::$actions; - - - // Get pages table - $pages = new Table('pages'); - - - // Get system timezone - $system_timezone = Option::get('timezone'); - - - // Get languages files - $language_files = File::scan(PLUGINS_BOX . DS . 'system' . DS . 'languages' . DS, '.lang.php'); - foreach ($language_files as $language) { - $parts = explode('.', $language); - $languages_array[$parts[0]] = I18n::$locales[$parts[0]]; - } - - // Get all pages - $pages_array = array(); - $pages_list = $pages->select('[slug!="error404" and parent="" and status="published"]'); - foreach ($pages_list as $page) { - $pages_array[$page['slug']] = Html::toText($page['title']); - } - - - // Create Sitemap - // ------------------------------------- - if (Request::get('sitemap') == 'create') { - - if (Security::check(Request::get('token'))) { - - Notification::set('success', __('Sitemap created', 'system')); - - Sitemap::create(); - - Request::redirect('index.php?id=system'); - - } else { die('csrf detected!'); } - - } - - - // Delete temporary files - // ------------------------------------- - if (Request::get('temporary_files') == 'delete') { - - if (Security::check(Request::get('token'))) { - - $namespaces = Dir::scan(CACHE); - if (count($namespaces) > 0) { - foreach ($namespaces as $namespace) { - Dir::delete(CACHE . DS . $namespace); - } - } - - $files = File::scan(MINIFY, array('css','js','php')); - if (count($files) > 0) { - foreach ($files as $file) { - File::delete(MINIFY . DS . $file); - } - } - - if (count(File::scan(MINIFY, array('css', 'js', 'php'))) == 0 && count(Dir::scan(CACHE)) == 0) { - Notification::set('success', __('Temporary files deleted', 'system')); - Request::redirect('index.php?id=system'); - } } - } + ); + + '); +} - // Set maintenance state on or off - // ------------------------------------- - if (Request::get('maintenance')) { +/** + * System Admin + */ +class SystemAdmin extends Backend +{ + /** + * System plugin admin + */ + public static function main() + { + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - if (Security::check(Request::get('token'))) { + $filters = Filter::$filters; + $plugins = Plugin::$plugins; + $components = Plugin::$components; + $actions = Action::$actions; - if ('on' == Request::get('maintenance')) { - Option::update('maintenance_status', 'on'); - Request::redirect('index.php?id=system'); + // Get pages table + $pages = new Table('pages'); + + // Get system timezone + $system_timezone = Option::get('timezone'); + + // Get languages files + $language_files = File::scan(PLUGINS_BOX . DS . 'system' . DS . 'languages' . DS, '.lang.php'); + foreach ($language_files as $language) { + $parts = explode('.', $language); + $languages_array[$parts[0]] = I18n::$locales[$parts[0]]; + } + + // Get all pages + $pages_array = array(); + $pages_list = $pages->select('[slug!="error404" and parent="" and status="published"]'); + foreach ($pages_list as $page) { + $pages_array[$page['slug']] = Html::toText($page['title']); + } + + // Create Sitemap + // ------------------------------------- + if (Request::get('sitemap') == 'create') { + + if (Security::check(Request::get('token'))) { + + Notification::set('success', __('Sitemap created', 'system')); + + Sitemap::create(); + + Request::redirect('index.php?id=system'); + + } else { die('csrf detected!'); } + + } + + // Delete temporary files + // ------------------------------------- + if (Request::get('temporary_files') == 'delete') { + + if (Security::check(Request::get('token'))) { + + $namespaces = Dir::scan(CACHE); + if (count($namespaces) > 0) { + foreach ($namespaces as $namespace) { + Dir::delete(CACHE . DS . $namespace); } - - if ('off' == Request::get('maintenance')) { - Option::update('maintenance_status', 'off'); - Request::redirect('index.php?id=system'); - } - } - } - // Edit settings - // ------------------------------------- - if (Request::post('edit_settings')) { - - if (Security::check(Request::post('csrf'))) { - - // Add trailing slashes - $_site_url = Request::post('system_url'); - if ($_site_url[strlen($_site_url)-1] !== '/') { - $_site_url = $_site_url.'/'; + $files = File::scan(MINIFY, array('css','js','php')); + if (count($files) > 0) { + foreach ($files as $file) { + File::delete(MINIFY . DS . $file); } + } - Option::update(array('sitename' => Request::post('site_name'), - 'keywords' => Request::post('site_keywords'), - 'description' => Request::post('site_description'), - 'slogan' => Request::post('site_slogan'), - 'defaultpage' => Request::post('site_default_page'), - 'siteurl' => $_site_url, - 'timezone' => Request::post('system_timezone'), - 'language' => Request::post('system_language'), - 'maintenance_message' => Request::post('site_maintenance_message'))); - - Notification::set('success', __('Your changes have been saved.', 'system')); + if (count(File::scan(MINIFY, array('css', 'js', 'php'))) == 0 && count(Dir::scan(CACHE)) == 0) { + Notification::set('success', __('Temporary files deleted', 'system')); Request::redirect('index.php?id=system'); - - } else { die('csrf detected!'); } + } } + } - // Its mean that you can add your own actions for this plugin - Action::run('admin_system_extra_actions'); + // Set maintenance state on or off + // ------------------------------------- + if (Request::get('maintenance')) { - // Display view - View::factory('box/system/views/backend/index') - ->assign('pages_array', $pages_array) - ->assign('languages_array', $languages_array) - ->display(); + if (Security::check(Request::get('token'))) { - } else { + if ('on' == Request::get('maintenance')) { + Option::update('maintenance_status', 'on'); + Request::redirect('index.php?id=system'); + } - Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); - } + if ('off' == Request::get('maintenance')) { + Option::update('maintenance_status', 'off'); + Request::redirect('index.php?id=system'); + } + + } + } + + // Edit settings + // ------------------------------------- + if (Request::post('edit_settings')) { + + if (Security::check(Request::post('csrf'))) { + + // Add trailing slashes + $_site_url = Request::post('system_url'); + if ($_site_url[strlen($_site_url)-1] !== '/') { + $_site_url = $_site_url.'/'; + } + + Option::update(array('sitename' => Request::post('site_name'), + 'keywords' => Request::post('site_keywords'), + 'description' => Request::post('site_description'), + 'slogan' => Request::post('site_slogan'), + 'defaultpage' => Request::post('site_default_page'), + 'siteurl' => $_site_url, + 'timezone' => Request::post('system_timezone'), + 'language' => Request::post('system_language'), + 'maintenance_message' => Request::post('site_maintenance_message'))); + + Notification::set('success', __('Your changes have been saved.', 'system')); + Request::redirect('index.php?id=system'); + + } else { die('csrf detected!'); } + } + + // Its mean that you can add your own actions for this plugin + Action::run('admin_system_extra_actions'); + + // Display view + View::factory('box/system/views/backend/index') + ->assign('pages_array', $pages_array) + ->assign('languages_array', $languages_array) + ->display(); + + } else { + + Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); } - } \ No newline at end of file + } +} diff --git a/plugins/box/system/system.plugin.php b/plugins/box/system/system.plugin.php index 68d7c72..869cc85 100644 --- a/plugins/box/system/system.plugin.php +++ b/plugins/box/system/system.plugin.php @@ -1,43 +1,37 @@ Session::get('user_login'))), 'top', 'users&action=edit&user_id='.Session::get('user_id'), 1, Navigation::TOP, false); - Navigation::add(__('View site', 'system'), 'top', Option::get('siteurl'), 2, Navigation::TOP, true); - Navigation::add(__('Logout', 'users'), 'top', '&logout=do', 3, Navigation::TOP, false); - - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - Navigation::add(__('Settings', 'system'), 'system', 'system', 1); - } + // Admin top navigation + Navigation::add(__('Welcome, :username', 'system', array(':username' => Session::get('user_login'))), 'top', 'users&action=edit&user_id='.Session::get('user_id'), 1, Navigation::TOP, false); + Navigation::add(__('View site', 'system'), 'top', Option::get('siteurl'), 2, Navigation::TOP, true); + Navigation::add(__('Logout', 'users'), 'top', '&logout=do', 3, Navigation::TOP, false); + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + Navigation::add(__('Settings', 'system'), 'system', 'system', 1); } - - Plugin::Admin('system', 'box'); - \ No newline at end of file +} + +Plugin::Admin('system', 'box'); diff --git a/plugins/box/system/views/backend/index.view.php b/plugins/box/system/views/backend/index.view.php index 204d897..be9d76c 100755 --- a/plugins/box/system/views/backend/index.view.php +++ b/plugins/box/system/views/backend/index.view.php @@ -17,12 +17,12 @@


    - 'input-xxlarge')). Html::br(). + Form::input('site_name', Option::get('sitename'), array('class' => 'input-xxlarge')). Html::br(). Form::label('site_description', __('Site description', 'system')). Form::textarea('site_description', Option::get('description'), array('class' => 'input-xxlarge')). Html::br(). Form::label('site_keywords', __('Site keywords', 'system')). @@ -43,15 +43,15 @@ Form::label('system_timezone', __('Time zone', 'system')). Form::select('system_timezone', Date::timezones(), Option::get('timezone'), array('class' => 'input-xxlarge')). Html::br(). Form::label('system_language', __('Language', 'system')). - Form::select('system_language', $languages_array, Option::get('language'), array('class' => 'input-xlarge')). Html::br(). + Form::select('system_language', $languages_array, Option::get('language'), array('class' => 'input-xlarge')). Html::br(). Form::label('system_admin_email', __('Email', 'system')). Form::input('system_admin_email', Option::get('admin_email'), array('class' => 'input-xlarge')). Html::br(). Form::label('site_maintenance_message', __('Maintenance Mode', 'system')). - Form::textarea('site_maintenance_message', Html::toText(Option::get('maintenance_message')), array('class' => 'input-xxlarge', 'style' => 'height:160px;')). Html::br(2) - ); + Form::textarea('site_maintenance_message', Html::toText(Option::get('maintenance_message')), array('class' => 'input-xxlarge', 'style' => 'height:160px;')). Html::br(2) + ); ?> - 'btn')). Form::close() @@ -60,6 +60,6 @@ diff --git a/plugins/box/themes/install/themes.manifest.xml b/plugins/box/themes/install/themes.manifest.xml index 28d662f..a6f0d80 100644 --- a/plugins/box/themes/install/themes.manifest.xml +++ b/plugins/box/themes/install/themes.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/themes/languages/de.lang.php b/plugins/box/themes/languages/de.lang.php index 2eda62d..f88b350 100644 --- a/plugins/box/themes/languages/de.lang.php +++ b/plugins/box/themes/languages/de.lang.php @@ -1,49 +1,49 @@ - array( - 'Themes' => 'Themes', - 'Themes manager' => 'Themes Manager', - 'Select theme' => 'Wähle Theme', - 'Save' => 'Speichern', - 'Save and exit' => 'Speichern und Schließen', - 'Name' => 'Name', - 'Create new template' => 'Erstelle neues Template', - 'New template' => 'Neues Template', - 'Delete template: :name' => 'Lösche Template: :name', - 'Delete chunk: :name' => 'Lösche Chunk: :name', - 'Delete styles: :name' => 'Lösche Styles: :name', - 'Templates' => 'Templates', - 'Clone' => 'Klonen', - 'Edit' => 'Bearbeiten', - 'Delete' => 'Löschen', - 'Actions' => 'Aktionen', - 'Create new chunk' => 'Erstelle neuen chunk', - 'New chunk' => 'Neuer Chunk', - 'Chunks' => 'Chunks', - 'Create new styles' => 'Erstelle neue Styles', - 'New styles' => 'Neue Styles', - 'Styles' => 'Styles', - 'Template content' => 'Template Inhalt', - 'Styles content' => 'Styles Inhalt', - 'Chunk content' => 'Chunk Inhalt', - 'Edit template' => 'Bearbeite Template', - 'Edit chunk' => 'Bearbeite Chunk', - 'Edit styles' => 'Bearbeite Styles', - 'Current site theme' => 'Aktuelle Seiten Template', - 'Current admin theme' => 'Aktuelles Admin Template', - 'This template already exists' => 'Dieses Template existiert bereits', - 'This chunk already exists' => 'Dieser Chunk exisitert bereits', - 'This styles already exists' => 'Diese Styles existieren bereits', - 'Components templates' => 'Komponenten Templates', - 'Your changes to the chunk :name have been saved.' => 'Deine Änderungen für das Chunk :name wurden gespeichert.', - 'Your changes to the styles :name have been saved.' => 'Deine Änderungen für die Styles :name wurden gespeichert.', - 'Your changes to the template :name have been saved.' => 'Deine Änderungen für das Template :name wurden gespeichert.', - 'This field should not be empty' => 'Dieses Feld darf nicht leer sein.', - 'Scripts' => 'Scripts', - 'Create new script' => 'Erstelle neues Script', - 'Script content' => 'Script Inhalt', - 'New script' => 'Neues Script', - 'Edit script' => 'Bearbeite Script', - ) - ); \ No newline at end of file + array( + 'Themes' => 'Themes', + 'Themes manager' => 'Themes Manager', + 'Select theme' => 'Wähle Theme', + 'Save' => 'Speichern', + 'Save and exit' => 'Speichern und Schließen', + 'Name' => 'Name', + 'Create new template' => 'Erstelle neues Template', + 'New template' => 'Neues Template', + 'Delete template: :name' => 'Lösche Template: :name', + 'Delete chunk: :name' => 'Lösche Chunk: :name', + 'Delete styles: :name' => 'Lösche Styles: :name', + 'Templates' => 'Templates', + 'Clone' => 'Klonen', + 'Edit' => 'Bearbeiten', + 'Delete' => 'Löschen', + 'Actions' => 'Aktionen', + 'Create new chunk' => 'Erstelle neuen chunk', + 'New chunk' => 'Neuer Chunk', + 'Chunks' => 'Chunks', + 'Create new styles' => 'Erstelle neue Styles', + 'New styles' => 'Neue Styles', + 'Styles' => 'Styles', + 'Template content' => 'Template Inhalt', + 'Styles content' => 'Styles Inhalt', + 'Chunk content' => 'Chunk Inhalt', + 'Edit template' => 'Bearbeite Template', + 'Edit chunk' => 'Bearbeite Chunk', + 'Edit styles' => 'Bearbeite Styles', + 'Current site theme' => 'Aktuelle Seiten Template', + 'Current admin theme' => 'Aktuelles Admin Template', + 'This template already exists' => 'Dieses Template existiert bereits', + 'This chunk already exists' => 'Dieser Chunk exisitert bereits', + 'This styles already exists' => 'Diese Styles existieren bereits', + 'Components templates' => 'Komponenten Templates', + 'Your changes to the chunk :name have been saved.' => 'Deine Änderungen für das Chunk :name wurden gespeichert.', + 'Your changes to the styles :name have been saved.' => 'Deine Änderungen für die Styles :name wurden gespeichert.', + 'Your changes to the template :name have been saved.' => 'Deine Änderungen für das Template :name wurden gespeichert.', + 'This field should not be empty' => 'Dieses Feld darf nicht leer sein.', + 'Scripts' => 'Scripts', + 'Create new script' => 'Erstelle neues Script', + 'Script content' => 'Script Inhalt', + 'New script' => 'Neues Script', + 'Edit script' => 'Bearbeite Script', + ) + ); diff --git a/plugins/box/themes/languages/en.lang.php b/plugins/box/themes/languages/en.lang.php index ff7192f..69452fd 100644 --- a/plugins/box/themes/languages/en.lang.php +++ b/plugins/box/themes/languages/en.lang.php @@ -17,7 +17,7 @@ 'Clone' => 'Clone', 'Edit' => 'Edit', 'Delete' => 'Delete', - 'Actions' => 'Actions', + 'Actions' => 'Actions', 'Create new chunk' => 'Create new chunk', 'New chunk' => 'New chunk', 'Chunks' => 'Chunks', @@ -46,4 +46,4 @@ 'New script' => 'New script', 'Edit script' => 'Edit script', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/themes/languages/it.lang.php b/plugins/box/themes/languages/it.lang.php index 353e466..d5f1441 100644 --- a/plugins/box/themes/languages/it.lang.php +++ b/plugins/box/themes/languages/it.lang.php @@ -17,7 +17,7 @@ 'Clone' => 'Duplica', 'Edit' => 'Modifica', 'Delete' => 'Elimina', - 'Actions' => 'Azioni', + 'Actions' => 'Azioni', 'Create new chunk' => 'Crea nuovo chunk', 'New chunk' => 'Nuovo chunk', 'Chunks' => 'Chunks', @@ -48,4 +48,4 @@ 'New script' => 'Nuovo script', 'Edit script' => 'Modifica script', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/themes/languages/lt.lang.php b/plugins/box/themes/languages/lt.lang.php index 8f74691..7d54d5d 100644 --- a/plugins/box/themes/languages/lt.lang.php +++ b/plugins/box/themes/languages/lt.lang.php @@ -17,7 +17,7 @@ 'Clone' => 'Klonuoti', 'Edit' => 'Redaguoti', 'Delete' => 'Ištrinti', - 'Actions' => 'Veiksmai', + 'Actions' => 'Veiksmai', 'Create new chunk' => 'Sukurti naują šablono dalį', 'New chunk' => 'Nauja šablono dalis', 'Chunks' => 'Šablono dalys', @@ -46,4 +46,4 @@ 'New script' => 'Naujas skriptas', 'Edit script' => 'Redaguoti skriptą', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/themes/languages/pt-br.lang.php b/plugins/box/themes/languages/pt-br.lang.php index 9e6cd04..881aff2 100644 --- a/plugins/box/themes/languages/pt-br.lang.php +++ b/plugins/box/themes/languages/pt-br.lang.php @@ -17,7 +17,7 @@ 'Clone' => 'Clonar', 'Edit' => 'Editar', 'Delete' => 'Deletar', - 'Actions' => 'Ações', + 'Actions' => 'Ações', 'Create new chunk' => 'Criar novo pedaço', 'New chunk' => 'Novo pedaço', 'Chunks' => 'Pedaços', @@ -46,4 +46,4 @@ 'New script' => 'Novo script', 'Edit script' => 'Editar script', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/themes/languages/ru.lang.php b/plugins/box/themes/languages/ru.lang.php index 8e0a159..4ead7f9 100644 --- a/plugins/box/themes/languages/ru.lang.php +++ b/plugins/box/themes/languages/ru.lang.php @@ -17,7 +17,7 @@ 'Clone' => 'Клонировать', 'Edit' => 'Редактировать', 'Delete' => 'Удалить', - 'Actions' => 'Действия', + 'Actions' => 'Действия', 'Create new chunk' => 'Создать новый чанк', 'New chunk' => 'Новый чанк', 'Chunks' => 'Чанки', @@ -48,4 +48,4 @@ 'New script' => 'Новый скрипт', 'Edit script' => 'Редактирование скрипта', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/themes/languages/uk.lang.php b/plugins/box/themes/languages/uk.lang.php index c849ce9..e611139 100644 --- a/plugins/box/themes/languages/uk.lang.php +++ b/plugins/box/themes/languages/uk.lang.php @@ -17,7 +17,7 @@ 'Clone' => 'Клонувати', 'Edit' => 'Редагувати', 'Delete' => 'Видалити', - 'Actions' => 'Дії', + 'Actions' => 'Дії', 'Create new chunk' => 'Створити новий чанк', 'New chunk' => 'Новый чанк', 'Chunks' => 'Чанки', @@ -48,4 +48,4 @@ 'New script' => 'Новий скрипт', 'Edit script' => 'Редагування скрипту', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/themes/themes.admin.php b/plugins/box/themes/themes.admin.php index 564102f..6a364cb 100755 --- a/plugins/box/themes/themes.admin.php +++ b/plugins/box/themes/themes.admin.php @@ -1,592 +1,587 @@ 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); - if (Security::check(Request::post('csrf'))) { - - Option::update('theme_site_name', Request::post('themes')); + Request::redirect('index.php?id=themes'); - // Cleanup minify - if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + } else { die('csrf detected!'); } + } - Request::redirect('index.php?id=themes'); + // Save site theme + if (Request::post('save_admin_theme')) { - } else { die('csrf detected!'); } - } + if (Security::check(Request::post('csrf'))) { - // Save site theme - if (Request::post('save_admin_theme')) { + Option::update('theme_admin_name', Request::post('themes')); - if (Security::check(Request::post('csrf'))) { - - Option::update('theme_admin_name', Request::post('themes')); + // Cleanup minify + if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); - // Cleanup minify - if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file); + Request::redirect('index.php?id=themes'); - Request::redirect('index.php?id=themes'); + } else { die('csrf detected!'); } + } - } else { die('csrf detected!'); } - } + // Its mean that you can add your own actions for this plugin + Action::run('admin_themes_extra_actions'); - // Its mean that you can add your own actions for this plugin - Action::run('admin_themes_extra_actions'); + // Check for get actions + // ------------------------------------- + if (Request::get('action')) { - // Check for get actions - // ------------------------------------- - if (Request::get('action')) { + // Switch actions + // ------------------------------------- + switch (Request::get('action')) { - // Switch actions - // ------------------------------------- - switch (Request::get('action')) { + // Add chunk + // ------------------------------------- + case "add_chunk": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { - // Add chunk - // ------------------------------------- - case "add_chunk": - if (Request::post('add_file') || Request::post('add_file_and_exit')) { + if (Security::check(Request::post('csrf'))) { - if (Security::check(Request::post('csrf'))) { - - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if (file_exists($chunk_path.Security::safeName(Request::post('name')).'.chunk.php')) $errors['file_exists'] = __('This chunk already exists', 'themes'); + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($chunk_path.Security::safeName(Request::post('name')).'.chunk.php')) $errors['file_exists'] = __('This chunk already exists', 'themes'); - if (count($errors) == 0) { - - // Save chunk - File::setContent($chunk_path.Security::safeName(Request::post('name')).'.chunk.php', Request::post('content')); - - Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + if (count($errors) == 0) { - if (Request::post('add_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_chunk&filename='.Security::safeName(Request::post('name'))); - } + // Save chunk + File::setContent($chunk_path.Security::safeName(Request::post('name')).'.chunk.php', Request::post('content')); + + Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_chunk&filename='.Security::safeName(Request::post('name'))); } + } - } else { die('csrf detected!'); } - } + } else { die('csrf detected!'); } + } - // Save fields - if (Request::post('name')) $name = Request::post('name'); else $name = ''; - if (Request::post('content')) $content = Request::post('content'); else $content = ''; + // Save fields + if (Request::post('name')) $name = Request::post('name'); else $name = ''; + if (Request::post('content')) $content = Request::post('content'); else $content = ''; - // Display view - View::factory('box/themes/views/backend/add') - ->assign('name', $name) - ->assign('content', $content) - ->assign('errors', $errors) - ->assign('action', 'chunk') - ->display(); - break; + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'chunk') + ->display(); + break; - // Add template - // ------------------------------------- - case "add_template": - if (Request::post('add_file') || Request::post('add_file_and_exit')) { + // Add template + // ------------------------------------- + case "add_template": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { - if (Security::check(Request::post('csrf'))) { - - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if (file_exists($template_path.Security::safeName(Request::post('name')).'.template.php')) $errors['file_exists'] = __('This template already exists', 'themes'); + if (Security::check(Request::post('csrf'))) { - if (count($errors) == 0) { - - // Save chunk - File::setContent($template_path.Security::safeName(Request::post('name')).'.template.php', Request::post('content')); - - Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($template_path.Security::safeName(Request::post('name')).'.template.php')) $errors['file_exists'] = __('This template already exists', 'themes'); - if (Request::post('add_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_template&filename='.Security::safeName(Request::post('name'))); - } + if (count($errors) == 0) { + + // Save chunk + File::setContent($template_path.Security::safeName(Request::post('name')).'.template.php', Request::post('content')); + + Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_template&filename='.Security::safeName(Request::post('name'))); } + } - } else { die('csrf detected!'); } - } + } else { die('csrf detected!'); } + } - // Save fields - if (Request::post('name')) $name = Request::post('name'); else $name = ''; - if (Request::post('content')) $content = Request::post('content'); else $content = ''; + // Save fields + if (Request::post('name')) $name = Request::post('name'); else $name = ''; + if (Request::post('content')) $content = Request::post('content'); else $content = ''; - // Display view - View::factory('box/themes/views/backend/add') - ->assign('name', $name) - ->assign('content', $content) - ->assign('errors', $errors) - ->assign('action', 'template') - ->display(); - break; + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'template') + ->display(); + break; - // Add styles - // ------------------------------------- - case "add_styles": - if (Request::post('add_file') || Request::post('add_file_and_exit')) { - - if (Security::check(Request::post('csrf'))) { + // Add styles + // ------------------------------------- + case "add_styles": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if (file_exists($style_path.Security::safeName(Request::post('name')).'.css')) $errors['file_exists'] = __('This styles already exists', 'themes'); + if (Security::check(Request::post('csrf'))) { - if (count($errors) == 0) { - - // Save chunk - File::setContent($style_path.Security::safeName(Request::post('name')).'.css', Request::post('content')); - - Notification::set('success', __('Your changes to the styles :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($style_path.Security::safeName(Request::post('name')).'.css')) $errors['file_exists'] = __('This styles already exists', 'themes'); - if (Request::post('add_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_styles&filename='.Security::safeName(Request::post('name'))); - } + if (count($errors) == 0) { + + // Save chunk + File::setContent($style_path.Security::safeName(Request::post('name')).'.css', Request::post('content')); + + Notification::set('success', __('Your changes to the styles :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_styles&filename='.Security::safeName(Request::post('name'))); } + } - } else { die('csrf detected!'); } - } + } else { die('csrf detected!'); } + } - // Save fields - if (Request::post('name')) $name = Request::post('name'); else $name = ''; - if (Request::post('content')) $content = Request::post('content'); else $content = ''; + // Save fields + if (Request::post('name')) $name = Request::post('name'); else $name = ''; + if (Request::post('content')) $content = Request::post('content'); else $content = ''; - // Display view - View::factory('box/themes/views/backend/add') - ->assign('name', $name) - ->assign('content', $content) - ->assign('errors', $errors) - ->assign('action', 'styles') - ->display(); - break; + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'styles') + ->display(); + break; - // Add script - // ------------------------------------- - case "add_script": - if (Request::post('add_file') || Request::post('add_file_and_exit')) { - - if (Security::check(Request::post('csrf'))) { + // Add script + // ------------------------------------- + case "add_script": + if (Request::post('add_file') || Request::post('add_file_and_exit')) { - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if (file_exists($script_path.Security::safeName(Request::post('name')).'.js')) $errors['file_exists'] = __('This script already exists', 'themes'); + if (Security::check(Request::post('csrf'))) { - if (count($errors) == 0) { - - // Save chunk - File::setContent($script_path.Security::safeName(Request::post('name')).'.js', Request::post('content')); - - Notification::set('success', __('Your changes to the script :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if (file_exists($script_path.Security::safeName(Request::post('name')).'.js')) $errors['file_exists'] = __('This script already exists', 'themes'); - if (Request::post('add_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_script&filename='.Security::safeName(Request::post('name'))); - } + if (count($errors) == 0) { + + // Save chunk + File::setContent($script_path.Security::safeName(Request::post('name')).'.js', Request::post('content')); + + Notification::set('success', __('Your changes to the script :name have been saved.', 'themes', array(':name' => Security::safeName(Request::post('name'))))); + + if (Request::post('add_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_script&filename='.Security::safeName(Request::post('name'))); } + } - } else { die('csrf detected!'); } - } + } else { die('csrf detected!'); } + } - // Save fields - if (Request::post('name')) $name = Request::post('name'); else $name = ''; - if (Request::post('content')) $content = Request::post('content'); else $content = ''; + // Save fields + if (Request::post('name')) $name = Request::post('name'); else $name = ''; + if (Request::post('content')) $content = Request::post('content'); else $content = ''; - // Display view - View::factory('box/themes/views/backend/add') - ->assign('name', $name) - ->assign('content', $content) - ->assign('errors', $errors) - ->assign('action', 'script') - ->display(); - break; + // Display view + View::factory('box/themes/views/backend/add') + ->assign('name', $name) + ->assign('content', $content) + ->assign('errors', $errors) + ->assign('action', 'script') + ->display(); + break; + // Edit chunk + // ------------------------------------- + case "edit_chunk": - // Edit chunk - // ------------------------------------- - case "edit_chunk": + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { - // Save current chunk action - if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + if (Security::check(Request::post('csrf'))) { - if (Security::check(Request::post('csrf'))) { + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($chunk_path.Security::safeName(Request::post('name')).'.chunk.php')) and (Security::safeName(Request::post('chunk_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This chunk already exists', 'themes'); - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if ((file_exists($chunk_path.Security::safeName(Request::post('name')).'.chunk.php')) and (Security::safeName(Request::post('chunk_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This chunk already exists', 'themes'); + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { - // Save fields - if (Request::post('content')) $content = Request::post('content'); else $content = ''; - if (count($errors) == 0) { - - $chunk_old_filename = $chunk_path.Request::post('chunk_old_name').'.chunk.php'; - $chunk_new_filename = $chunk_path.Security::safeName(Request::post('name')).'.chunk.php'; - if ( ! empty($chunk_old_filename)) { - if ($chunk_old_filename !== $chunk_new_filename) { - rename($chunk_old_filename, $chunk_new_filename); - $save_filename = $chunk_new_filename; - } else { - $save_filename = $chunk_new_filename; - } + $chunk_old_filename = $chunk_path.Request::post('chunk_old_name').'.chunk.php'; + $chunk_new_filename = $chunk_path.Security::safeName(Request::post('name')).'.chunk.php'; + if ( ! empty($chunk_old_filename)) { + if ($chunk_old_filename !== $chunk_new_filename) { + rename($chunk_old_filename, $chunk_new_filename); + $save_filename = $chunk_new_filename; } else { $save_filename = $chunk_new_filename; } + } else { + $save_filename = $chunk_new_filename; + } - // Save chunk - File::setContent($save_filename, Request::post('content')); + // Save chunk + File::setContent($save_filename, Request::post('content')); - Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => basename($save_filename, '.chunk.php')))); + Notification::set('success', __('Your changes to the chunk :name have been saved.', 'themes', array(':name' => basename($save_filename, '.chunk.php')))); - if (Request::post('edit_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_chunk&filename='.Security::safeName(Request::post('name'))); - } - } + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_chunk&filename='.Security::safeName(Request::post('name'))); + } + } - } else { die('csrf detected!'); } - } - if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); - $content = File::getContent($chunk_path.Request::get('filename').'.chunk.php'); - - // Display view - View::factory('box/themes/views/backend/edit') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->assign('action', 'chunk') - ->display(); - - break; + } else { die('csrf detected!'); } + } + if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); + $content = File::getContent($chunk_path.Request::get('filename').'.chunk.php'); - // Edit template - // ------------------------------------- - case "edit_template": + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'chunk') + ->display(); - // Save current chunk action - if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + break; - if (Security::check(Request::post('csrf'))) { + // Edit template + // ------------------------------------- + case "edit_template": - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if ((file_exists($template_path.Security::safeName(Request::post('name')).'.template.php')) and (Security::safeName(Request::post('template_old_name')) !== Security::safeName(Request::post('name')))) $errors['template_exists'] = __('This template already exists', 'themes'); + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { - // Save fields - if (Request::post('content')) $content = Request::post('content'); else $content = ''; - if (count($errors) == 0) { + if (Security::check(Request::post('csrf'))) { - $template_old_filename = $template_path.Request::post('template_old_name').'.template.php'; - $template_new_filename = $template_path.Security::safeName(Request::post('name')).'.template.php'; - if ( ! empty($template_old_filename)) { - if ($template_old_filename !== $template_new_filename) { - rename($template_old_filename, $template_new_filename); - $save_filename = $template_new_filename; - } else { - $save_filename = $template_new_filename; - } + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($template_path.Security::safeName(Request::post('name')).'.template.php')) and (Security::safeName(Request::post('template_old_name')) !== Security::safeName(Request::post('name')))) $errors['template_exists'] = __('This template already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $template_old_filename = $template_path.Request::post('template_old_name').'.template.php'; + $template_new_filename = $template_path.Security::safeName(Request::post('name')).'.template.php'; + if ( ! empty($template_old_filename)) { + if ($template_old_filename !== $template_new_filename) { + rename($template_old_filename, $template_new_filename); + $save_filename = $template_new_filename; } else { $save_filename = $template_new_filename; } + } else { + $save_filename = $template_new_filename; + } - // Save chunk - File::setContent($save_filename, Request::post('content')); + // Save chunk + File::setContent($save_filename, Request::post('content')); - Notification::set('success', __('Your changes to the template :name have been saved.', 'themes', array(':name' => basename($save_filename, '.template.php')))); + Notification::set('success', __('Your changes to the template :name have been saved.', 'themes', array(':name' => basename($save_filename, '.template.php')))); - if (Request::post('edit_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_template&filename='.Security::safeName(Request::post('name'))); - } - } + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_template&filename='.Security::safeName(Request::post('name'))); + } + } - } else { die('csrf detected!'); } - } - if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); - $content = File::getContent($chunk_path.Request::get('filename').'.template.php'); - - // Display view - View::factory('box/themes/views/backend/edit') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->assign('action', 'template') - ->display(); - - break; + } else { die('csrf detected!'); } + } + if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); + $content = File::getContent($chunk_path.Request::get('filename').'.template.php'); - // Edit styles - // ------------------------------------- - case "edit_styles": + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'template') + ->display(); - // Save current chunk action - if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + break; - if (Security::check(Request::post('csrf'))) { + // Edit styles + // ------------------------------------- + case "edit_styles": - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if ((file_exists($style_path.Security::safeName(Request::post('name')).'.css')) and (Security::safeName(Request::post('styles_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This styles already exists', 'themes'); + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { - // Save fields - if (Request::post('content')) $content = Request::post('content'); else $content = ''; - if (count($errors) == 0) { + if (Security::check(Request::post('csrf'))) { - $styles_old_filename = $style_path.Request::post('styles_old_name').'.css'; - $styles_new_filename = $style_path.Security::safeName(Request::post('name')).'.css'; - if ( ! empty($styles_old_filename)) { - if ($styles_old_filename !== $styles_new_filename) { - rename($styles_old_filename, $styles_new_filename); - $save_filename = $styles_new_filename; - } else { - $save_filename = $styles_new_filename; - } + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($style_path.Security::safeName(Request::post('name')).'.css')) and (Security::safeName(Request::post('styles_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This styles already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $styles_old_filename = $style_path.Request::post('styles_old_name').'.css'; + $styles_new_filename = $style_path.Security::safeName(Request::post('name')).'.css'; + if ( ! empty($styles_old_filename)) { + if ($styles_old_filename !== $styles_new_filename) { + rename($styles_old_filename, $styles_new_filename); + $save_filename = $styles_new_filename; } else { $save_filename = $styles_new_filename; } + } else { + $save_filename = $styles_new_filename; + } - // Save chunk - File::setContent($save_filename, Request::post('content')); + // Save chunk + File::setContent($save_filename, Request::post('content')); - Notification::set('success', __('Your changes to the styles :name have been saved.', 'themes', array(':name' => basename($save_filename, '.css')))); + Notification::set('success', __('Your changes to the styles :name have been saved.', 'themes', array(':name' => basename($save_filename, '.css')))); - if (Request::post('edit_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_styles&filename='.Security::safeName(Request::post('name'))); - } - } + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_styles&filename='.Security::safeName(Request::post('name'))); + } + } - } else { die('csrf detected!'); } - } - if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); - $content = File::getContent($style_path.Request::get('filename').'.css'); - - // Display view - View::factory('box/themes/views/backend/edit') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->assign('action', 'styles') - ->display(); - - break; - - - // Edit script - // ------------------------------------- - case "edit_script": + } else { die('csrf detected!'); } + } + if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); + $content = File::getContent($style_path.Request::get('filename').'.css'); - // Save current chunk action - if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'styles') + ->display(); - if (Security::check(Request::post('csrf'))) { + break; - if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); - if ((file_exists($script_path.Security::safeName(Request::post('name')).'.js')) and (Security::safeName(Request::post('script_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This script already exists', 'themes'); + // Edit script + // ------------------------------------- + case "edit_script": - // Save fields - if (Request::post('content')) $content = Request::post('content'); else $content = ''; - if (count($errors) == 0) { + // Save current chunk action + if (Request::post('edit_file') || Request::post('edit_file_and_exit') ) { - $script_old_filename = $script_path.Request::post('script_old_name').'.js'; - $script_new_filename = $script_path.Security::safeName(Request::post('name')).'.js'; - if ( ! empty($script_old_filename)) { - if ($script_old_filename !== $script_new_filename) { - rename($script_old_filename, $script_new_filename); - $save_filename = $script_new_filename; - } else { - $save_filename = $script_new_filename; - } + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('name')) == '') $errors['file_empty_name'] = __('Required field', 'themes'); + if ((file_exists($script_path.Security::safeName(Request::post('name')).'.js')) and (Security::safeName(Request::post('script_old_name')) !== Security::safeName(Request::post('name')))) $errors['file_exists'] = __('This script already exists', 'themes'); + + // Save fields + if (Request::post('content')) $content = Request::post('content'); else $content = ''; + if (count($errors) == 0) { + + $script_old_filename = $script_path.Request::post('script_old_name').'.js'; + $script_new_filename = $script_path.Security::safeName(Request::post('name')).'.js'; + if ( ! empty($script_old_filename)) { + if ($script_old_filename !== $script_new_filename) { + rename($script_old_filename, $script_new_filename); + $save_filename = $script_new_filename; } else { $save_filename = $script_new_filename; } + } else { + $save_filename = $script_new_filename; + } - // Save chunk - File::setContent($save_filename, Request::post('content')); + // Save chunk + File::setContent($save_filename, Request::post('content')); - Notification::set('success', __('Your changes to the script :name have been saved.', 'themes', array(':name' => basename($save_filename, '.js')))); + Notification::set('success', __('Your changes to the script :name have been saved.', 'themes', array(':name' => basename($save_filename, '.js')))); - if (Request::post('edit_file_and_exit')) { - Request::redirect('index.php?id=themes'); - } else { - Request::redirect('index.php?id=themes&action=edit_script&filename='.Security::safeName(Request::post('name'))); - } - } + if (Request::post('edit_file_and_exit')) { + Request::redirect('index.php?id=themes'); + } else { + Request::redirect('index.php?id=themes&action=edit_script&filename='.Security::safeName(Request::post('name'))); + } + } - } else { die('csrf detected!'); } - } - if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); - $content = File::getContent($script_path.Request::get('filename').'.js'); - - // Display view - View::factory('box/themes/views/backend/edit') - ->assign('content', $content) - ->assign('name', $name) - ->assign('errors', $errors) - ->assign('action', 'script') - ->display(); - - break; + } else { die('csrf detected!'); } + } + if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename')); + $content = File::getContent($script_path.Request::get('filename').'.js'); - // Delete chunk - // ------------------------------------- - case "delete_chunk": + // Display view + View::factory('box/themes/views/backend/edit') + ->assign('content', $content) + ->assign('name', $name) + ->assign('errors', $errors) + ->assign('action', 'script') + ->display(); - if (Security::check(Request::get('token'))) { + break; - File::delete($chunk_path.Request::get('filename').'.chunk.php'); - Notification::set('success', __('Chunk :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); - Request::redirect('index.php?id=themes'); + // Delete chunk + // ------------------------------------- + case "delete_chunk": - } else { die('csrf detected!'); } + if (Security::check(Request::get('token'))) { - break; + File::delete($chunk_path.Request::get('filename').'.chunk.php'); + Notification::set('success', __('Chunk :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); + } else { die('csrf detected!'); } - // Delete styles - // ------------------------------------- - case "delete_styles": + break; - if (Security::check(Request::get('token'))) { + // Delete styles + // ------------------------------------- + case "delete_styles": - File::delete($style_path.Request::get('filename').'.css'); - Notification::set('success', __('Styles :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); - Request::redirect('index.php?id=themes'); + if (Security::check(Request::get('token'))) { - } else { die('csrf detected!'); } + File::delete($style_path.Request::get('filename').'.css'); + Notification::set('success', __('Styles :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); - break; - - // Delete script - // ------------------------------------- - case "delete_script": - - if (Security::check(Request::get('token'))) { + } else { die('csrf detected!'); } - File::delete($script_path.Request::get('filename').'.js'); - Notification::set('success', __('Script :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); - Request::redirect('index.php?id=themes'); + break; - } else { die('csrf detected!'); } + // Delete script + // ------------------------------------- + case "delete_script": - break; + if (Security::check(Request::get('token'))) { - // Delete template - // ------------------------------------- - case "delete_template": - - if (Security::check(Request::get('token'))) { + File::delete($script_path.Request::get('filename').'.js'); + Notification::set('success', __('Script :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); - File::delete($template_path.Request::get('filename').'.template.php'); - Notification::set('success', __('Template :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); - Request::redirect('index.php?id=themes'); - } + } else { die('csrf detected!'); } - break; + break; - // Clone styles - // ------------------------------------- - case "clone_styles": + // Delete template + // ------------------------------------- + case "delete_template": - if (Security::check(Request::get('token'))) { + if (Security::check(Request::get('token'))) { - File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.css', - File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') . '.css')); - - Request::redirect('index.php?id=themes'); - } + File::delete($template_path.Request::get('filename').'.template.php'); + Notification::set('success', __('Template :name deleted', 'themes', array(':name' => File::name(Request::get('filename'))))); + Request::redirect('index.php?id=themes'); + } - break; + break; - // Clone script - // ------------------------------------- - case "clone_script": - - if (Security::check(Request::get('token'))) { + // Clone styles + // ------------------------------------- + case "clone_styles": - File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.js', - File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') . '.js')); - - Request::redirect('index.php?id=themes'); - } + if (Security::check(Request::get('token'))) { - break; + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.css', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'css' . DS . Request::get('filename') . '.css')); - // Clone template - // ------------------------------------- - case "clone_template": + Request::redirect('index.php?id=themes'); + } - if (Security::check(Request::get('token'))) { + break; - File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.template.php', - File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.template.php')); - - Request::redirect('index.php?id=themes'); + // Clone script + // ------------------------------------- + case "clone_script": - } + if (Security::check(Request::get('token'))) { - break; + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.js', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . 'js' . DS . Request::get('filename') . '.js')); - // Clone chunk - // ------------------------------------- - case "clone_chunk": + Request::redirect('index.php?id=themes'); + } - if (Security::check(Request::get('token'))) { - File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.chunk.php', - File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.chunk.php')); - - Request::redirect('index.php?id=themes'); - } - - break; - - } - - } else { - - // Display view - View::factory('box/themes/views/backend/index') - ->assign('themes_site', $themes_site) - ->assign('themes_admin', $themes_admin) - ->assign('templates', $templates) - ->assign('chunks', $chunks) - ->assign('styles', $styles) - ->assign('scripts', $scripts) - ->assign('current_site_theme', $current_site_theme) - ->assign('current_admin_theme', $current_admin_theme) - ->display(); + break; + + // Clone template + // ------------------------------------- + case "clone_template": + + if (Security::check(Request::get('token'))) { + + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.template.php', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.template.php')); + + Request::redirect('index.php?id=themes'); + + } + + break; + + // Clone chunk + // ------------------------------------- + case "clone_chunk": + + if (Security::check(Request::get('token'))) { + File::setContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') .'_clone_'.date("Ymd_His").'.chunk.php', + File::getContent(THEMES_SITE . DS . $current_site_theme . DS . Request::get('filename') . '.chunk.php')); + + Request::redirect('index.php?id=themes'); + } + + break; } + + } else { + + // Display view + View::factory('box/themes/views/backend/index') + ->assign('themes_site', $themes_site) + ->assign('themes_admin', $themes_admin) + ->assign('templates', $templates) + ->assign('chunks', $chunks) + ->assign('styles', $styles) + ->assign('scripts', $scripts) + ->assign('current_site_theme', $current_site_theme) + ->assign('current_admin_theme', $current_admin_theme) + ->display(); + } } +} diff --git a/plugins/box/themes/themes.plugin.php b/plugins/box/themes/themes.plugin.php index 7ad30b8..5005449 100644 --- a/plugins/box/themes/themes.plugin.php +++ b/plugins/box/themes/themes.plugin.php @@ -1,199 +1,191 @@ filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php')) { - file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php', - Minify::html(file_get_contents(THEMES_SITE. DS . $current_theme . DS . $name .'.chunk.php'))); - } + /** + * Get Styles + * + * @param string $theme Theme name + * @return mixed + */ + public static function getStyles($theme = null) + { + $theme = ($theme === null) ? null : (string) $theme; - // Include chunk - include MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php'; + if ($theme == null) $theme = Option::get('theme_site_name'); + + $styles = array(); + + // Get all templates in current theme folder + $styles = File::scan(THEMES_SITE . DS . $theme . DS . 'css', '.css'); + + return ($styles) ? $styles : array(); + } + + /** + * Get Scripts + * + * @param string $theme Theme name + * @return mixed + */ + public static function getScripts($theme = null) + { + $theme = ($theme === null) ? null : (string) $theme; + + if ($theme == null) $theme = Option::get('theme_site_name'); + + $scripts = array(); + + // Get all templates in current theme folder + $scripts = File::scan(THEMES_SITE . DS . $theme . DS . 'js' . DS , '.js'); + + return ($scripts) ? $scripts : array(); + } + +} + +/** + * Chunk class + */ +class Chunk +{ + /** + * Get chunk + * + * @param string $name Chunk name + * @param string $theme Theme name + */ + public static function get($name, $vars = array(), $theme = null) + { + // Redefine vars + $name = (string) $name; + $current_theme = ($theme === null) ? Option::get('theme_site_name') : (string) $theme; + + // Extract vars + extract($vars); + + // Chunk path + $chunk_path = THEMES_SITE . DS . $current_theme . DS; + + // Is chunk exist ? + if (file_exists($chunk_path . $name . '.chunk.php')) { + + // Is chunk minified + if ( ! file_exists(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php') or + filemtime(THEMES_SITE . DS . $current_theme . DS . $name .'.chunk.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php')) { + file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php', + Minify::html(file_get_contents(THEMES_SITE. DS . $current_theme . DS . $name .'.chunk.php'))); } + // Include chunk + include MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $name . '.chunk.php'; } - } \ No newline at end of file + } + +} diff --git a/plugins/box/themes/views/backend/add.view.php b/plugins/box/themes/views/backend/add.view.php index 0207062..254d572 100644 --- a/plugins/box/themes/views/backend/add.view.php +++ b/plugins/box/themes/views/backend/add.view.php @@ -1,7 +1,7 @@

    -

    -

    +

    +


    @@ -18,8 +18,8 @@ (isset($errors['file_empty_name']) || isset($errors['file_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?> .chunk.php .template.php - .css - .js + .css + .js
    'width:100%;height:400px;', 'class' => 'source-editor')); echo ( @@ -44,4 +44,3 @@ Form::submit('add_file', __('Save', 'themes'), array('class' => 'btn')). Form::close() ); -?> \ No newline at end of file diff --git a/plugins/box/themes/views/backend/edit.view.php b/plugins/box/themes/views/backend/edit.view.php index 28df5a9..fe6ffa7 100644 --- a/plugins/box/themes/views/backend/edit.view.php +++ b/plugins/box/themes/views/backend/edit.view.php @@ -1,13 +1,13 @@

    -

    +


    - - - + + @@ -28,8 +27,8 @@ (isset($errors['file_empty_name']) || isset($errors['file_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?> .chunk.php .template.php - .css - .js + .css + .js 'width:100%;height:400px;', 'class' => 'source-editor')). Html::br(2). @@ -53,11 +52,10 @@ Form::submit('edit_file', __('Save', 'themes'), array('class' => 'btn')). Html::nbsp(). Form::close() ); - + } else { if ($action == 'chunk') { echo '
    '.__('This chunk does not exist', 'themes').'
    '; } if ($action == 'template') { echo '
    '.__('This template does not exist', 'themes').'
    '; } if ($action == 'styles') { echo '
    '.__('This styles does not exist', 'themes').'
    '; } if ($action == 'script') { echo '
    '.__('This script does not exist', 'themes').'
    '; } } -?> \ No newline at end of file diff --git a/plugins/box/themes/views/backend/index.view.php b/plugins/box/themes/views/backend/index.view.php index 087e3b3..665cec9 100755 --- a/plugins/box/themes/views/backend/index.view.php +++ b/plugins/box/themes/views/backend/index.view.php @@ -20,7 +20,6 @@ -

    @@ -49,13 +48,12 @@
    - - __('Create new template'), 'class' => 'btn btn-small')).Html::br(2)); ?> @@ -69,15 +67,15 @@ - - + +
    'btn btn-small')); ?> + 'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete template: :name', 'themes', array(':name' => basename($template, '.template.php')))."')")); @@ -104,15 +102,15 @@ - - + +
    'btn btn-small')); ?> + 'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete chunk: :name', 'themes', array(':name' => basename($chunk, '.chunk.php')))."')")); @@ -139,15 +137,15 @@ - - + +
    'btn btn-small')); ?> + 'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete styles: :name', 'themes', array(':name' => basename($style, '.css')))."')")); @@ -174,15 +172,15 @@ - - + +
    'btn btn-small')); ?> + 'btn btn-actions btn-small btn-actions-default', 'onclick' => "return confirmDelete('".__('Delete script: :name', 'themes', array(':name' => basename($script, '.js')))."')")); @@ -196,9 +194,8 @@ - - 3) { + 3) { ?>


    3) { ?>
    -
    \ No newline at end of file +
    diff --git a/plugins/box/users/install/users.manifest.xml b/plugins/box/users/install/users.manifest.xml index 7c7bcff..90808b9 100644 --- a/plugins/box/users/install/users.manifest.xml +++ b/plugins/box/users/install/users.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/box/users/languages/de.lang.php b/plugins/box/users/languages/de.lang.php index a7ecb71..a0041e7 100644 --- a/plugins/box/users/languages/de.lang.php +++ b/plugins/box/users/languages/de.lang.php @@ -1,67 +1,67 @@ - array( - 'Users' => 'Benutzer', - 'Login' => 'Login', - 'Username' => 'Benutzername', - 'Password' => 'Passwort', - 'Registered' => 'Registriert', - 'Email' => 'Email', - 'Role' => 'Rolle', - 'Roles' => 'Rollen', - 'Edit' => 'Bearbeiten', - 'Actions' => 'Aktionen', - 'Delete' => 'Löschen', - 'Enter' => 'Eintragen', - 'Logout' => 'Ausloggen', - 'Register new user' => 'Registriere neuen Benutzer', - 'New User Registration' => 'Neuen Benutzer registrieren', - 'Delete user: :user' => 'Lösche Benutzer: :user', - 'User :user have been deleted.' => 'Benutzer :user wurde gelöscht.', - 'This field should not be empty' => 'Dieses Feld darf nicht leer sein', - 'This user alredy exist' => 'Dieser Benutzer existiert bereits', - 'Changes saved' => 'Änderungen gespeichert', - 'Wrong old password' => 'Altes Passwort falsch', - 'Admin' => 'Admin', - 'User' => 'Benutzer', - 'Editor' => 'Redakteur', - 'Register' => 'Registrieren', - 'Edit profile' => 'Profil bearbeiten', - 'Save' => 'Speichern', - 'Firstname' => 'Vorname', - 'Lastname' => 'Nachname', - 'Old password' => 'Altes Passwort', - 'New password' => 'Neues Passwort', - 'Welcome' => 'Willkommen', - 'Wrong username or password' => 'Falscher Benutzername oder Passwort', - 'Your changes have been saved.' => 'Deine Änderungen wurden gespeichert.', - 'New user have been registered.' => 'Neuer Benutzer wurde registriert.', - 'Captcha' => 'Captcha', - 'Registration' => 'Registrierung', - 'Username' => 'Benutzername', - 'User email is invalid' => 'Benutzer Email ist nicht gültig', - 'Reset Password' => 'Passwort zurücksetzen', - 'Send New Password' => 'Neues Passwort zusenden', - 'This user doesnt alredy exist' => 'Dieser Benutzer ist nocht nicht vorhanden', - 'Users - Profile' => 'Benutzer - Profil', - 'Users - Edit Profile' => 'Benutzer - Profil Bearbeiten', - 'Users - Login' => 'Benutzer - Login', - 'Users - Registration' => 'Benutzer - Registration', - 'Users - Password Recover' => 'Benutzer - Passwort wiederherstellen', - 'New Password' => 'Neues Passwort', - 'Forgot your password?' => 'Passwort vergessen?', - 'New password has been sent' => 'Neues Passwort wurde versendet', - 'Monstra says: This is not your profile...' => 'Monstra sagt: Das ist nicht dein Profil...', - 'User registration is closed.' => 'Benutzer Registration ist geschloßen.', - 'Allow user registration' => 'Erlaube Benutzer Registration', - 'Required field' => 'Pflichtfeld', - 'This user doesnt exist' => 'Dieser Benutzer existiert nicht', - 'Captcha code is wrong' => 'Captcha Code ist falsch', - 'Your login details for :site_name has been sent' => 'Deine Login-Daten für :site_name wurden versendet', - 'Your new password for :site_name' => 'Dein neues Passwort für :site_name', - 'Your login details for :site_name' => 'Deine Login-Daten für :site_name', - 'About Me' => 'Über Mich', - 'Profile' => 'Profil', - ) - ); \ No newline at end of file + array( + 'Users' => 'Benutzer', + 'Login' => 'Login', + 'Username' => 'Benutzername', + 'Password' => 'Passwort', + 'Registered' => 'Registriert', + 'Email' => 'Email', + 'Role' => 'Rolle', + 'Roles' => 'Rollen', + 'Edit' => 'Bearbeiten', + 'Actions' => 'Aktionen', + 'Delete' => 'Löschen', + 'Enter' => 'Eintragen', + 'Logout' => 'Ausloggen', + 'Register new user' => 'Registriere neuen Benutzer', + 'New User Registration' => 'Neuen Benutzer registrieren', + 'Delete user: :user' => 'Lösche Benutzer: :user', + 'User :user have been deleted.' => 'Benutzer :user wurde gelöscht.', + 'This field should not be empty' => 'Dieses Feld darf nicht leer sein', + 'This user alredy exist' => 'Dieser Benutzer existiert bereits', + 'Changes saved' => 'Änderungen gespeichert', + 'Wrong old password' => 'Altes Passwort falsch', + 'Admin' => 'Admin', + 'User' => 'Benutzer', + 'Editor' => 'Redakteur', + 'Register' => 'Registrieren', + 'Edit profile' => 'Profil bearbeiten', + 'Save' => 'Speichern', + 'Firstname' => 'Vorname', + 'Lastname' => 'Nachname', + 'Old password' => 'Altes Passwort', + 'New password' => 'Neues Passwort', + 'Welcome' => 'Willkommen', + 'Wrong username or password' => 'Falscher Benutzername oder Passwort', + 'Your changes have been saved.' => 'Deine Änderungen wurden gespeichert.', + 'New user have been registered.' => 'Neuer Benutzer wurde registriert.', + 'Captcha' => 'Captcha', + 'Registration' => 'Registrierung', + 'Username' => 'Benutzername', + 'User email is invalid' => 'Benutzer Email ist nicht gültig', + 'Reset Password' => 'Passwort zurücksetzen', + 'Send New Password' => 'Neues Passwort zusenden', + 'This user doesnt alredy exist' => 'Dieser Benutzer ist nocht nicht vorhanden', + 'Users - Profile' => 'Benutzer - Profil', + 'Users - Edit Profile' => 'Benutzer - Profil Bearbeiten', + 'Users - Login' => 'Benutzer - Login', + 'Users - Registration' => 'Benutzer - Registration', + 'Users - Password Recover' => 'Benutzer - Passwort wiederherstellen', + 'New Password' => 'Neues Passwort', + 'Forgot your password?' => 'Passwort vergessen?', + 'New password has been sent' => 'Neues Passwort wurde versendet', + 'Monstra says: This is not your profile...' => 'Monstra sagt: Das ist nicht dein Profil...', + 'User registration is closed.' => 'Benutzer Registration ist geschloßen.', + 'Allow user registration' => 'Erlaube Benutzer Registration', + 'Required field' => 'Pflichtfeld', + 'This user doesnt exist' => 'Dieser Benutzer existiert nicht', + 'Captcha code is wrong' => 'Captcha Code ist falsch', + 'Your login details for :site_name has been sent' => 'Deine Login-Daten für :site_name wurden versendet', + 'Your new password for :site_name' => 'Dein neues Passwort für :site_name', + 'Your login details for :site_name' => 'Deine Login-Daten für :site_name', + 'About Me' => 'Über Mich', + 'Profile' => 'Profil', + ) + ); diff --git a/plugins/box/users/languages/en.lang.php b/plugins/box/users/languages/en.lang.php index 113b53e..7734e50 100644 --- a/plugins/box/users/languages/en.lang.php +++ b/plugins/box/users/languages/en.lang.php @@ -64,4 +64,4 @@ 'About Me' => 'About Me', 'Profile' => 'Profile', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/users/languages/it.lang.php b/plugins/box/users/languages/it.lang.php index 50a4267..ffd2b04 100644 --- a/plugins/box/users/languages/it.lang.php +++ b/plugins/box/users/languages/it.lang.php @@ -62,4 +62,4 @@ 'About Me' => 'Su di me', 'Profile' => 'Profilo', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/users/languages/lt.lang.php b/plugins/box/users/languages/lt.lang.php index 3bf1c18..d826c94 100644 --- a/plugins/box/users/languages/lt.lang.php +++ b/plugins/box/users/languages/lt.lang.php @@ -63,4 +63,4 @@ 'About Me' => 'Apie mane', 'Profile' => 'Profilis', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/users/languages/pt-br.lang.php b/plugins/box/users/languages/pt-br.lang.php index 6c4eed3..84bf8f5 100644 --- a/plugins/box/users/languages/pt-br.lang.php +++ b/plugins/box/users/languages/pt-br.lang.php @@ -64,4 +64,4 @@ 'About Me' => 'Sobre mim', 'Profile' => 'Perfil', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/users/languages/ru.lang.php b/plugins/box/users/languages/ru.lang.php index d5261ff..d709057 100644 --- a/plugins/box/users/languages/ru.lang.php +++ b/plugins/box/users/languages/ru.lang.php @@ -62,4 +62,4 @@ 'About Me' => 'Обо мне', 'Profile' => 'Профиль', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/users/languages/uk.lang.php b/plugins/box/users/languages/uk.lang.php index 2fae7c5..0a53d03 100644 --- a/plugins/box/users/languages/uk.lang.php +++ b/plugins/box/users/languages/uk.lang.php @@ -62,4 +62,4 @@ 'About Me' => 'Про мене', 'Profile' => 'Профіль', ) - ); \ No newline at end of file + ); diff --git a/plugins/box/users/users.admin.php b/plugins/box/users/users.admin.php index c7217d4..7cb0f10 100755 --- a/plugins/box/users/users.admin.php +++ b/plugins/box/users/users.admin.php @@ -1,222 +1,220 @@ __('Admin', 'users'), + 'editor' => __('Editor', 'users'), + 'user' => __('User', 'users')); - /** - * Users admin - */ - public static function main() { + // Get uses table + $users = new Table('users'); - // Users roles - $roles = array('admin' => __('Admin', 'users'), - 'editor' => __('Editor', 'users'), - 'user' => __('User', 'users')); + if (Option::get('users_frontend_registration') == 'true') { + $users_frontend_registration = true; + } else { + $users_frontend_registration = false; + } - // Get uses table - $users = new Table('users'); + if (Request::post('users_frontend_submit')) { - if (Option::get('users_frontend_registration') == 'true') { - $users_frontend_registration = true; - } else { - $users_frontend_registration = false; - } + if (Security::check(Request::post('csrf'))) { - if (Request::post('users_frontend_submit')) { + if (Request::post('users_frontend_registration')) $users_frontend_registration = 'true'; else $users_frontend_registration = 'false'; + Option::update('users_frontend_registration', $users_frontend_registration); + Request::redirect('index.php?id=users'); - if (Security::check(Request::post('csrf'))) { + } else { die('csrf detected!'); } + } - if (Request::post('users_frontend_registration')) $users_frontend_registration = 'true'; else $users_frontend_registration = 'false'; - Option::update('users_frontend_registration', $users_frontend_registration); - Request::redirect('index.php?id=users'); + // Check for get actions + // --------------------------------------------- + if (Request::get('action')) { - } else { die('csrf detected!'); } - } + // Switch actions + // ----------------------------------------- + switch (Request::get('action')) { - // Check for get actions - // --------------------------------------------- - if (Request::get('action')) { + // Add + // ------------------------------------- + case "add": - // Switch actions - // ----------------------------------------- - switch (Request::get('action')) { + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - // Add - // ------------------------------------- - case "add": + // Errors + $errors = array(); - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + if (Request::post('register')) { - // Errors - $errors = array(); + if (Security::check(Request::post('csrf'))) { - if (Request::post('register')) { + $user_login = trim(Request::post('login')); + $user_password = trim(Request::post('password')); + $user_email = trim(Request::post('email')); + + if ($user_login == '') $errors['users_empty_login'] = __('Required field', 'users'); + if ($user_password == '') $errors['users_empty_password'] = __('Required field', 'users'); + if ($user_email == '') $errors['users_empty_email'] = __('Required field', 'users'); + if ($users->select("[login='".$user_login."']")) $errors['users_this_user_already_exists'] = __('This user already exists', 'users'); + if ($users->select("[email='".$user_email."']")) $errors['users_this_email_already_exists'] = __('This email already exists', 'users'); + + if (count($errors) == 0) { + $users->insert(array('login' => Security::safeName($user_login), + 'password' => Security::encryptPassword(Request::post('password')), + 'email' => Request::post('email'), + 'hash' => Text::random('alnum', 12), + 'date_registered' => time(), + 'role' => Request::post('role'))); + + Notification::set('success', __('New user have been registered.', 'users')); + Request::redirect('index.php?id=users'); + } + + } else { die('csrf detected!'); } + } + + // Display view + View::factory('box/users/views/backend/add') + ->assign('roles', $roles) + ->assign('errors', $errors) + ->display(); + + } else { + Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); + } + + break; + + // Edit + // ------------------------------------- + case "edit": + + // Get current user record + $user = $users->select("[id='".(int) Request::get('user_id')."']", null); + + if (isset($user['firstname'])) $user_firstname = $user['firstname']; else $user_firstname = ''; + if (isset($user['lastname'])) $user_lastname = $user['lastname']; else $user_lastname = ''; + if (isset($user['email'])) $user_email = $user['email']; else $user_email = ''; + if (isset($user['twitter'])) $user_twitter = $user['twitter']; else $user_twitter = ''; + if (isset($user['skype'])) $user_skype = $user['skype']; else $user_skype = ''; + if (isset($user['about_me'])) $user_about_me = $user['about_me']; else $user_about_me = ''; + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) { + + if ((Request::post('edit_profile')) and + (((int) Session::get('user_id') == (int) Request::get('user_id')) or + (in_array(Session::get('user_role'), array('admin'))))){ if (Security::check(Request::post('csrf'))) { - $user_login = trim(Request::post('login')); - $user_password = trim(Request::post('password')); - $user_email = trim(Request::post('email')); + if (Security::safeName(Request::post('login')) != '') { + if ($users->update(Request::post('user_id'), array('login' => Security::safeName(Request::post('login')), + 'firstname' => Request::post('firstname'), + 'lastname' => Request::post('lastname'), + 'email' => Request::post('email'), + 'skype' => Request::post('skype'), + 'twitter' => Request::post('twitter'), + 'about_me' => Request::post('about_me'), + 'role' => Request::post('role')))) { - if ($user_login == '') $errors['users_empty_login'] = __('Required field', 'users'); - if ($user_password == '') $errors['users_empty_password'] = __('Required field', 'users'); - if ($user_email == '') $errors['users_empty_email'] = __('Required field', 'users'); - if ($users->select("[login='".$user_login."']")) $errors['users_this_user_already_exists'] = __('This user already exists', 'users'); - if ($users->select("[email='".$user_email."']")) $errors['users_this_email_already_exists'] = __('This email already exists', 'users'); - - if (count($errors) == 0) { - $users->insert(array('login' => Security::safeName($user_login), - 'password' => Security::encryptPassword(Request::post('password')), - 'email' => Request::post('email'), - 'hash' => Text::random('alnum', 12), - 'date_registered' => time(), - 'role' => Request::post('role'))); - - Notification::set('success', __('New user have been registered.', 'users')); - Request::redirect('index.php?id=users'); - } + Notification::set('success', __('Your changes have been saved.', 'users')); + Request::redirect('index.php?id=users&action=edit&user_id='.Request::post('user_id')); + } + } else { } } else { die('csrf detected!'); } - } - + + } + + if (Request::post('edit_profile_password')) { + + if (Security::check(Request::post('csrf'))) { + + if (trim(Request::post('new_password')) != '') { + $users->update(Request::post('user_id'), array('password' => Security::encryptPassword(trim(Request::post('new_password'))))); + Notification::set('success', __('Your changes have been saved.', 'users')); + Request::redirect('index.php?id=users&action=edit&user_id='.Request::post('user_id')); + } + + } else { die('csrf detected!'); } + } + + if ( ((int) Session::get('user_id') == (int) Request::get('user_id')) or (in_array(Session::get('user_role'), array('admin')) && count($user) != 0) ) { + // Display view - View::factory('box/users/views/backend/add') + View::factory('box/users/views/backend/edit') + ->assign('user', $user) + ->assign('user_firstname', $user_firstname) + ->assign('user_lastname', $user_lastname) + ->assign('user_email', $user_email) + ->assign('user_twitter', $user_twitter) + ->assign('user_skype', $user_skype) + ->assign('user_about_me', $user_about_me) ->assign('roles', $roles) - ->assign('errors', $errors) ->display(); } else { - Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); + echo __('Monstra says: This is not your profile...', 'users'); } - break; + } - // Edit - // ------------------------------------- - case "edit": + break; - // Get current user record - $user = $users->select("[id='".(int)Request::get('user_id')."']", null); - - if (isset($user['firstname'])) $user_firstname = $user['firstname']; else $user_firstname = ''; - if (isset($user['lastname'])) $user_lastname = $user['lastname']; else $user_lastname = ''; - if (isset($user['email'])) $user_email = $user['email']; else $user_email = ''; - if (isset($user['twitter'])) $user_twitter = $user['twitter']; else $user_twitter = ''; - if (isset($user['skype'])) $user_skype = $user['skype']; else $user_skype = ''; - if (isset($user['about_me'])) $user_about_me = $user['about_me']; else $user_about_me = ''; + // Delete + // ------------------------------------- + case "delete": - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) { + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - if ((Request::post('edit_profile')) and - (((int)Session::get('user_id') == (int)Request::get('user_id')) or - (in_array(Session::get('user_role'), array('admin'))))){ + if (Security::check(Request::get('token'))) { - if (Security::check(Request::post('csrf'))) { + $user = $users->select('[id="'.Request::get('user_id').'"]', null); + $users->delete(Request::get('user_id')); + Notification::set('success', __('User :user have been deleted.', 'users', array(':user' => $user['login']))); + Request::redirect('index.php?id=users'); - if (Security::safeName(Request::post('login')) != '') { - if ($users->update(Request::post('user_id'), array('login' => Security::safeName(Request::post('login')), - 'firstname' => Request::post('firstname'), - 'lastname' => Request::post('lastname'), - 'email' => Request::post('email'), - 'skype' => Request::post('skype'), - 'twitter' => Request::post('twitter'), - 'about_me' => Request::post('about_me'), - 'role' => Request::post('role')))) { - - Notification::set('success', __('Your changes have been saved.', 'users')); - Request::redirect('index.php?id=users&action=edit&user_id='.Request::post('user_id')); - } - } else { } + } else { die('csrf detected!'); } - } else { die('csrf detected!'); } - - } + } - if (Request::post('edit_profile_password')) { - - if (Security::check(Request::post('csrf'))) { - - if (trim(Request::post('new_password')) != '') { - $users->update(Request::post('user_id'), array('password' => Security::encryptPassword(trim(Request::post('new_password'))))); - Notification::set('success', __('Your changes have been saved.', 'users')); - Request::redirect('index.php?id=users&action=edit&user_id='.Request::post('user_id')); - } - - } else { die('csrf detected!'); } - } - - if ( ((int)Session::get('user_id') == (int)Request::get('user_id')) or (in_array(Session::get('user_role'), array('admin')) && count($user) != 0) ) { - - // Display view - View::factory('box/users/views/backend/edit') - ->assign('user', $user) - ->assign('user_firstname', $user_firstname) - ->assign('user_lastname', $user_lastname) - ->assign('user_email', $user_email) - ->assign('user_twitter', $user_twitter) - ->assign('user_skype', $user_skype) - ->assign('user_about_me', $user_about_me) - ->assign('roles', $roles) - ->display(); - - } else { - echo __('Monstra says: This is not your profile...', 'users'); - } - - } - - break; - - // Delete - // ------------------------------------- - case "delete": - - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - - if (Security::check(Request::get('token'))) { - - $user = $users->select('[id="'.Request::get('user_id').'"]', null); - $users->delete(Request::get('user_id')); - Notification::set('success', __('User :user have been deleted.', 'users', array(':user' => $user['login']))); - Request::redirect('index.php?id=users'); - - } else { die('csrf detected!'); } - - } - - - - break; - } - } else { - - if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { - - // Dislay view - View::factory('box/users/views/backend/index') - ->assign('roles', $roles) - ->assign('users_list', $users->select()) - ->assign('users_frontend_registration', $users_frontend_registration) - ->display(); - - } else { - Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); - } + break; + } + } else { + + if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { + + // Dislay view + View::factory('box/users/views/backend/index') + ->assign('roles', $roles) + ->assign('users_list', $users->select()) + ->assign('users_frontend_registration', $users_frontend_registration) + ->display(); + + } else { + Request::redirect('index.php?id=users&action=edit&user_id='.Session::get('user_id')); } - } - } \ No newline at end of file + + } +} diff --git a/plugins/box/users/users.plugin.php b/plugins/box/users/users.plugin.php index 5064c41..ccf0cad 100644 --- a/plugins/box/users/users.plugin.php +++ b/plugins/box/users/users.plugin.php @@ -1,461 +1,451 @@ assign('users', Users::$users->select(null, 'all')) + ->display(); + } + /** + * Get user profile + */ + public static function getProfile($id) + { + View::factory('box/users/views/frontend/profile') + ->assign('user', Users::$users->select("[id=".(int) $id."]", null)) + ->display(); + } - /** - * Route - */ - protected static function route() { - /* /users */ - if (Uri::segment(0) == 'users' && !Uri::segment(1)) return 'list'; - /* /users/(int) */ - if (Uri::segment(1) && (Uri::segment(1) !== 'login' && Uri::segment(1) !== 'registration' && Uri::segment(1) !== 'password-reset' && Uri::segment(2) !== 'edit')) return 'profile'; - /* /users/login */ - if (Uri::segment(1) == 'login') return 'login'; - /* /users/registration */ - if (Uri::segment(1) == 'registration') return 'registration'; - /* /pusers/password-reset */ - if (Uri::segment(1) == 'password-reset') return 'password-reset'; - /* /users/(int)/edit */ - if ( ( Uri::segment(1) and (Uri::segment(1) !== 'login' && Uri::segment(1) !== 'registration' && Uri::segment(1) !== 'password-reset') ) and Uri::segment(2) == 'edit') return 'edit'; - /* /users/logout */ - if (Uri::segment(1) == 'logout') return 'logout'; - } - - - /** - * Get users list - */ - public static function getList() { - View::factory('box/users/views/frontend/index') - ->assign('users', Users::$users->select(null, 'all')) - ->display(); - } - - - /** - * Get user profile - */ - public static function getProfile($id) { - View::factory('box/users/views/frontend/profile') - ->assign('user', Users::$users->select("[id=".(int)$id."]", null)) - ->display(); - } - - - /** - * Get New User Registration - */ - public static function getRegistration() { - - if (Option::get('users_frontend_registration') == 'true') { - - // Is User Loged in ? - if ( ! Session::get('user_id')) { - - $errors = array(); - - $user_email = Request::post('email'); - $user_login = Request::post('login'); - $user_password = Request::post('password'); - - // Register form submit - if (Request::post('register')) { - - // Check csrf - if (Security::check(Request::post('csrf'))) { - - $user_email = trim($user_email); - $user_login = trim($user_login); - $user_password = trim($user_password); - - if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'captcha'); - if ($user_login == '') $errors['users_empty_login'] = __('Required field', 'users'); - if ($user_password == '') $errors['users_empty_password'] = __('Required field', 'users'); - if ($user_email == '') $errors['users_empty_email'] = __('Required field', 'users'); - if ($user_email != '' && ! Valid::email($user_email)) $errors['users_invalid_email'] = __('User email is invalid', 'users'); - if (Users::$users->select("[login='".$user_login."']")) $errors['users_this_user_alredy_exists'] = __('This user alredy exist', 'users'); - if (Users::$users->select("[email='".$user_email."']")) $errors['users_this_email_alredy_exists'] = __('This email alredy exist', 'users'); - - if (count($errors) == 0) { - - Users::$users->insert(array('login' => Security::safeName($user_login), - 'password' => Security::encryptPassword(Request::post('password')), - 'email' => Request::post('email'), - 'hash' => Text::random('alnum', 12), - 'date_registered' => time(), - 'role' => 'user')); - - // Log in - $user = Users::$users->select("[id='".Users::$users->lastId()."']", null); - Session::set('user_id', (int)$user['id']); - Session::set('user_login', (string)$user['login']); - Session::set('user_role', (string)$user['role']); - - // Message - $message = View::factory('box/users/views/frontend/registration_email') - ->assign('site_name', Option::get('sitename')) - ->assign('user_login', $user['login']) - ->render(); - - - // Send - @mail($user['email'], Option::get('sitename'), $message); - - - // Redirect to user profile - Request::redirect(Option::get('siteurl').'users/'.Users::$users->lastId()); - } - - - - } else { die('csrf detected!'); } - } - - // Display view - View::factory('box/users/views/frontend/registration') - ->assign('errors', $errors) - ->assign('user_email', $user_email) - ->assign('user_login', $user_login) - ->assign('user_password', $user_password) - ->display(); - - } else { - Request::redirect(Site::url().'users/'.Session::get('user_id')); - } - - } else { - echo __('User registration is closed.', 'users'); - } - - } - - - /** - * Get user panel - */ - public static function getPanel() { - View::factory('box/users/views/frontend/userspanel')->display(); - } - - - /** - * Is User Loged - */ - public static function isLoged() { - if ((Session::get('user_id')) and (((int)Session::get('user_id') == Uri::segment(1)) or (in_array(Session::get('user_role'), array('admin'))))) { - return true; - } else { - return false; - } - } - - - /** - * Logout - */ - public static function logout() { - Session::destroy(); - Request::redirect($_SERVER["HTTP_REFERER"]); - } - - - /** - * Edit user profile - */ - public static function getProfileEdit($id) { - - // Is Current User Loged in ? - if (Users::isLoged()) { - - $user = Users::$users->select("[id='".(int)$id."']", null); - - // Edit Profile Submit - if (Request::post('edit_profile')) { - - // Check csrf - if (Security::check(Request::post('csrf'))) { - - - if (Security::safeName(Request::post('login')) != '') { - if (Users::$users->update(Request::post('user_id'), - array('login' => Security::safeName(Request::post('login')), - 'firstname' => Request::post('firstname'), - 'lastname' => Request::post('lastname'), - 'email' => Request::post('email'), - 'skype' => Request::post('skype'), - 'about_me' => Request::post('about_me'), - 'twitter' => Request::post('twitter')))) { - - // Change password - if (trim(Request::post('new_password')) != '') { - Users::$users->update(Request::post('user_id'), array('password' => Security::encryptPassword(trim(Request::post('new_password'))))); - } - - Notification::set('success', __('Your changes have been saved.', 'users')); - Request::redirect(Site::url().'users/'.$user['id']); - } - } else { } - - } else { die('csrf detected!'); } - - } - - View::factory('box/users/views/frontend/edit') - ->assign('user', $user) - ->display(); - - } else { - Request::redirect(Site::url().'users/login'); - } - } - - /** - * Get Password Reset - */ - public static function getPasswordReset() { + /** + * Get New User Registration + */ + public static function getRegistration() + { + if (Option::get('users_frontend_registration') == 'true') { // Is User Loged in ? if ( ! Session::get('user_id')) { $errors = array(); - $site_url = Option::get('siteurl'); - $site_name = Option::get('sitename'); + $user_email = Request::post('email'); + $user_login = Request::post('login'); + $user_password = Request::post('password'); - // Reset Password from hash - if (Request::get('hash')) { - - // Get user with specific hash - $user = Users::$users->select("[hash='" . Request::get('hash') . "']", null); + // Register form submit + if (Request::post('register')) { - // If user exists - if ((count($user) > 0) && ($user['hash'] == Request::get('hash'))) { + // Check csrf + if (Security::check(Request::post('csrf'))) { - // Generate new password - $new_password = Text::random('alnum', 6); + $user_email = trim($user_email); + $user_login = trim($user_login); + $user_password = trim($user_password); - // Update user profile - // Set new hash and new password - Users::$users->updateWhere("[login='" . $user['login'] . "']", array('hash' => Text::random('alnum', 12), 'password' => Security::encryptPassword($new_password))); + if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'captcha'); + if ($user_login == '') $errors['users_empty_login'] = __('Required field', 'users'); + if ($user_password == '') $errors['users_empty_password'] = __('Required field', 'users'); + if ($user_email == '') $errors['users_empty_email'] = __('Required field', 'users'); + if ($user_email != '' && ! Valid::email($user_email)) $errors['users_invalid_email'] = __('User email is invalid', 'users'); + if (Users::$users->select("[login='".$user_login."']")) $errors['users_this_user_alredy_exists'] = __('This user alredy exist', 'users'); + if (Users::$users->select("[email='".$user_email."']")) $errors['users_this_email_alredy_exists'] = __('This email alredy exist', 'users'); + + if (count($errors) == 0) { + + Users::$users->insert(array('login' => Security::safeName($user_login), + 'password' => Security::encryptPassword(Request::post('password')), + 'email' => Request::post('email'), + 'hash' => Text::random('alnum', 12), + 'date_registered' => time(), + 'role' => 'user')); + + // Log in + $user = Users::$users->select("[id='".Users::$users->lastId()."']", null); + Session::set('user_id', (int) $user['id']); + Session::set('user_login', (string) $user['login']); + Session::set('user_role', (string) $user['role']); + + // Message + $message = View::factory('box/users/views/frontend/registration_email') + ->assign('site_name', Option::get('sitename')) + ->assign('user_login', $user['login']) + ->render(); + + // Send + @mail($user['email'], Option::get('sitename'), $message); + + // Redirect to user profile + Request::redirect(Option::get('siteurl').'users/'.Users::$users->lastId()); + } + + } else { die('csrf detected!'); } + } + + // Display view + View::factory('box/users/views/frontend/registration') + ->assign('errors', $errors) + ->assign('user_email', $user_email) + ->assign('user_login', $user_login) + ->assign('user_password', $user_password) + ->display(); + + } else { + Request::redirect(Site::url().'users/'.Session::get('user_id')); + } + + } else { + echo __('User registration is closed.', 'users'); + } + + } + + /** + * Get user panel + */ + public static function getPanel() + { + View::factory('box/users/views/frontend/userspanel')->display(); + } + + /** + * Is User Loged + */ + public static function isLoged() + { + if ((Session::get('user_id')) and (((int) Session::get('user_id') == Uri::segment(1)) or (in_array(Session::get('user_role'), array('admin'))))) { + return true; + } else { + return false; + } + } + + /** + * Logout + */ + public static function logout() + { + Session::destroy(); + Request::redirect($_SERVER["HTTP_REFERER"]); + } + + /** + * Edit user profile + */ + public static function getProfileEdit($id) + { + // Is Current User Loged in ? + if (Users::isLoged()) { + + $user = Users::$users->select("[id='".(int) $id."']", null); + + // Edit Profile Submit + if (Request::post('edit_profile')) { + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + if (Security::safeName(Request::post('login')) != '') { + if (Users::$users->update(Request::post('user_id'), + array('login' => Security::safeName(Request::post('login')), + 'firstname' => Request::post('firstname'), + 'lastname' => Request::post('lastname'), + 'email' => Request::post('email'), + 'skype' => Request::post('skype'), + 'about_me' => Request::post('about_me'), + 'twitter' => Request::post('twitter')))) { + + // Change password + if (trim(Request::post('new_password')) != '') { + Users::$users->update(Request::post('user_id'), array('password' => Security::encryptPassword(trim(Request::post('new_password'))))); + } + + Notification::set('success', __('Your changes have been saved.', 'users')); + Request::redirect(Site::url().'users/'.$user['id']); + } + } else { } + + } else { die('csrf detected!'); } + + } + + View::factory('box/users/views/frontend/edit') + ->assign('user', $user) + ->display(); + + } else { + Request::redirect(Site::url().'users/login'); + } + } + + /** + * Get Password Reset + */ + public static function getPasswordReset() + { + // Is User Loged in ? + if ( ! Session::get('user_id')) { + + $errors = array(); + + $site_url = Option::get('siteurl'); + $site_name = Option::get('sitename'); + + // Reset Password from hash + if (Request::get('hash')) { + + // Get user with specific hash + $user = Users::$users->select("[hash='" . Request::get('hash') . "']", null); + + // If user exists + if ((count($user) > 0) && ($user['hash'] == Request::get('hash'))) { + + // Generate new password + $new_password = Text::random('alnum', 6); + + // Update user profile + // Set new hash and new password + Users::$users->updateWhere("[login='" . $user['login'] . "']", array('hash' => Text::random('alnum', 12), 'password' => Security::encryptPassword($new_password))); + + // Message + $message = View::factory('box/users/views/frontend/new_password_email') + ->assign('site_url', $site_url) + ->assign('site_name', $site_name) + ->assign('user_id', $user['id']) + ->assign('user_login', $user['login']) + ->assign('new_password', $new_password) + ->render(); + + // Send + @mail($user['email'], __('Your new password for :site_name', 'users', array(':site_name' => $site_name)), $message); + + // Set notification + Notification::set('success', __('New password has been sent', 'users')); + + // Redirect to password-reset page + Request::redirect(Site::url().'users/password-reset'); + + } + } + + // Reset Password Form Submit + if (Request::post('reset_password_submit')) { + + $user_login = trim(Request::post('login')); + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users'); + if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users'); + if ($user_login != '' && ! Users::$users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users'); + + if (count($errors) == 0) { + + // Get user + $user = Users::$users->select("[login='" . $user_login . "']", null); + + // Generate new hash + $new_hash = Text::random('alnum', 12); + + // Update user hash + Users::$users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash)); // Message - $message = View::factory('box/users/views/frontend/new_password_email') + $message = View::factory('box/users/views/frontend/reset_password_email') ->assign('site_url', $site_url) ->assign('site_name', $site_name) ->assign('user_id', $user['id']) ->assign('user_login', $user['login']) - ->assign('new_password', $new_password) + ->assign('new_hash', $new_hash) ->render(); - // Send - @mail($user['email'], __('Your new password for :site_name', 'users', array(':site_name' => $site_name)), $message); + @mail($user['email'], __('Your login details for :site_name', 'users', array(':site_name' => $site_name)), $message); // Set notification - Notification::set('success', __('New password has been sent', 'users')); + Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name))); // Redirect to password-reset page Request::redirect(Site::url().'users/password-reset'); } - } - // Reset Password Form Submit - if (Request::post('reset_password_submit')) { - - $user_login = trim(Request::post('login')); - - // Check csrf - if (Security::check(Request::post('csrf'))) { - - if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users'); - if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users'); - if ($user_login != '' && ! Users::$users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users'); - - if (count($errors) == 0) { - - // Get user - $user = Users::$users->select("[login='" . $user_login . "']", null); - - // Generate new hash - $new_hash = Text::random('alnum', 12); - - // Update user hash - Users::$users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash)); - - // Message - $message = View::factory('box/users/views/frontend/reset_password_email') - ->assign('site_url', $site_url) - ->assign('site_name', $site_name) - ->assign('user_id', $user['id']) - ->assign('user_login', $user['login']) - ->assign('new_hash', $new_hash) - ->render(); - - - // Send - @mail($user['email'], __('Your login details for :site_name', 'users', array(':site_name' => $site_name)), $message); - - // Set notification - Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name))); - - // Redirect to password-reset page - Request::redirect(Site::url().'users/password-reset'); - - } - - } else { die('csrf detected!'); } - - } - - View::factory('box/users/views/frontend/password_reset') - ->assign('errors', $errors) - ->assign('user_login', trim(Request::post('login'))) - ->display(); + } else { die('csrf detected!'); } } + + View::factory('box/users/views/frontend/password_reset') + ->assign('errors', $errors) + ->assign('user_login', trim(Request::post('login'))) + ->display(); + } - - /** - * Get User login - */ - public static function getLogin() { - - // Is User Loged in ? - if ( ! Session::get('user_id')) { - - // Login Form Submit - if (Request::post('login_submit')) { - - // Check csrf - if (Security::check(Request::post('csrf'))) { - - $user = Users::$users->select("[login='" . trim(Request::post('username')) . "']", null); - - if (count($user) !== 0) { - if ($user['login'] == Request::post('username')) { - if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) { - if ($user['role'] == 'admin' || $user['role'] == 'editor') { - Session::set('admin', true); - } - Session::set('user_id', (int)$user['id']); - Session::set('user_login', (string)$user['login']); - Session::set('user_role', (string)$user['role']); - Request::redirect(Site::url().'users/'.Session::get('user_id')); - } else { - Notification::setNow('error', __('Wrong username or password', 'users')); - } - } - } else { - Notification::setNow('error', __('Wrong username or password', 'users')); - } - - } else { die('csrf detected!'); } - - } - - View::factory('box/users/views/frontend/login')->display(); - } else { - Request::redirect(Site::url().'users/'.Session::get('user_id')); - } - } - - - /** - * Set title - */ - public static function title(){ - switch (Users::route()) { - case 'list': return __('Users', 'users'); break; - case 'profile': return __('Users - Profile', 'users'); break; - case 'edit': return __('Users - Edit Profile', 'users'); break; - case 'login': return __('Users - Login', 'users'); break; - case 'registration': return __('Users - Registration', 'users'); break; - case 'password-reset': return __('Users - Password Recover', 'users'); break; - } - } - - - /** - * Set content - */ - public static function content(){ - switch (Users::route()) { - case 'list': Users::getList(); break; - case 'profile': Users::getProfile(Uri::segment(1)); break; - case 'edit': Users::getProfileEdit(Uri::segment(1)); break; - case 'login': Users::getLogin(); break; - case 'registration': Users::getRegistration(); break; - case 'password-reset': Users::getPasswordReset(); break; - - } - } - - /** - * Set template - */ - public static function template() { - return 'index'; - } - - - /** - * Get Gravatar - */ - public static function getGravatarURL($email, $size) { - return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).'&rating=PG'.'&size='.$size; - } - } + + /** + * Get User login + */ + public static function getLogin() + { + // Is User Loged in ? + if ( ! Session::get('user_id')) { + + // Login Form Submit + if (Request::post('login_submit')) { + + // Check csrf + if (Security::check(Request::post('csrf'))) { + + $user = Users::$users->select("[login='" . trim(Request::post('username')) . "']", null); + + if (count($user) !== 0) { + if ($user['login'] == Request::post('username')) { + if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) { + if ($user['role'] == 'admin' || $user['role'] == 'editor') { + Session::set('admin', true); + } + Session::set('user_id', (int) $user['id']); + Session::set('user_login', (string) $user['login']); + Session::set('user_role', (string) $user['role']); + Request::redirect(Site::url().'users/'.Session::get('user_id')); + } else { + Notification::setNow('error', __('Wrong username or password', 'users')); + } + } + } else { + Notification::setNow('error', __('Wrong username or password', 'users')); + } + + } else { die('csrf detected!'); } + + } + + View::factory('box/users/views/frontend/login')->display(); + } else { + Request::redirect(Site::url().'users/'.Session::get('user_id')); + } + } + + /** + * Set title + */ + public static function title() + { + switch (Users::route()) { + case 'list': return __('Users', 'users'); break; + case 'profile': return __('Users - Profile', 'users'); break; + case 'edit': return __('Users - Edit Profile', 'users'); break; + case 'login': return __('Users - Login', 'users'); break; + case 'registration': return __('Users - Registration', 'users'); break; + case 'password-reset': return __('Users - Password Recover', 'users'); break; + } + } + + /** + * Set content + */ + public static function content() + { + switch (Users::route()) { + case 'list': Users::getList(); break; + case 'profile': Users::getProfile(Uri::segment(1)); break; + case 'edit': Users::getProfileEdit(Uri::segment(1)); break; + case 'login': Users::getLogin(); break; + case 'registration': Users::getRegistration(); break; + case 'password-reset': Users::getPasswordReset(); break; + + } + } + + /** + * Set template + */ + public static function template() + { + return 'index'; + } + + /** + * Get Gravatar + */ + public static function getGravatarURL($email, $size) + { + return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).'&rating=PG'.'&size='.$size; + } + +} diff --git a/plugins/box/users/views/backend/add.view.php b/plugins/box/users/views/backend/add.view.php index 0c9e5eb..193098a 100644 --- a/plugins/box/users/views/backend/add.view.php +++ b/plugins/box/users/views/backend/add.view.php @@ -35,4 +35,4 @@ Form::close() ); ?> - \ No newline at end of file + diff --git a/plugins/box/users/views/backend/edit.view.php b/plugins/box/users/views/backend/edit.view.php index 270e938..dae5e2e 100644 --- a/plugins/box/users/views/backend/edit.view.php +++ b/plugins/box/users/views/backend/edit.view.php @@ -15,7 +15,7 @@
    -
    +
    'input-xlarge')); } else { @@ -33,7 +33,7 @@ echo ( Html::br(). - Form::label('firstname', __('Firstname', 'users')). + Form::label('firstname', __('Firstname', 'users')). Form::input('firstname', $user_firstname, array('class' => 'input-xlarge')).Html::br(). Form::label('lastname', __('Lastname', 'users')). Form::input('lastname', $user_lastname, array('class' => 'input-xlarge')).Html::br(). @@ -47,20 +47,19 @@ Form::textarea('about_me', $user_about_me, array('class' => 'input-xlarge')).Html::br() ); - if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], array('admin'))) { + if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], array('admin'))) { echo Form::label('role', __('Role', 'users')); echo Form::select('role', array('admin' => __('Admin', 'users'), 'editor' => __('Editor', 'users'), 'user' => __('User', 'users')), $user['role'], array('class' => 'input-xlarge')). Html::br(); - } else { + } else { echo Form::hidden('role', $_SESSION['user_role']); } - echo ( Html::br(). Form::submit('edit_profile', __('Save', 'users'), array('class' => 'btn')). Form::close() ); - + ?>
    @@ -75,7 +74,7 @@ Form::password('new_password', null, array('class' => 'input-xlarge')).Html::br().Html::br(). Form::submit('edit_profile_password', __('Save', 'users'), array('class' => 'btn')). Form::close() - ); + ); ?>
    @@ -88,4 +87,4 @@ echo '
    '.__('This user does not exist', 'users').'
    '; } ?> - \ No newline at end of file + diff --git a/plugins/box/users/views/backend/index.view.php b/plugins/box/users/views/backend/index.view.php index 964cf1d..3b30c2d 100755 --- a/plugins/box/users/views/backend/index.view.php +++ b/plugins/box/users/views/backend/index.view.php @@ -28,7 +28,7 @@ - + @@ -50,8 +50,8 @@ ?>
    - + - \ No newline at end of file + diff --git a/plugins/box/users/views/frontend/edit.view.php b/plugins/box/users/views/frontend/edit.view.php index ba37512..42bb872 100644 --- a/plugins/box/users/views/frontend/edit.view.php +++ b/plugins/box/users/views/frontend/edit.view.php @@ -6,13 +6,13 @@
    - + @@ -23,4 +23,4 @@
    -
    \ No newline at end of file + diff --git a/plugins/box/users/views/frontend/index.view.php b/plugins/box/users/views/frontend/index.view.php index 6adfed3..9173f3a 100644 --- a/plugins/box/users/views/frontend/index.view.php +++ b/plugins/box/users/views/frontend/index.view.php @@ -2,13 +2,13 @@
    - - + + + + -
    - -
    \ No newline at end of file + diff --git a/plugins/box/users/views/frontend/login.view.php b/plugins/box/users/views/frontend/login.view.php index d74c49f..d935d86 100644 --- a/plugins/box/users/views/frontend/login.view.php +++ b/plugins/box/users/views/frontend/login.view.php @@ -7,4 +7,3 @@
    - diff --git a/plugins/box/users/views/frontend/new_password_email.view.php b/plugins/box/users/views/frontend/new_password_email.view.php index 7fb6db8..1154b15 100644 --- a/plugins/box/users/views/frontend/new_password_email.view.php +++ b/plugins/box/users/views/frontend/new_password_email.view.php @@ -6,9 +6,7 @@ Username: Password: - To change your password, please visit this page: users/ - All the best, - \ No newline at end of file + diff --git a/plugins/box/users/views/frontend/password_reset.view.php b/plugins/box/users/views/frontend/password_reset.view.php index 3d9f702..d066536 100644 --- a/plugins/box/users/views/frontend/password_reset.view.php +++ b/plugins/box/users/views/frontend/password_reset.view.php @@ -10,7 +10,7 @@ ?> -'.$errors['users_user_doesnt_exists'].''; if (isset($errors['users_empty_field'])) echo Html::nbsp(3).''.$errors['users_empty_field'].''; ?> @@ -22,4 +22,4 @@
    - \ No newline at end of file + diff --git a/plugins/box/users/views/frontend/profile.view.php b/plugins/box/users/views/frontend/profile.view.php index 1f6c404..c6a0f13 100644 --- a/plugins/box/users/views/frontend/profile.view.php +++ b/plugins/box/users/views/frontend/profile.view.php @@ -3,18 +3,18 @@ - - - - - - - + + + + + + +
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :
    :

    / - / + / - \ No newline at end of file + diff --git a/plugins/box/users/views/frontend/registration.view.php b/plugins/box/users/views/frontend/registration.view.php index 7166844..06f8cf1 100644 --- a/plugins/box/users/views/frontend/registration.view.php +++ b/plugins/box/users/views/frontend/registration.view.php @@ -6,7 +6,7 @@ ?> -'.$errors['users_this_user_alredy_exists'].''; if (isset($errors['users_empty_login'])) echo Html::nbsp(3).''.$errors['users_empty_login'].''; ?> @@ -15,10 +15,10 @@ if (isset($errors['users_empty_password'])) echo Html::nbsp(3).''.$errors['users_empty_password'].''; ?> -'.$errors['users_this_email_alredy_exists'].''; if (isset($errors['users_empty_email'])) echo Html::nbsp(3).''.$errors['users_empty_email'].''; - if (isset($errors['users_invalid_email'])) echo Html::nbsp(3).''.$errors['users_invalid_email'].''; + if (isset($errors['users_invalid_email'])) echo Html::nbsp(3).''.$errors['users_invalid_email'].''; ?>
    diff --git a/plugins/captcha/captcha.plugin.php b/plugins/captcha/captcha.plugin.php index 732da8d..672c263 100644 --- a/plugins/captcha/captcha.plugin.php +++ b/plugins/captcha/captcha.plugin.php @@ -1,49 +1,48 @@ "; if ($reload) echo "  "; echo ""; } - /** * Verify Code */ -function chk_crypt($code) { +function chk_crypt($code) +{ include ($_SESSION['configfile']); $code = addslashes ($code); $code = str_replace(' ', '', $code); $code = ($difuplow ? $code : strtoupper($code)); - switch (strtoupper($cryptsecure)) { + switch (strtoupper($cryptsecure)) { case "MD5" : $code = md5($code); break; case "SHA1" : $code = sha1($code); break; } if ($_SESSION['cryptcode'] and ($_SESSION['cryptcode'] == $code)) { unset($_SESSION['cryptreload']); - if ($cryptoneuse) unset($_SESSION['cryptcode']); + if ($cryptoneuse) unset($_SESSION['cryptcode']); return true; } else { $_SESSION['cryptreload'] = true; + return false; } -} \ No newline at end of file +} diff --git a/plugins/captcha/crypt/cryptographp.inc.php b/plugins/captcha/crypt/cryptographp.inc.php index 851f5ce..a55c306 100644 --- a/plugins/captcha/crypt/cryptographp.inc.php +++ b/plugins/captcha/crypt/cryptographp.inc.php @@ -4,15 +4,15 @@ * Cryptographp / v1.5 * * @version 1.5 Romanenko Sergey / Awilum - * @version 1.4 by Sylvain BRISON + * @version 1.4 by Sylvain BRISON */ error_reporting(0); -srand((double)microtime()*1000000); +srand((double) microtime()*1000000); -if (( ! isset($_COOKIE['cryptcookietest'])) and ($_GET[$_GET['sn']] == "")) { +if (( ! isset($_COOKIE['cryptcookietest'])) and ($_GET[$_GET['sn']] == "")) { header("Content-type: image/png"); - readfile('images/erreur3.png'); + readfile('images/erreur3.png'); exit; } @@ -20,27 +20,26 @@ if ($_GET[$_GET['sn']] == "") { unset ($_GET['sn']); } session_start(); - // Takes only the configuration files in the same directory if (is_file($_GET['cfg']) and dirname($_GET['cfg']) == '.' ) { $_SESSION['configfile']=$_GET['cfg']; } else { $_SESSION['configfile'] = "cryptographp.cfg.php"; } -include($_SESSION['configfile']); +include($_SESSION['configfile']); if ($_SESSION['cryptcptuse'] >= $cryptusemax) { header("Content-type: image/png"); - readfile('images/erreur1.png'); + readfile('images/erreur1.png'); exit; } $delai = time()-$_SESSION['crypttime']; -if ($delai < $cryptusetimer) { +if ($delai < $cryptusetimer) { switch ($cryptusertimererror) { case 2 : header("Content-type: image/png"); - readfile('images/erreur2.png'); + readfile('images/erreur2.png'); exit; case 3 : sleep ($cryptusetimer-$delai); break; // Fait une pause - case 1 : + case 1 : default : exit; // Quitte le script sans rien faire } } @@ -51,15 +50,14 @@ $blank = imagecolorallocate($imgtmp,255,255,255); $black = imagecolorallocate($imgtmp,0,0,0); imagefill($imgtmp,0,0,$blank); - $word =''; -$x = 10; +$x = 10; $pair = rand(0,1); $charnb = rand($charnbmin,$charnbmax); -for ($i=1;$i<= $charnb;$i++) { +for ($i=1;$i<= $charnb;$i++) { $tword[$i]['font'] = $tfont[array_rand($tfont,1)]; $tword[$i]['angle'] = (rand(1,2)==1)?rand(0,$charanglemax):rand(360-$charanglemax,360); - + if ($crypteasy) $tword[$i]['element'] =(!$pair)?$charelc{rand(0,strlen($charelc)-1)}:$charelv{rand(0,strlen($charelv)-1)}; else $tword[$i]['element'] = $charel{rand(0,strlen($charel)-1)}; @@ -67,12 +65,12 @@ for ($i=1;$i<= $charnb;$i++) { $tword[$i]['size'] = rand($charsizemin,$charsizemax); $tword[$i]['y'] = ($charup?($cryptheight/2)+rand(0,($cryptheight/5)):($cryptheight/1.5)); $word .=$tword[$i]['element']; - + $lafont="fonts/".$tword[$i]['font']; imagettftext($imgtmp,$tword[$i]['size'],$tword[$i]['angle'],$x,$tword[$i]['y'],$black,$lafont,$tword[$i]['element']); $x +=$charspace; -} +} // Calculation of horizontal framing cryptograms temporary $xbegin=0; @@ -84,8 +82,8 @@ while (($x<$cryptwidth)and(!$xbegin)) { $y++; } $x++; -} - +} + $xend=0; $x=$cryptwidth-1; while (($x>0)and(!$xend)) { @@ -95,18 +93,17 @@ while (($x>0)and(!$xend)) { $y++; } $x--; -} - +} + $xvariation = round(($cryptwidth/2)-(($xend-$xbegin)/2)); imagedestroy ($imgtmp); - // Creating the final cryptogram -$img = imagecreatetruecolor($cryptwidth, $cryptheight); +$img = imagecreatetruecolor($cryptwidth, $cryptheight); if ($bgimg and is_dir($bgimg)) { $dh = opendir($bgimg); - while (false !== ($filename = readdir($dh))) + while (false !== ($filename = readdir($dh))) if (eregi(".[gif|jpg|png]$", $filename)) { $files[] = $filename; } closedir($dh); $bgimg = $bgimg.'/'.$files[array_rand($files,1)]; @@ -127,17 +124,16 @@ if ($bgimg) { if ($bgclear) imagecolortransparent($img,$bg); } - -function ecriture() { - +function ecriture() +{ global $img, $ink, $charR, $charG, $charB, $charclear, $xvariation, $charnb, $charcolorrnd, $charcolorrndlevel, $tword, $charspace; if (function_exists ('imagecolorallocatealpha')) $ink = imagecolorallocatealpha($img,$charR,$charG,$charB,$charclear); else $ink = imagecolorallocate ($img,$charR,$charG,$charB); - + $x = $xvariation; - for ($i = 1; $i <= $charnb; $i++) { - - if ($charcolorrnd) { + for ($i = 1; $i <= $charnb; $i++) { + + if ($charcolorrnd) { $ok = false; do { $rndR = rand(0,255); $rndG = rand(0,255); $rndB = rand(0,255); @@ -147,29 +143,29 @@ function ecriture() { case 2 : if ($rndcolor<400) $ok=true; break; // sombre case 3 : if ($rndcolor>500) $ok=true; break; // claires case 4 : if ($rndcolor>650) $ok=true; break; // tr?s claires - default : $ok=true; + default : $ok=true; } } while (!$ok); - + if (function_exists ('imagecolorallocatealpha')) $rndink = imagecolorallocatealpha($img,$rndR,$rndG,$rndB,$charclear); - else $rndink = imagecolorallocate ($img,$rndR,$rndG,$rndB); - } - + else $rndink = imagecolorallocate ($img,$rndR,$rndG,$rndB); + } + $lafont="fonts/".$tword[$i]['font']; imagettftext($img,$tword[$i]['size'],$tword[$i]['angle'],$x,$tword[$i]['y'],$charcolorrnd?$rndink:$ink,$lafont,$tword[$i]['element']); $x +=$charspace; - } + } } - -function noisecolor() { +function noisecolor() +{ global $img, $noisecolorchar, $ink, $bg, $brushsize; switch ($noisecolorchar) { case 1 : $noisecol = $ink; break; case 2 : $noisecol = $bg; break; - case 3 : - default : $noisecol = imagecolorallocate ($img,rand(0,255),rand(0,255),rand(0,255)); break; + case 3 : + default : $noisecol = imagecolorallocate ($img,rand(0,255),rand(0,255),rand(0,255)); break; } if ($brushsize and $brushsize > 1 and function_exists('imagesetbrush')) { $brush = imagecreatetruecolor($brushsize,$brushsize); @@ -177,11 +173,12 @@ function noisecolor() { imagesetbrush($img, $brush); $noisecol = IMG_COLOR_BRUSHED; } - return $noisecol; + + return $noisecol; } - -function bruit() { +function bruit() +{ global $noisepxmin, $noisepxmax, $noiselinemin, $noiselinemax, $nbcirclemin, $nbcirclemax,$img, $cryptwidth, $cryptheight; $nbpx = rand($noisepxmin,$noisepxmax); $nbline = rand($noiselinemin,$noiselinemax); @@ -189,8 +186,7 @@ function bruit() { for ($i=1;$i<$nbpx;$i++) imagesetpixel ($img,rand(0,$cryptwidth-1),rand(0,$cryptheight-1),noisecolor()); for ($i=1;$i<=$nbline;$i++) imageline($img,rand(0,$cryptwidth-1),rand(0,$cryptheight-1),rand(0,$cryptwidth-1),rand(0,$cryptheight-1),noisecolor()); for ($i=1;$i<=$nbcircle;$i++) imagearc($img,rand(0,$cryptwidth-1),rand(0,$cryptheight-1),$rayon=rand(5,$cryptwidth/3),$rayon,0,360,noisecolor()); -} - +} if ($noiseup) { ecriture(); @@ -200,51 +196,46 @@ if ($noiseup) { ecriture(); } - // Creating frame if ($bgframe) { $framecol = imagecolorallocate($img,($bgR*3+$charR)/4,($bgG*3+$charG)/4,($bgB*3+$charB)/4); imagerectangle($img, 0, 0, $cryptwidth-1, $cryptheight-1, $framecol); } - - + // Additional changes: grayscale and gaussian blur if (function_exists('imagefilter')) { if ($cryptgrayscal) imagefilter ( $img, IMG_FILTER_GRAYSCALE); if ($cryptgaussianblur) imagefilter ( $img, IMG_FILTER_GAUSSIAN_BLUR); } - // Shift conversion cryptograms $word = ($difuplow?$word:strtoupper($word)); - // Write cryptcode to the Session -switch (strtoupper($cryptsecure)) { +switch (strtoupper($cryptsecure)) { case "MD5" : $_SESSION['cryptcode'] = md5($word); break; case "SHA1" : $_SESSION['cryptcode'] = sha1($word); break; default : $_SESSION['cryptcode'] = $word; break; } $_SESSION['crypttime'] = time(); -$_SESSION['cryptcptuse']++; - +$_SESSION['cryptcptuse']++; -// Render image -switch (strtoupper($cryptformat)) { +// Render image +switch (strtoupper($cryptformat)) { case "JPG" : - case "JPEG" : if (imagetypes() & IMG_JPG) { + case "JPEG" : if (imagetypes() & IMG_JPG) { header("Content-type: image/jpeg"); imagejpeg($img, "", 80); } break; - case "GIF" : if (imagetypes() & IMG_GIF) { + case "GIF" : if (imagetypes() & IMG_GIF) { header("Content-type: image/gif"); imagegif($img); } break; - case "PNG" : - default : if (imagetypes() & IMG_PNG) { + case "PNG" : + default : if (imagetypes() & IMG_PNG) { header("Content-type: image/png"); imagepng($img); } @@ -252,4 +243,4 @@ switch (strtoupper($cryptformat)) { imagedestroy ($img); unset ($word,$tword); -unset ($_SESSION['cryptreload']); \ No newline at end of file +unset ($_SESSION['cryptreload']); diff --git a/plugins/captcha/crypt/cryptographp.php b/plugins/captcha/crypt/cryptographp.php index c462aa0..b54ad32 100644 --- a/plugins/captcha/crypt/cryptographp.php +++ b/plugins/captcha/crypt/cryptographp.php @@ -2,4 +2,4 @@ session_start(); error_reporting(E_ALL ^ E_NOTICE); SetCookie("cryptcookietest", "1"); -Header("Location: cryptographp.inc.php?cfg=".$_GET['cfg']."&sn=".session_name()."&".SID); \ No newline at end of file +Header("Location: cryptographp.inc.php?cfg=".$_GET['cfg']."&sn=".session_name()."&".SID); diff --git a/plugins/captcha/install/captcha.install.php b/plugins/captcha/install/captcha.install.php index 303ebf3..f5cecd8 100644 --- a/plugins/captcha/install/captcha.install.php +++ b/plugins/captcha/install/captcha.install.php @@ -1,4 +1,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/captcha/install/captcha.uninstall.php b/plugins/captcha/install/captcha.uninstall.php index 1288584..e00e10b 100644 --- a/plugins/captcha/install/captcha.uninstall.php +++ b/plugins/captcha/install/captcha.uninstall.php @@ -1,4 +1,4 @@ array( - 'Captcha' => 'Captcha', - 'Captcha plugin for Monstra' => 'Captcha Plugin für Monstra', - 'Captcha code is wrong' => 'Captcha Code ist falsch', - ) - ); \ No newline at end of file + array( + 'Captcha' => 'Captcha', + 'Captcha plugin for Monstra' => 'Captcha Plugin für Monstra', + 'Captcha code is wrong' => 'Captcha Code ist falsch', + ) + ); diff --git a/plugins/captcha/languages/en.lang.php b/plugins/captcha/languages/en.lang.php index ef46308..b06844e 100644 --- a/plugins/captcha/languages/en.lang.php +++ b/plugins/captcha/languages/en.lang.php @@ -5,5 +5,5 @@ 'Captcha' => 'Captcha', 'Captcha plugin for Monstra' => 'Captcha plugin for Monstra', 'Captcha code is wrong' => 'Captcha code is wrong', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/captcha/languages/it.lang.php b/plugins/captcha/languages/it.lang.php index 543e21a..e43d160 100644 --- a/plugins/captcha/languages/it.lang.php +++ b/plugins/captcha/languages/it.lang.php @@ -5,5 +5,5 @@ 'Captcha' => 'Captcha', 'Captcha plugin for Monstra' => 'Captcha plugin per Monstra', 'Captcha code is wrong' => 'Codice captcha è errato', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/captcha/languages/lt.lang.php b/plugins/captcha/languages/lt.lang.php index 1b1e28b..aa89284 100644 --- a/plugins/captcha/languages/lt.lang.php +++ b/plugins/captcha/languages/lt.lang.php @@ -5,5 +5,5 @@ 'Captcha' => 'Saugos kodas', 'Captcha plugin for Monstra' => 'Saugos kodo papildinys', 'Captcha code is wrong' => 'Saugos kodas yra neteisingas', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/captcha/languages/pt-br.lang.php b/plugins/captcha/languages/pt-br.lang.php index 33124d6..2b39253 100644 --- a/plugins/captcha/languages/pt-br.lang.php +++ b/plugins/captcha/languages/pt-br.lang.php @@ -5,5 +5,5 @@ 'Captcha' => 'Captcha', 'Captcha plugin for Monstra' => 'Plugin de captcha para o Monstra CMS', 'Captcha code is wrong' => 'O Captcha está errado', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/captcha/languages/ru.lang.php b/plugins/captcha/languages/ru.lang.php index eac02b2..9f22d48 100644 --- a/plugins/captcha/languages/ru.lang.php +++ b/plugins/captcha/languages/ru.lang.php @@ -5,5 +5,5 @@ 'Captcha' => 'Captcha', 'Captcha plugin for Monstra' => 'Captcha плагин для Monstra', 'Captcha code is wrong' => 'Captcha код неправильный', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/captcha/languages/uk.lang.php b/plugins/captcha/languages/uk.lang.php index c1882a0..5233c47 100644 --- a/plugins/captcha/languages/uk.lang.php +++ b/plugins/captcha/languages/uk.lang.php @@ -5,5 +5,5 @@ 'Captcha' => 'Каптча', 'Captcha plugin for Monstra' => 'Каптча плагін для Monstra', 'Captcha code is wrong' => 'Код каптчі невірний', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/markitup/install/markitup.manifest.xml b/plugins/markitup/install/markitup.manifest.xml index 8dc191b..b8fde15 100644 --- a/plugins/markitup/install/markitup.manifest.xml +++ b/plugins/markitup/install/markitup.manifest.xml @@ -8,4 +8,4 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/markitup/markitup.plugin.php b/plugins/markitup/markitup.plugin.php index aeb7763..9a55fe8 100644 --- a/plugins/markitup/markitup.plugin.php +++ b/plugins/markitup/markitup.plugin.php @@ -1,51 +1,49 @@ + + + + + + + + '); + echo (''); + } - // Register plugin - Plugin::register( __FILE__, - __('MarkItUp!', 'markitup'), - __('MarkItUp! universal markup jQuery editor', 'markitup'), - '1.0.0', - 'Awilum', - 'http://monstra.org/'); - - - // Add hooks - Action::add('admin_header', 'MarkItUp::headers'); - - /** - * MarkItUp Class - */ - class MarkItUp { - - - /** - * Set editor headers - */ - public static function headers() { - echo (' - - - - - - - - - '); - - echo (''); - } - - } \ No newline at end of file +} diff --git a/plugins/sandbox/install/sandbox.install.php b/plugins/sandbox/install/sandbox.install.php index 8e6d6cf..c1b0047 100644 --- a/plugins/sandbox/install/sandbox.install.php +++ b/plugins/sandbox/install/sandbox.install.php @@ -1,5 +1,5 @@ 1.0.0 Awilum http://monstra.org/ - \ No newline at end of file + diff --git a/plugins/sandbox/install/sandbox.uninstall.php b/plugins/sandbox/install/sandbox.uninstall.php index ad47fc1..f7a8083 100644 --- a/plugins/sandbox/install/sandbox.uninstall.php +++ b/plugins/sandbox/install/sandbox.uninstall.php @@ -1,5 +1,5 @@ array( - 'Sandbox' => 'Sandbox', - 'Sandbox plugin for Monstra' => 'Sandbox Plugin für Monstra', - 'Sandbox template' => 'Sandbox Template', - 'Save' => 'Speichern', - ) - ); \ No newline at end of file + array( + 'Sandbox' => 'Sandbox', + 'Sandbox plugin for Monstra' => 'Sandbox Plugin für Monstra', + 'Sandbox template' => 'Sandbox Template', + 'Save' => 'Speichern', + ) + ); diff --git a/plugins/sandbox/languages/en.lang.php b/plugins/sandbox/languages/en.lang.php index c07df60..cd11228 100644 --- a/plugins/sandbox/languages/en.lang.php +++ b/plugins/sandbox/languages/en.lang.php @@ -6,5 +6,5 @@ 'Sandbox plugin for Monstra' => 'Sandbox plugin for Monstra', 'Sandbox template' => 'Sandbox template', 'Save' => 'Save', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/sandbox/languages/it.lang.php b/plugins/sandbox/languages/it.lang.php index 0125db0..ff5729a 100644 --- a/plugins/sandbox/languages/it.lang.php +++ b/plugins/sandbox/languages/it.lang.php @@ -7,4 +7,4 @@ 'Sandbox template' => 'Modello Sandbox', 'Save' => 'Salva', ) - ); \ No newline at end of file + ); diff --git a/plugins/sandbox/languages/lt.lang.php b/plugins/sandbox/languages/lt.lang.php index 029e148..817a5a3 100644 --- a/plugins/sandbox/languages/lt.lang.php +++ b/plugins/sandbox/languages/lt.lang.php @@ -6,5 +6,5 @@ 'Sandbox plugin for Monstra' => 'Sandbox papildinys', 'Sandbox template' => 'Sandbox šablonas', 'Save' => 'Išsaugoti', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/sandbox/languages/pt-br.lang.php b/plugins/sandbox/languages/pt-br.lang.php index 9642439..7cecfa9 100644 --- a/plugins/sandbox/languages/pt-br.lang.php +++ b/plugins/sandbox/languages/pt-br.lang.php @@ -6,5 +6,5 @@ 'Sandbox plugin for Monstra' => 'Plugin Caixa de Areia para o Monstra CMS', 'Sandbox template' => 'Template da caixa de areia', 'Save' => 'Salvar', - ) - ); \ No newline at end of file + ) + ); diff --git a/plugins/sandbox/languages/ru.lang.php b/plugins/sandbox/languages/ru.lang.php index cdc53ce..cc22cfd 100644 --- a/plugins/sandbox/languages/ru.lang.php +++ b/plugins/sandbox/languages/ru.lang.php @@ -7,4 +7,4 @@ 'Sandbox template' => 'Шаблон песочницы', 'Save' => 'Сохранить', ) - ); \ No newline at end of file + ); diff --git a/plugins/sandbox/languages/uk.lang.php b/plugins/sandbox/languages/uk.lang.php index ef55ee5..b368ca9 100644 --- a/plugins/sandbox/languages/uk.lang.php +++ b/plugins/sandbox/languages/uk.lang.php @@ -7,4 +7,4 @@ 'Sandbox template' => 'Шаблон пісочниці', 'Save' => 'Зберегти', ) - ); \ No newline at end of file + ); diff --git a/plugins/sandbox/sandbox.admin.php b/plugins/sandbox/sandbox.admin.php index 1c65a41..aaba825 100644 --- a/plugins/sandbox/sandbox.admin.php +++ b/plugins/sandbox/sandbox.admin.php @@ -1,95 +1,91 @@ -display(); + } + + } /** - * Sandbox admin class + * Form Component Save */ - class SandboxAdmin extends Backend { - - /** - * Main Sandbox admin function - */ - public static function main() { - - // - // Do something here... - // - - // Check for get actions - // ------------------------------------- - if (Request::get('action')) { - - // Switch actions - // ------------------------------------- - switch (Request::get('action')) { - - // Plugin action - // ------------------------------------- - case "add": - // - // Do something here... - // - break; - - // Plugin action - // ------------------------------------- - case "delete": - // - // Do something here... - // - break; - } - - } else { - - // Display view - View::factory('sandbox/views/backend/index')->display(); - } - - } - - - /** - * Form Component Save - */ - public static function formComponentSave() { - if (Request::post('sandbox_component_save')) { - if (Security::check(Request::post('csrf'))) { - Option::update('sandbox_template', Request::post('sandbox_form_template')); - Request::redirect('index.php?id=themes'); - } + public static function formComponentSave() + { + if (Request::post('sandbox_component_save')) { + if (Security::check(Request::post('csrf'))) { + Option::update('sandbox_template', Request::post('sandbox_form_template')); + Request::redirect('index.php?id=themes'); } } + } - - /** - * Form Component - */ - public static function formComponent() { - - $_templates = Themes::getTemplates(); - foreach($_templates as $template) { - $templates[basename($template, '.template.php')] = basename($template, '.template.php'); - } - - echo ( - Form::open(). - Form::hidden('csrf', Security::token()). - Form::label('sandbox_form_template', __('Sandbox template', 'sandbox')). - Form::select('sandbox_form_template', $templates, Option::get('sandbox_template')). - Html::br(). - Form::submit('sandbox_component_save', __('Save', 'sandbox'), array('class' => 'btn')). - Form::close() - ); + /** + * Form Component + */ + public static function formComponent() + { + $_templates = Themes::getTemplates(); + foreach ($_templates as $template) { + $templates[basename($template, '.template.php')] = basename($template, '.template.php'); } + echo ( + Form::open(). + Form::hidden('csrf', Security::token()). + Form::label('sandbox_form_template', __('Sandbox template', 'sandbox')). + Form::select('sandbox_form_template', $templates, Option::get('sandbox_template')). + Html::br(). + Form::submit('sandbox_component_save', __('Save', 'sandbox'), array('class' => 'btn')). + Form::close() + ); + } - } \ No newline at end of file +} diff --git a/plugins/sandbox/sandbox.plugin.php b/plugins/sandbox/sandbox.plugin.php index d2a8f6f..9f4a159 100644 --- a/plugins/sandbox/sandbox.plugin.php +++ b/plugins/sandbox/sandbox.plugin.php @@ -1,79 +1,82 @@ sitemap"> \ No newline at end of file + diff --git a/public/themes/default/footer.chunk.php b/public/themes/default/footer.chunk.php index b2d042d..7667a81 100644 --- a/public/themes/default/footer.chunk.php +++ b/public/themes/default/footer.chunk.php @@ -1,8 +1,8 @@
    -

    +

    -

    +

    @@ -10,8 +10,8 @@ - - + + diff --git a/public/themes/default/header.chunk.php b/public/themes/default/header.chunk.php index eba9284..fd401e4 100644 --- a/public/themes/default/header.chunk.php +++ b/public/themes/default/header.chunk.php @@ -3,21 +3,21 @@ <?php echo Site::name() . ' - ' . Site::title(); ?> - + - + - - - - - - - - - + + + + + + + + + @@ -59,4 +59,3 @@
    - diff --git a/public/themes/default/home.template.php b/public/themes/default/home.template.php index 72f67c1..54ad3dd 100644 --- a/public/themes/default/home.template.php +++ b/public/themes/default/home.template.php @@ -20,7 +20,7 @@
    -
    +
    @@ -30,5 +30,4 @@

    - - \ No newline at end of file +
    - - \ No newline at end of file + - \ No newline at end of file + diff --git a/storage/database/options.table.xml b/storage/database/options.table.xml index 04f32a3..ec2288e 100644 --- a/storage/database/options.table.xml +++ b/storage/database/options.table.xml @@ -1,2 +1,2 @@ -181527510b419sitenameMonstra25fe7b20ebbkeywordsSite keywords32996da0de2descriptionSite description44056d724b8sloganSite slogan5620d3e963edefaultpagehome66c9cd389f6siteurlhttp://example.org/72db8769b1etimezoneKwajalein8a0b440adcelanguageen9d7bd60ad05maintenance_statusoff10c415980d92maintenance_message<h1>Monstra :: Maintenance mode</h1>114c4e8f0aa8theme_site_namedefault124c4e8f0aa8theme_admin_namedefault124c4e8f0aa8users_frontend_registrationtrue18f469fc791ccaptcha_installedtrue +181527510b419sitenameSitename25fe7b20ebbkeywordsSite keywords32996da0de2descriptionSite description44056d724b8sloganSite slogan5620d3e963edefaultpagehome66c9cd389f6siteurlhttp://localhost/projects/monstra-cms/72db8769b1etimezoneKwajalein8a0b440adcelanguageen9d7bd60ad05maintenance_statusoff10c415980d92maintenance_message<h1>Monstra :: Maintenance mode</h1>114c4e8f0aa8theme_site_namedefault124c4e8f0aa8theme_admin_namedefault124c4e8f0aa8users_frontend_registrationtrue18f469fc791ccaptcha_installedtrue diff --git a/storage/database/users.table.xml b/storage/database/users.table.xml index 0d023b6..8a2106e 100644 --- a/storage/database/users.table.xml +++ b/storage/database/users.table.xml @@ -1,2 +1,2 @@ -0 \ No newline at end of file +1139f93e26b7admin5d1e3697d706b0e24e574b56e79affdaadmin@admin.comrMyy0lJ9LQe91357302731admin diff --git a/storage/snippets/google-analytics.snippet.php b/storage/snippets/google-analytics.snippet.php index 65567d0..d66069c 100644 --- a/storage/snippets/google-analytics.snippet.php +++ b/storage/snippets/google-analytics.snippet.php @@ -1 +1 @@ - \ No newline at end of file +