Пример #1
1
 function doModel()
 {
     switch ($this->action) {
         case 'login_post':
             //post execution for the login
             if (!osc_users_enabled()) {
                 osc_add_flash_error_message(_m('Users are not enabled'));
                 $this->redirectTo(osc_base_url());
             }
             osc_csrf_check();
             osc_run_hook('before_validating_login');
             // e-mail or/and password is/are empty or incorrect
             $wrongCredentials = false;
             $email = Params::getParam('email');
             $password = Params::getParam('password', false, false);
             if ($email == '') {
                 osc_add_flash_error_message(_m('Please provide an email address'));
                 $wrongCredentials = true;
             }
             if ($password == '') {
                 osc_add_flash_error_message(_m('Empty passwords are not allowed. Please provide a password'));
                 $wrongCredentials = true;
             }
             if ($wrongCredentials) {
                 $this->redirectTo(osc_user_login_url());
             }
             if (osc_validate_email($email)) {
                 $user = User::newInstance()->findByEmail($email);
             }
             if (empty($user)) {
                 $user = User::newInstance()->findByUsername($email);
             }
             if (empty($user)) {
                 osc_add_flash_error_message(_m("The user doesn't exist"));
                 $this->redirectTo(osc_user_login_url());
             }
             if (!osc_verify_password($password, isset($user['s_password']) ? $user['s_password'] : '')) {
                 osc_add_flash_error_message(_m('The password is incorrect'));
                 $this->redirectTo(osc_user_login_url());
                 // @TODO if valid user, send email parameter back to the login form
             } else {
                 if (@$user['s_password'] != '') {
                     if (preg_match('|\\$2y\\$([0-9]{2})\\$|', $user['s_password'], $cost)) {
                         if ($cost[1] != BCRYPT_COST) {
                             User::newInstance()->update(array('s_password' => osc_hash_password($password)), array('pk_i_id' => $user['pk_i_id']));
                         }
                     } else {
                         User::newInstance()->update(array('s_password' => osc_hash_password($password)), array('pk_i_id' => $user['pk_i_id']));
                     }
                 }
             }
             // e-mail or/and IP is/are banned
             $banned = osc_is_banned($email);
             // int 0: not banned or unknown, 1: email is banned, 2: IP is banned, 3: both email & IP are banned
             if ($banned & 1) {
                 osc_add_flash_error_message(_m('Your current email is not allowed'));
             }
             if ($banned & 2) {
                 osc_add_flash_error_message(_m('Your current IP is not allowed'));
             }
             if ($banned !== 0) {
                 $this->redirectTo(osc_user_login_url());
             }
             osc_run_hook('before_login');
             $url_redirect = osc_get_http_referer();
             $page_redirect = '';
             if (osc_rewrite_enabled()) {
                 if ($url_redirect != '') {
                     $request_uri = urldecode(preg_replace('@^' . osc_base_url() . '@', "", $url_redirect));
                     $tmp_ar = explode("?", $request_uri);
                     $request_uri = $tmp_ar[0];
                     $rules = Rewrite::newInstance()->listRules();
                     foreach ($rules as $match => $uri) {
                         if (preg_match('#' . $match . '#', $request_uri, $m)) {
                             $request_uri = preg_replace('#' . $match . '#', $uri, $request_uri);
                             if (preg_match('|([&?]{1})page=([^&]*)|', '&' . $request_uri . '&', $match)) {
                                 $page_redirect = $match[2];
                                 if ($page_redirect == '' || $page_redirect == 'login') {
                                     $url_redirect = osc_user_dashboard_url();
                                 }
                             }
                             break;
                         }
                     }
                 }
             }
             require_once LIB_PATH . 'osclass/UserActions.php';
             $uActions = new UserActions(false);
             $logged = $uActions->bootstrap_login($user['pk_i_id']);
             if ($logged == 0) {
                 osc_add_flash_error_message(_m("The user doesn't exist"));
             } else {
                 if ($logged == 1) {
                     if (time() - strtotime($user['dt_access_date']) > 1200) {
                         // EACH 20 MINUTES
                         osc_add_flash_error_message(sprintf(_m('The user has not been validated yet. Would you like to re-send your <a href="%s">activation?</a>'), osc_user_resend_activation_link($user['pk_i_id'], $user['s_email'])));
                     } else {
                         osc_add_flash_error_message(_m('The user has not been validated yet'));
                     }
                 } else {
                     if ($logged == 2) {
                         osc_add_flash_error_message(_m('The user has been suspended'));
                     } else {
                         if ($logged == 3) {
                             if (Params::getParam('remember') == 1) {
                                 //this include contains de osc_genRandomPassword function
                                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                                 $secret = osc_genRandomPassword();
                                 User::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $user['pk_i_id']));
                                 Cookie::newInstance()->set_expires(osc_time_cookie());
                                 Cookie::newInstance()->push('oc_userId', $user['pk_i_id']);
                                 Cookie::newInstance()->push('oc_userSecret', $secret);
                                 Cookie::newInstance()->set();
                             }
                             if ($url_redirect == '') {
                                 $url_redirect = osc_user_dashboard_url();
                             }
                             osc_run_hook("after_login", $user, $url_redirect);
                             $this->redirectTo(osc_apply_filter('correct_login_url_redirect', $url_redirect));
                         } else {
                             osc_add_flash_error_message(_m('This should never happen'));
                         }
                     }
                 }
             }
             if (!$user['b_enabled']) {
                 $this->redirectTo(osc_user_login_url());
             }
             $this->redirectTo(osc_user_login_url());
             break;
         case 'resend':
             $id = Params::getParam('id');
             $email = Params::getParam('email');
             $user = User::newInstance()->findByPrimaryKey($id);
             if ($id == '' || $email == '' || !isset($user) || $user['b_active'] == 1 || $email != $user['s_email']) {
                 osc_add_flash_error_message(_m('Incorrect link'));
                 $this->redirectTo(osc_user_login_url());
             }
             if (time() - strtotime($user['dt_access_date']) > 1200) {
                 // EACH 20 MINUTES
                 if (osc_notify_new_user()) {
                     osc_run_hook('hook_email_admin_new_user', $user);
                 }
                 if (osc_user_validation_enabled()) {
                     osc_run_hook('hook_email_user_validation', $user, $user);
                 }
                 User::newInstance()->update(array('dt_access_date' => date('Y-m-d H:i:s')), array('pk_i_id' => $user['pk_i_id']));
                 osc_add_flash_ok_message(_m('Validation email re-sent'));
             } else {
                 osc_add_flash_warning_message(_m('We have just sent you an email to validate your account, you will have to wait a few minutes to resend it again'));
             }
             $this->redirectTo(osc_user_login_url());
             break;
         case 'recover':
             //form to recover the password (in this case we have the form in /gui/)
             $this->doView('user-recover.php');
             break;
         case 'recover_post':
             //post execution to recover the password
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             // e-mail is incorrect
             if (!preg_match('|^[a-z0-9\\.\\_\\+\\-]+@[a-z0-9\\.\\-]+\\.[a-z]{2,3}$|i', Params::getParam('s_email'))) {
                 osc_add_flash_error_message(_m('Invalid email address'));
                 $this->redirectTo(osc_recover_user_password_url());
             }
             $userActions = new UserActions(false);
             $success = $userActions->recover_password();
             switch ($success) {
                 case 0:
                     // recover ok
                     osc_add_flash_ok_message(_m('We have sent you an email with the instructions to reset your password'));
                     $this->redirectTo(osc_base_url());
                     break;
                 case 1:
                     // e-mail does not exist
                     osc_add_flash_error_message(_m('We were not able to identify you given the information provided'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
                 case 2:
                     // recaptcha wrong
                     osc_add_flash_error_message(_m('The recaptcha code is wrong'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
             }
             break;
         case 'forgot':
             //form to recover the password (in this case we have the form in /gui/)
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user) {
                 $this->doView('user-forgot_password.php');
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'forgot_post':
             osc_csrf_check();
             if (Params::getParam('new_password', false, false) == '' || Params::getParam('new_password2', false, false) == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
             }
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user['b_enabled'] == 1) {
                 if (Params::getParam('new_password', false, false) == Params::getParam('new_password2', false, false)) {
                     User::newInstance()->update(array('s_pass_code' => osc_genRandomPassword(50), 's_pass_date' => date('Y-m-d H:i:s', 0), 's_pass_ip' => Params::getServerParam('REMOTE_ADDR'), 's_password' => osc_hash_password(Params::getParam('new_password', false, false))), array('pk_i_id' => $user['pk_i_id']));
                     osc_add_flash_ok_message(_m('The password has been changed'));
                     $this->redirectTo(osc_user_login_url());
                 } else {
                     osc_add_flash_error_message(_m("Error, the password don't match"));
                     $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
             }
             $this->redirectTo(osc_base_url());
             break;
         default:
             //login
             Session::newInstance()->_setReferer(osc_get_http_referer());
             if (osc_logged_user_id() != '') {
                 $this->redirectTo(osc_user_dashboard_url());
             }
             $this->doView('user-login.php');
     }
 }
Пример #2
0
 function doModel()
 {
     switch ($this->action) {
         case 'advanced':
             //calling the advanced settings view
             $this->doView('settings/advanced.php');
             break;
         case 'advanced_post':
             // updating advanced settings
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=advanced');
             }
             osc_csrf_check();
             $subdomain_type = Params::getParam('e_type');
             if (!in_array($subdomain_type, array('category', 'country', 'region', 'city', 'user'))) {
                 $subdomain_type = '';
             }
             $iUpdated = osc_set_preference('subdomain_type', $subdomain_type);
             $iUpdated += osc_set_preference('subdomain_host', Params::getParam('s_host'));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(_m("Advanced settings have been updated"), 'admin');
             }
             osc_calculate_location_slug(osc_subdomain_type());
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=advanced');
             break;
         case 'advanced_cache_flush':
             osc_cache_flush();
             osc_add_flash_ok_message(_m("Cache flushed correctly"), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=advanced');
             break;
     }
 }
Пример #3
0
 function __construct()
 {
     parent::__construct();
     // check if is moderator and can enter to this page
     if ($this->isModerator()) {
         if (!in_array($this->page, array('items', 'comments', 'media', 'login', 'admins', 'ajax', 'stats', ''))) {
             osc_add_flash_error_message(_m("You don't have enough permissions"), 'admin');
             $this->redirectTo(osc_admin_base_url());
         }
     }
     osc_run_hook('init_admin');
     // check if exist a new version each day
     if (time() - osc_last_version_check() > 24 * 3600) {
         $data = osc_file_get_contents('http://osclass.org/latest_version.php?callback=?');
         $data = preg_replace('|^\\?\\((.*?)\\);$|', '$01', $data);
         $json = json_decode($data);
         if ($json->version > osc_version()) {
             osc_set_preference('update_core_json', $data);
         } else {
             osc_set_preference('update_core_json', '');
         }
         osc_set_preference('last_version_check', time());
         osc_reset_preferences();
     }
     $config_version = str_replace('.', '', OSCLASS_VERSION);
     $config_version = preg_replace('|-.*|', '', $config_version);
     if ($config_version > Preference::newInstance()->get('version')) {
         if (get_class($this) == 'CAdminTools') {
         } else {
             if (get_class($this) != 'CAdminUpgrade') {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=upgrade');
             }
         }
     }
     // show messages subscribed
     $status_subscribe = Params::getParam('subscribe_osclass');
     if ($status_subscribe != '') {
         switch ($status_subscribe) {
             case -1:
                 osc_add_flash_error_message(_m('Entered an invalid email'), 'admin');
                 break;
             case 0:
                 osc_add_flash_warning_message(_m("You're already subscribed"), 'admin');
                 break;
             case 1:
                 osc_add_flash_ok_message(_m('Subscribed correctly'), 'admin');
                 break;
             default:
                 osc_add_flash_warning_message(_m("Error subscribing"), 'admin');
                 break;
         }
     }
     // show donation successful
     if (Params::getParam('donation') == 'successful') {
         osc_add_flash_ok_message(_m('Thank you very much for your donation'), 'admin');
     }
 }
Пример #4
0
 function doModel()
 {
     switch ($this->action) {
         case 'mailserver':
             // calling the mailserver view
             $this->doView('settings/mailserver.php');
             break;
         case 'mailserver_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver');
             }
             osc_csrf_check();
             // updating mailserver
             $iUpdated = 0;
             $mailserverAuth = Params::getParam('mailserver_auth');
             $mailserverAuth = $mailserverAuth != '' ? true : false;
             $mailserverPop = Params::getParam('mailserver_pop');
             $mailserverPop = $mailserverPop != '' ? true : false;
             $mailserverType = Params::getParam('mailserver_type');
             $mailserverHost = Params::getParam('mailserver_host');
             $mailserverPort = Params::getParam('mailserver_port');
             $mailserverUsername = Params::getParam('mailserver_username');
             $mailserverPassword = Params::getParam('mailserver_password', false, false);
             $mailserverSsl = Params::getParam('mailserver_ssl');
             $mailserverMailFrom = Params::getParam('mailserver_mail_from');
             $mailserverNameFrom = Params::getParam('mailserver_name_from');
             if (!in_array($mailserverType, array('custom', 'gmail'))) {
                 osc_add_flash_error_message(_m('Mail server type is incorrect'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver');
             }
             $iUpdated += osc_set_preference('mailserver_auth', $mailserverAuth);
             $iUpdated += osc_set_preference('mailserver_pop', $mailserverPop);
             $iUpdated += osc_set_preference('mailserver_type', $mailserverType);
             $iUpdated += osc_set_preference('mailserver_host', $mailserverHost);
             $iUpdated += osc_set_preference('mailserver_port', $mailserverPort);
             $iUpdated += osc_set_preference('mailserver_username', $mailserverUsername);
             $iUpdated += osc_set_preference('mailserver_password', $mailserverPassword);
             $iUpdated += osc_set_preference('mailserver_ssl', $mailserverSsl);
             $iUpdated += osc_set_preference('mailserver_mail_from', $mailserverMailFrom);
             $iUpdated += osc_set_preference('mailserver_name_from', $mailserverNameFrom);
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(_m('Mail server configuration has changed'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver');
             break;
     }
 }
Пример #5
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add':
             $this->doView("plugins/add.php");
             break;
         case 'add_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             }
             $package = Params::getFiles("package");
             if (isset($package['size']) && $package['size'] != 0) {
                 $path = osc_plugins_path();
                 (int) ($status = osc_unzip_file($package['tmp_name'], $path));
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The plugin folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     $msg = _m('The plugin has been uploaded correctly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_error_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=plugins&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the plugin');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'install':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             }
             $pn = Params::getParam('plugin');
             // set header just in case it's triggered some fatal error
             header("Location: " . osc_admin_base_url(true) . "?page=plugins&error=" . $pn, true, '302');
             $installed = Plugins::install($pn);
             if (is_array($installed)) {
                 switch ($installed['error_code']) {
                     case 'error_output':
                         osc_add_flash_error_message(sprintf(_m('The plugin generated %d characters of <strong>unexpected output</strong> during the installation'), strlen($installed['output'])), 'admin');
                         break;
                     case 'error_installed':
                         osc_add_flash_error_message(_m('Plugin is already installed'), 'admin');
                         break;
                     case 'error_file':
                         osc_add_flash_error_message(_m("Plugin couldn't be installed because their files are missing"), 'admin');
                         break;
                     case 'custom_error':
                         osc_add_flash_error_message(sprintf(_m("Plugin couldn't be installed because of: %s"), $installed['msg']), 'admin');
                         break;
                     default:
                         osc_add_flash_error_message(_m("Plugin couldn't be installed"), 'admin');
                         break;
                 }
             } else {
                 osc_add_flash_ok_message(_m('Plugin installed'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             break;
         case 'uninstall':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             }
             if (Plugins::uninstall(Params::getParam("plugin"))) {
                 osc_add_flash_ok_message(_m('Plugin uninstalled'), 'admin');
             } else {
                 osc_add_flash_error_message(_m("Plugin couldn't be uninstalled"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             break;
         case 'enable':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             }
             if (Plugins::activate(Params::getParam('plugin'))) {
                 osc_add_flash_ok_message(_m('Plugin enabled'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('Plugin is already enabled'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             break;
         case 'disable':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             }
             if (Plugins::deactivate(Params::getParam('plugin'))) {
                 osc_add_flash_ok_message(_m('Plugin disabled'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('Plugin is already disabled'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             break;
         case 'admin':
             $plugin = Params::getParam("plugin");
             if ($plugin != "") {
                 Plugins::runHook($plugin . '_configure');
             }
             break;
         case 'admin_post':
             Plugins::runHook('admin_post');
         case 'renderplugin':
             $file = Params::getParam("file");
             if ($file != "") {
                 // We pass the GET variables (in case we have somes)
                 if (preg_match('|(.+?)\\?(.*)|', $file, $match)) {
                     $file = $match[1];
                     if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) {
                         for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) {
                             //$_GET[$get_vars[1][$var_k]] = $get_vars[2][$var_k];
                             //$_REQUEST[$get_vars[1][$var_k]] = $get_vars[2][$var_k];
                             Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]);
                         }
                     }
                 } else {
                     $file = $_REQUEST['file'];
                 }
                 $this->_exportVariableToView("file", osc_plugins_path() . $file);
                 //osc_renderPluginView($file);
                 $this->doView("plugins/view.php");
             }
             break;
         case 'render':
             $file = Params::getParam("file");
             if ($file != "") {
                 // We pass the GET variables (in case we have somes)
                 if (preg_match('|(.+?)\\?(.*)|', $file, $match)) {
                     $file = $match[1];
                     if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) {
                         for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) {
                             Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]);
                         }
                     }
                 } else {
                     $file = $_REQUEST['file'];
                 }
                 $this->_exportVariableToView("file", ABS_PATH . $file);
                 $this->doView("theme/view.php");
             }
             break;
         case 'configure':
             $plugin = Params::getParam("plugin");
             if ($plugin != '') {
                 $plugin_data = Plugins::getInfo($plugin);
                 $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll());
                 $this->_exportVariableToView("selected", PluginCategory::newInstance()->listSelected($plugin_data['short_name']));
                 $this->_exportVariableToView("plugin_data", $plugin_data);
                 $this->doView("plugins/configuration.php");
             } else {
                 $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             }
             break;
         case 'configure_post':
             $plugin_short_name = Params::getParam("plugin_short_name");
             $categories = Params::getParam("categories");
             if ($plugin_short_name != "") {
                 Plugins::cleanCategoryFromPlugin($plugin_short_name);
                 if (isset($categories)) {
                     Plugins::addToCategoryPlugin($categories, $plugin_short_name);
                 }
             } else {
                 osc_add_flash_error_message(_m('No plugin selected'), 'admin');
                 $this->doView("plugins/index.php");
             }
             osc_add_flash_ok_message(_m('Configuration was saved'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'error_plugin':
             // force php errors and simulate plugin installation to show the errors in the iframe
             if (!OSC_DEBUG) {
                 error_reporting(E_ALL | E_STRICT);
             }
             @ini_set('display_errors', 1);
             include osc_plugins_path() . Params::getParam('plugin');
             Plugins::install(Params::getParam('plugin'));
             exit;
             break;
         default:
             $this->_exportVariableToView("plugins", Plugins::listAll());
             $this->doView("plugins/index.php");
     }
 }
Пример #6
0
 function doModel()
 {
     switch ($this->action) {
         case 'dashboard':
             //dashboard...
             $max_items = Params::getParam('max_items') != '' ? Params::getParam('max_items') : 5;
             $aItems = Item::newInstance()->findByUserIDEnabled(osc_logged_user_id(), 0, $max_items);
             //calling the view...
             $this->_exportVariableToView('items', $aItems);
             $this->_exportVariableToView('max_items', $max_items);
             $this->doView('user-dashboard.php');
             break;
         case 'profile':
             //profile...
             $user = User::newInstance()->findByPrimaryKey(osc_logged_user_id());
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($user['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->findByCountry($user['fk_c_country_code']);
             } elseif (count($aCountries) > 0) {
                 $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
             }
             $aCities = array();
             if ($user['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->findByRegion($user['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
                 }
             }
             //calling the view...
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('user', $user);
             $this->_exportVariableToView('locales', OSCLocale::newInstance()->listAllEnabled());
             $this->doView('user-profile.php');
             break;
         case 'profile_post':
             //profile post...
             osc_csrf_check();
             $userId = Session::newInstance()->_get('userId');
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(false);
             $success = $userActions->edit($userId);
             if ($success == 1 || $success == 2) {
                 osc_add_flash_ok_message(_m('Your profile has been updated successfully'));
             } else {
                 osc_add_flash_error_message($success);
             }
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'alerts':
             //alerts
             $aAlerts = Alerts::newInstance()->findByUser(Session::newInstance()->_get('userId'), false);
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             foreach ($aAlerts as $k => $a) {
                 $array_conditions = (array) json_decode($a['s_search']);
                 //                                            $search = Search::newInstance();
                 $search = new Search();
                 $search->setJsonAlert($array_conditions);
                 $search->limit(0, 3);
                 $aAlerts[$k]['items'] = $search->doSearch();
             }
             $this->_exportVariableToView('alerts', $aAlerts);
             View::newInstance()->_reset('alerts');
             $this->_exportVariableToView('user', $user);
             $this->doView('user-alerts.php');
             break;
         case 'change_email':
             //change email
             $this->doView('user-change_email.php');
             break;
         case 'change_email_post':
             //change email post
             osc_csrf_check();
             if (!osc_validate_email(Params::getParam('new_email'))) {
                 osc_add_flash_error_message(_m('The specified e-mail is not valid'));
                 $this->redirectTo(osc_change_user_email_url());
             } else {
                 $user = User::newInstance()->findByEmail(Params::getParam('new_email'));
                 if (!isset($user['pk_i_id'])) {
                     $userEmailTmp = array();
                     $userEmailTmp['fk_i_user_id'] = Session::newInstance()->_get('userId');
                     $userEmailTmp['s_new_email'] = Params::getParam('new_email');
                     UserEmailTmp::newInstance()->insertOrUpdate($userEmailTmp);
                     $code = osc_genRandomPassword(30);
                     $date = date('Y-m-d H:i:s');
                     $userManager = new User();
                     $userManager->update(array('s_pass_code' => $code, 's_pass_date' => $date, 's_pass_ip' => $_SERVER['REMOTE_ADDR']), array('pk_i_id' => Session::newInstance()->_get('userId')));
                     $validation_url = osc_change_user_email_confirm_url(Session::newInstance()->_get('userId'), $code);
                     osc_run_hook('hook_email_new_email', Params::getParam('new_email'), $validation_url);
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('The specified e-mail is already in use'));
                     $this->redirectTo(osc_change_user_email_url());
                 }
             }
             break;
         case 'change_username':
             //change username
             $this->doView('user-change_username.php');
             break;
         case 'change_username_post':
             //change username
             $username = osc_sanitize_username(Params::getParam('s_username'));
             osc_run_hook('before_username_change', Session::newInstance()->_get('userId'), $username);
             if ($username != '') {
                 $user = User::newInstance()->findByUsername($username);
                 if (isset($user['s_username'])) {
                     osc_add_flash_error_message(_m('The specified username is already in use'));
                 } else {
                     if (!osc_is_username_blacklisted($username)) {
                         User::newInstance()->update(array('s_username' => $username), array('pk_i_id' => Session::newInstance()->_get('userId')));
                         osc_add_flash_ok_message(_m('The username was updated'));
                         osc_run_hook('after_username_change', Session::newInstance()->_get('userId'), Params::getParam('s_username'));
                         $this->redirectTo(osc_user_profile_url());
                     } else {
                         osc_add_flash_error_message(_m('The specified username is not valid, it contains some invalid words'));
                     }
                 }
             } else {
                 osc_add_flash_error_message(_m('The specified username could not be empty'));
             }
             $this->redirectTo(osc_change_user_username_url());
             break;
         case 'change_password':
             //change password
             $this->doView('user-change_password.php');
             break;
         case 'change_password_post':
             //change password post
             osc_csrf_check();
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             if (Params::getParam('password', false, false) == '' || Params::getParam('new_password', false, false) == '' || Params::getParam('new_password2', false, false) == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (!osc_verify_password(Params::getParam('password', false, false), $user['s_password'])) {
                 osc_add_flash_error_message(_m("Current password doesn't match"));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (!Params::getParam('new_password', false, false)) {
                 osc_add_flash_error_message(_m("Passwords can't be empty"));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (Params::getParam('new_password', false, false) != Params::getParam('new_password2', false, false)) {
                 osc_add_flash_error_message(_m("Passwords don't match"));
                 $this->redirectTo(osc_change_user_password_url());
             }
             User::newInstance()->update(array('s_password' => osc_hash_password(Params::getParam('new_password', false, false))), array('pk_i_id' => Session::newInstance()->_get('userId')));
             osc_add_flash_ok_message(_m('Password has been changed'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'items':
             // view items user
             $itemsPerPage = Params::getParam('itemsPerPage') != '' ? Params::getParam('itemsPerPage') : 10;
             $page = Params::getParam('iPage') > 0 ? Params::getParam('iPage') - 1 : 0;
             $itemType = Params::getParam('itemType');
             $total_items = Item::newInstance()->countItemTypesByUserID(osc_logged_user_id(), $itemType);
             $total_pages = ceil($total_items / $itemsPerPage);
             $items = Item::newInstance()->findItemTypesByUserID(osc_logged_user_id(), $page * $itemsPerPage, $itemsPerPage, $itemType);
             $this->_exportVariableToView('items', $items);
             $this->_exportVariableToView('search_total_pages', $total_pages);
             $this->_exportVariableToView('search_total_items', $total_items);
             $this->_exportVariableToView('items_per_page', $itemsPerPage);
             $this->_exportVariableToView('items_type', $itemType);
             $this->_exportVariableToView('search_page', $page);
             $this->doView('user-items.php');
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $result = 0;
             if ($email != '' && $secret != '') {
                 $result = Alerts::newInstance()->activate($email, $secret);
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Oops! There was a problem trying to activate your alert. Please contact an administrator'));
             }
             $this->redirectTo(osc_base_url());
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $alert = Alerts::newInstance()->findByPrimaryKey($id);
             $result = 0;
             if (!empty($alert)) {
                 if ($email == $alert['s_email'] && $secret == $alert['s_secret']) {
                     $result = Alerts::newInstance()->unsub($id);
                 }
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Oops! There was a problem trying to unsubscribe you. Please contact an administrator'));
             }
             $this->redirectTo(osc_user_alerts_url());
             break;
         case 'delete':
             $id = Params::getParam('id');
             $secret = Params::getParam('secret');
             if (osc_is_web_user_logged_in()) {
                 $user = User::newInstance()->findByPrimaryKey(osc_logged_user_id());
                 View::newInstance()->_exportVariableToView('user', $user);
                 if (!empty($user) && osc_logged_user_id() == $id && $secret == $user['s_secret']) {
                     User::newInstance()->deleteUser(osc_logged_user_id());
                     Session::newInstance()->_drop('userId');
                     Session::newInstance()->_drop('userName');
                     Session::newInstance()->_drop('userEmail');
                     Session::newInstance()->_drop('userPhone');
                     Cookie::newInstance()->pop('oc_userId');
                     Cookie::newInstance()->pop('oc_userSecret');
                     Cookie::newInstance()->set();
                     osc_add_flash_ok_message(_m("Your account have been deleted"));
                     $this->redirectTo(osc_base_url());
                 } else {
                     osc_add_flash_error_message(_m("Oops! you can not do that"));
                     $this->redirectTo(osc_user_dashboard_url());
                 }
             } else {
                 osc_add_flash_error_message(_m("Oops! you can not do that"));
                 $this->redirectTo(osc_base_url());
             }
             break;
     }
 }
Пример #7
0
 function doModel()
 {
     switch ($this->action) {
         case 'login_post':
             //post execution for the login
             if (!osc_users_enabled()) {
                 osc_add_flash_error_message(_m('Users are not enabled'));
                 $this->redirectTo(osc_base_url());
             }
             require_once LIB_PATH . 'osclass/UserActions.php';
             $user = User::newInstance()->findByEmail(Params::getParam('email'));
             $url_redirect = osc_user_dashboard_url();
             $page_redirect = '';
             if (osc_rewrite_enabled()) {
                 if (isset($_SERVER['HTTP_REFERER'])) {
                     $request_uri = urldecode(preg_replace('@^' . osc_base_url() . '@', "", $_SERVER['HTTP_REFERER']));
                     $tmp_ar = explode("?", $request_uri);
                     $request_uri = $tmp_ar[0];
                     $rules = Rewrite::newInstance()->listRules();
                     foreach ($rules as $match => $uri) {
                         if (preg_match('#' . $match . '#', $request_uri, $m)) {
                             $request_uri = preg_replace('#' . $match . '#', $uri, $request_uri);
                             if (preg_match('|([&?]{1})page=([^&]*)|', '&' . $request_uri . '&', $match)) {
                                 $page_redirect = $match[2];
                             }
                             break;
                         }
                     }
                 }
             } else {
                 if (preg_match('|[\\?&]page=([^&]+)|', $_SERVER['HTTP_REFERER'] . '&', $match)) {
                     $page_redirect = $match[1];
                 }
             }
             if (Params::getParam('http_referer') != '') {
                 Session::newInstance()->_setReferer(Params::getParam('http_referer'));
                 $url_redirect = Params::getParam('http_referer');
             } else {
                 if (Session::newInstance()->_getReferer() != '') {
                     Session::newInstance()->_setReferer(Session::newInstance()->_getReferer());
                     $url_redirect = Session::newInstance()->_getReferer();
                 } else {
                     if ($page_redirect != '' && $page_redirect != 'login') {
                         Session::newInstance()->_setReferer($_SERVER['HTTP_REFERER']);
                         $url_redirect = $_SERVER['HTTP_REFERER'];
                     }
                 }
             }
             if (!$user) {
                 osc_add_flash_error_message(_m('The username doesn\'t exist'));
                 $this->redirectTo(osc_user_login_url());
             }
             if ($user["s_password"] != sha1(Params::getParam('password'))) {
                 osc_add_flash_error_message(_m('The password is incorrect'));
                 $this->redirectTo(osc_user_login_url());
             }
             $uActions = new UserActions(false);
             $logged = $uActions->bootstrap_login($user['pk_i_id']);
             if ($logged == 0) {
                 osc_add_flash_error_message(_m('The username doesn\'t exist'));
             } else {
                 if ($logged == 1) {
                     osc_add_flash_error_message(_m('The user has not been validated yet'));
                 } else {
                     if ($logged == 2) {
                         osc_add_flash_error_message(_m('The user has been suspended'));
                     } else {
                         if ($logged == 3) {
                             if (Params::getParam('remember') == 1) {
                                 //this include contains de osc_genRandomPassword function
                                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                                 $secret = osc_genRandomPassword();
                                 User::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $user['pk_i_id']));
                                 Cookie::newInstance()->set_expires(osc_time_cookie());
                                 Cookie::newInstance()->push('oc_userId', $user['pk_i_id']);
                                 Cookie::newInstance()->push('oc_userSecret', $secret);
                                 Cookie::newInstance()->set();
                             }
                             $this->redirectTo($url_redirect);
                         } else {
                             osc_add_flash_error_message(_m('This should never happens'));
                         }
                     }
                 }
             }
             if (!$user['b_enabled']) {
                 $this->redirectTo(osc_user_login_url());
             }
             $this->redirectTo(osc_user_login_url());
             break;
         case 'recover':
             //form to recover the password (in this case we have the form in /gui/)
             $this->doView('user-recover.php');
             break;
         case 'recover_post':
             //post execution to recover the password
             require_once LIB_PATH . 'osclass/UserActions.php';
             // e-mail is incorrect
             if (!preg_match('|^[a-z0-9\\.\\_\\+\\-]+@[a-z0-9\\.\\-]+\\.[a-z]{2,3}$|i', Params::getParam('s_email'))) {
                 osc_add_flash_error_message(_m('Invalid email address'));
                 $this->redirectTo(osc_recover_user_password_url());
             }
             $userActions = new UserActions(false);
             $success = $userActions->recover_password();
             switch ($success) {
                 case 0:
                     // recover ok
                     osc_add_flash_ok_message(_m('We have sent you an email with the instructions to reset your password'));
                     $this->redirectTo(osc_base_url());
                     break;
                 case 1:
                     // e-mail does not exist
                     osc_add_flash_error_message(_m('We were not able to identify you given the information provided'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
                 case 2:
                     // recaptcha wrong
                     osc_add_flash_error_message(_m('The recaptcha code is wrong'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
             }
             break;
         case 'forgot':
             //form to recover the password (in this case we have the form in /gui/)
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user) {
                 $this->doView('user-forgot_password.php');
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'forgot_post':
             if (Params::getParam('new_password') == '' || Params::getParam('new_password2') == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
             }
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user['b_enabled'] == 1) {
                 if (Params::getParam('new_password') == Params::getParam('new_password2')) {
                     User::newInstance()->update(array('s_pass_code' => osc_genRandomPassword(50), 's_pass_date' => date('Y-m-d H:i:s', 0), 's_pass_ip' => $_SERVER['REMOTE_ADDR'], 's_password' => sha1(Params::getParam('new_password'))), array('pk_i_id' => $user['pk_i_id']));
                     osc_add_flash_ok_message(_m('The password has been changed'));
                     $this->redirectTo(osc_user_login_url());
                 } else {
                     osc_add_flash_error_message(_m('Error, the password don\'t match'));
                     $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
             }
             $this->redirectTo(osc_base_url());
             break;
         default:
             //login
             if (osc_logged_user_id() != '') {
                 $this->redirectTo(osc_user_dashboard_url());
             }
             $this->doView('user-login.php');
     }
 }
Пример #8
0
 public static function ajaxPayment()
 {
     $status = self::processPayment();
     $data = payment_get_custom(Params::getParam('extra'));
     $product_type = explode('x', $data['product']);
     if ($status == PAYMENT_COMPLETED) {
         osc_add_flash_ok_message(sprintf(__('Success! Please write down this transaction ID in case you have any problem: %s', 'payment'), Params::getParam('stripe_transaction_id')));
         if ($product_type[0] == 101) {
             $item = Item::newInstance()->findByPrimaryKey($product_type[2]);
             $category = Category::newInstance()->findByPrimaryKey($item['fk_i_category_id']);
             View::newInstance()->_exportVariableToView('category', $category);
             payment_js_redirect_to(osc_search_category_url());
         } else {
             if ($product_type[0] == 201) {
                 if (osc_is_web_user_logged_in()) {
                     payment_js_redirect_to(osc_route_url('payment-user-menu'));
                 } else {
                     View::newInstance()->_exportVariableToView('item', Item::newInstance()->findByPrimaryKey($product_type[2]));
                     payment_js_redirect_to(osc_item_url());
                 }
             } else {
                 if (osc_is_web_user_logged_in()) {
                     payment_js_redirect_to(osc_route_url('payment-user-pack'));
                 } else {
                     // THIS SHOULD NOT HAPPEN
                     payment_js_redirect_to(osc_base_path());
                 }
             }
         }
     } else {
         if ($status == PAYMENT_ALREADY_PAID) {
             osc_add_flash_warning_message(__('Warning! This payment was already paid', 'payment'));
         } else {
             osc_add_flash_error_message(_e('There were an error processing your payment', 'payment'));
         }
         if ($product_type[0] == 301) {
             if (osc_is_web_user_logged_in()) {
                 payment_js_redirect_to(osc_route_url('payment-user-pack'));
             } else {
                 // THIS SHOULD NOT HAPPEN
                 payment_js_redirect_to(osc_base_path());
             }
         } else {
             if (osc_is_web_user_logged_in()) {
                 payment_js_redirect_to(osc_route_url('payment-user-menu'));
             } else {
                 View::newInstance()->_exportVariableToView('item', Item::newInstance()->findByPrimaryKey($product_type[2]));
                 payment_js_redirect_to(osc_item_url());
             }
         }
     }
 }
Пример #9
0
 function doModel()
 {
     switch ($this->action) {
         case 'logout':
             // unset only the required parameters in Session
             osc_run_hook('logout_admin');
             $this->logout();
             $this->redirectTo(osc_admin_base_url(true));
             break;
         default:
             //default dashboard page (main page at oc-admin)
             $this->_exportVariableToView("numItemsPerCategory", osc_get_non_empty_categories());
             $this->_exportVariableToView("numUsers", User::newInstance()->count());
             $this->_exportVariableToView("numItems", Item::newInstance()->count());
             // stats
             $items = array();
             $stats_items = Stats::newInstance()->new_items_count(date('Y-m-d H:i:s', mktime(0, 0, 0, date("m"), date("d") - 10, date("Y"))), 'day');
             for ($k = 10; $k >= 0; $k--) {
                 $items[date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - $k, date("Y")))] = 0;
             }
             foreach ($stats_items as $item) {
                 $items[$item['d_date']] = $item['num'];
             }
             $users = array();
             $stats_users = Stats::newInstance()->new_users_count(date('Y-m-d H:i:s', mktime(0, 0, 0, date("m"), date("d") - 10, date("Y"))), 'day');
             for ($k = 10; $k >= 0; $k--) {
                 $users[date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - $k, date("Y")))] = 0;
             }
             foreach ($stats_users as $user) {
                 $users[$user['d_date']] = $user['num'];
             }
             if (function_exists('disk_free_space')) {
                 $freedisk = @disk_free_space(osc_uploads_path());
                 if ($freedisk !== false && $freedisk < 52428800) {
                     //52428800 = 50*1024*1024
                     osc_add_flash_error_message(_m('You have very few free space left, users will not be able to upload pictures'), 'admin');
                 }
             }
             // show messages subscribed
             $status_subscribe = Params::getParam('subscribe_osclass');
             if ($status_subscribe != '') {
                 switch ($status_subscribe) {
                     case -1:
                         osc_add_flash_error_message(_m('Entered an invalid email'), 'admin');
                         break;
                     case 0:
                         osc_add_flash_warning_message(_m("You're already subscribed"), 'admin');
                         break;
                     case 1:
                         osc_add_flash_ok_message(_m('Subscribed correctly'), 'admin');
                         break;
                     default:
                         osc_add_flash_warning_message(_m("Error subscribing"), 'admin');
                         break;
                 }
             }
             $this->_exportVariableToView("item_stats", $items);
             $this->_exportVariableToView("user_stats", $users);
             //calling the view...
             $this->doView('main/index.php');
     }
 }
Пример #10
0
 function doModel()
 {
     parent::doModel();
     switch ($this->action) {
         case 'import':
             // calling import view
             $this->doView('tools/import.php');
             break;
         case 'import_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import');
             }
             // calling
             $sql = Params::getFiles('sql');
             if (isset($sql['size']) && $sql['size'] != 0) {
                 $content_file = file_get_contents($sql['tmp_name']);
                 $conn = DBConnectionClass::newInstance();
                 $c_db = $conn->getOsclassDb();
                 $comm = new DBCommandClass($c_db);
                 if ($comm->importSQL($content_file)) {
                     osc_add_flash_ok_message(_m('Import complete'), 'admin');
                 } else {
                     osc_add_flash_error_message(_m('There was a problem importing data to the database'), 'admin');
                 }
             } else {
                 osc_add_flash_warning_message(_m('No file was uploaded'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import');
             break;
         case 'images':
             // calling images view
             $this->doView('tools/images.php');
             break;
         case 'images_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images');
             }
             $preferences = Preference::newInstance()->toArray();
             $wat = new Watermark();
             $aResources = ItemResource::newInstance()->getAllResources();
             foreach ($aResources as $resource) {
                 osc_run_hook('regenerate_image', $resource);
                 $path = osc_content_path() . 'uploads/';
                 // comprobar que no haya original
                 $img_original = $path . $resource['pk_i_id'] . "_original*";
                 $aImages = glob($img_original);
                 // there is original image
                 if (count($aImages) == 1) {
                     $image_tmp = $aImages[0];
                 } else {
                     $img_normal = $path . $resource['pk_i_id'] . ".*";
                     $aImages = glob($img_normal);
                     if (count($aImages) == 1) {
                         $image_tmp = $aImages[0];
                     } else {
                         $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*";
                         $aImages = glob($img_thumbnail);
                         $image_tmp = $aImages[0];
                     }
                 }
                 // extension
                 preg_match('/\\.(.*)$/', $image_tmp, $matches);
                 if (isset($matches[1])) {
                     $extension = $matches[1];
                     // Create normal size
                     $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg';
                     $size = explode('x', osc_normal_dimensions());
                     ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path);
                     if (osc_is_watermark_text()) {
                         $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg');
                     } elseif (osc_is_watermark_image()) {
                         $wat->doWatermarkImage($path, 'image/jpeg');
                     }
                     // Create preview
                     $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg';
                     $size = explode('x', osc_preview_dimensions());
                     ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                     // Create thumbnail
                     $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg';
                     $size = explode('x', osc_thumbnail_dimensions());
                     ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                     // update resource info
                     ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id']));
                     osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id']));
                     // si extension es direfente a jpg, eliminar las imagenes con $extension si hay
                     if ($extension != 'jpg') {
                         $files_to_remove = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "*" . $extension;
                         $fs = glob($files_to_remove);
                         if (is_array($fs)) {
                             array_map("unlink", $fs);
                         }
                     }
                     // ....
                 } else {
                     // no es imagen o imagen sin extesión
                 }
             }
             osc_add_flash_ok_message(_m('Re-generation complete'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images');
             break;
         case 'category':
             $this->doView('tools/category.php');
             break;
         case 'category_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=category');
             }
             osc_update_cat_stats();
             osc_add_flash_ok_message(_m("Recount category stats has been successful"), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=category');
             break;
         case 'locations':
             $this->doView('tools/locations.php');
             break;
         case 'locations_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=locations');
             }
             $workToDo = LocationsTmp::newInstance()->count();
             if ($workToDo > 0) {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=locations');
                 break;
             }
             // we need populate location tmp table
             $aCountry = Country::newInstance()->listAll();
             foreach ($aCountry as $country) {
                 $aRegionsCountry = Region::newInstance()->getByCountry($country['pk_c_code']);
                 LocationsTmp::newInstance()->insert(array('id_location' => $country['pk_c_code'], 'e_type' => 'COUNTRY'));
                 foreach ($aRegionsCountry as $region) {
                     $aCitiesRegion = City::newInstance()->getByRegion($region['pk_i_id']);
                     LocationsTmp::newInstance()->insert(array('id_location' => $region['pk_i_id'], 'e_type' => 'REGION'));
                     foreach ($aCitiesRegion as $city) {
                         LocationsTmp::newInstance()->insert(array('id_location' => $city['pk_i_id'], 'e_type' => 'CITY'));
                     }
                     unset($aCitiesRegion);
                 }
                 unset($aRegionsCountry);
             }
             unset($aCountry);
             $workToDo = LocationsTmp::newInstance()->count();
             Preference::newInstance()->replace('location_todo', $workToDo);
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=locations');
             break;
         case 'upgrade':
             $this->doView('tools/upgrade.php');
             break;
         case 'backup':
             $this->doView('tools/backup.php');
             break;
         case 'backup-sql':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             }
             //databasse dump...
             if (Params::getParam('bck_dir') != '') {
                 $path = trim(Params::getParam('bck_dir'));
                 if (substr($path, -1, 1) != "/") {
                     $path .= '/';
                 }
             } else {
                 $path = osc_base_path();
             }
             $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql';
             switch (osc_dbdump($path, $filename)) {
                 case -1:
                     $msg = _m('Path is empty');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -2:
                     $msg = sprintf(_m('Could not connect with the database. Error: %s'), mysql_error());
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -3:
                     $msg = _m('There are no tables to back up');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -4:
                     $msg = _m('The folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 default:
                     $msg = _m('Backup completed successfully');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             break;
         case 'backup-sql_file':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             }
             //databasse dump...
             $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql';
             $path = sys_get_temp_dir() . "/";
             switch (osc_dbdump($path, $filename)) {
                 case -1:
                     $msg = _m('Path is empty');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -2:
                     $msg = sprintf(_m('Could not connect with the database. Error: %s'), mysql_error());
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -3:
                     $msg = sprintf(_m('Could not select the database. Error: %s'), mysql_error());
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -4:
                     $msg = _m('There are no tables to back up');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -5:
                     $msg = _m('The folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 default:
                     $msg = _m('Backup completed successfully');
                     osc_add_flash_ok_message($msg, 'admin');
                     header('Content-Description: File Transfer');
                     header('Content-Type: application/octet-stream');
                     header('Content-Disposition: attachment; filename=' . basename($filename));
                     header('Content-Transfer-Encoding: binary');
                     header('Expires: 0');
                     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                     header('Pragma: public');
                     header('Content-Length: ' . filesize($path . $filename));
                     flush();
                     readfile($path . $filename);
                     exit;
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             break;
         case 'backup-zip_file':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             }
             $filename = "OSClass_backup." . date('YmdHis') . ".zip";
             $path = sys_get_temp_dir() . "/";
             if (osc_zip_folder(osc_base_path(), $path . $filename)) {
                 $msg = _m('Archived successfully!');
                 osc_add_flash_ok_message($msg, 'admin');
                 header('Content-Description: File Transfer');
                 header('Content-Type: application/octet-stream');
                 header('Content-Disposition: attachment; filename=' . basename($filename));
                 header('Content-Transfer-Encoding: binary');
                 header('Expires: 0');
                 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                 header('Pragma: public');
                 header('Content-Length: ' . filesize($path . $filename));
                 flush();
                 readfile($path . $filename);
                 exit;
             } else {
                 $msg = _m('Error, the zip file was not created in the specified directory');
                 osc_add_flash_error_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             break;
         case 'backup-zip':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             }
             //zip of the code just to back it up
             if (Params::getParam('bck_dir') != '') {
                 $archive_name = trim(Params::getParam('bck_dir'));
                 if (substr(trim($archive_name), -1, 1) != "/") {
                     $archive_name .= '/';
                 }
                 $archive_name = Params::getParam('bck_dir') . '/OSClass_backup.' . date('YmdHis') . '.zip';
             } else {
                 $archive_name = osc_base_path() . "OSClass_backup." . date('YmdHis') . ".zip";
             }
             $archive_folder = osc_base_path();
             if (osc_zip_folder($archive_folder, $archive_name)) {
                 $msg = _m('Archived successfully!');
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 $msg = _m('Error, the zip file was not created in the specified directory');
                 osc_add_flash_error_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             break;
         case 'backup_post':
             $this->doView('tools/backup.php');
             break;
         case 'maintenance':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because it is a demo site"), 'admin');
                 $this->doView('tools/maintenance.php');
                 break;
             }
             $mode = Params::getParam('mode');
             if ($mode == 'on') {
                 $maintenance_file = osc_base_path() . '.maintenance';
                 $fileHandler = @fopen($maintenance_file, 'w');
                 if ($fileHandler) {
                     osc_add_flash_ok_message(_m('Maintenance mode is ON'), 'admin');
                 } else {
                     osc_add_flash_error_message(_m('There was an error creating the .maintenance file, please create it manually at the root folder'), 'admin');
                 }
                 fclose($fileHandler);
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance');
             } else {
                 if ($mode == 'off') {
                     $deleted = @unlink(osc_base_path() . '.maintenance');
                     if ($deleted) {
                         osc_add_flash_ok_message(_m('Maintenance mode is OFF'), 'admin');
                     } else {
                         osc_add_flash_error_message(_m('There was an error removing the .maintenance file, please remove it manually from the root folder'), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance');
                 }
             }
             $this->doView('tools/maintenance.php');
             break;
         default:
     }
 }
Пример #11
0
 function doModel()
 {
     switch ($this->action) {
         case 'login_post':
             //post execution for the login
             if (Params::getParam('user') == '' && Params::getParam('password', false, false) == '') {
                 $this->redirectTo(osc_admin_base_url());
             }
             if (Params::getParam('user') == '') {
                 osc_add_flash_error_message(_m('The username field is empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             if (Params::getParam('password') == '') {
                 osc_add_flash_error_message(_m('The password field is empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             // fields are not empty
             $admin = Admin::newInstance()->findByUsername(Params::getParam('user'));
             if (!$admin) {
                 osc_add_flash_error_message(sprintf(_m('Sorry, incorrect username. <a href="%s">Have you lost your password?</a>'), osc_admin_base_url(true) . '?page=login&amp;action=recover'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             if ($admin["s_password"] !== sha1(Params::getParam('password', false, false))) {
                 osc_add_flash_error_message(sprintf(_m('Sorry, incorrect password. <a href="%s">Have you lost your password?</a>'), osc_admin_base_url(true) . '?page=login&amp;action=recover'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             if (Params::getParam('remember')) {
                 // this include contains de osc_genRandomPassword function
                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                 $secret = osc_genRandomPassword();
                 Admin::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $admin['pk_i_id']));
                 Cookie::newInstance()->set_expires(osc_time_cookie());
                 Cookie::newInstance()->push('oc_adminId', $admin['pk_i_id']);
                 Cookie::newInstance()->push('oc_adminSecret', $secret);
                 Cookie::newInstance()->push('oc_adminLocale', Params::getParam('locale'));
                 Cookie::newInstance()->set();
             }
             // we are logged in... let's go!
             Session::newInstance()->_set('adminId', $admin['pk_i_id']);
             Session::newInstance()->_set('adminUserName', $admin['s_username']);
             Session::newInstance()->_set('adminName', $admin['s_name']);
             Session::newInstance()->_set('adminEmail', $admin['s_email']);
             Session::newInstance()->_set('adminLocale', Params::getParam('locale'));
             $this->redirectTo(osc_admin_base_url());
             break;
         case 'recover':
             // form to recover the password (in this case we have the form in /gui/)
             $this->doView('gui/recover.php');
             break;
         case 'recover_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             // post execution to recover the password
             $admin = Admin::newInstance()->findByEmail(Params::getParam('email'));
             if ($admin) {
                 if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                     if (!osc_check_recaptcha()) {
                         osc_add_flash_error_message(_m('The Recaptcha code is wrong'), 'admin');
                         $this->redirectTo(osc_admin_base_url(true) . '?page=login&action=recover');
                         return false;
                         // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                     }
                 }
                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                 $newPassword = osc_genRandomPassword(40);
                 Admin::newInstance()->update(array('s_secret' => $newPassword), array('pk_i_id' => $admin['pk_i_id']));
                 $password_url = osc_forgot_admin_password_confirm_url($admin['pk_i_id'], $newPassword);
                 osc_run_hook('hook_email_user_forgot_password', $admin, $password_url);
             }
             osc_add_flash_ok_message(_m('A new password has been sent to your e-mail'), 'admin');
             $this->redirectTo(osc_admin_base_url());
             break;
         case 'forgot':
             // form to recover the password (in this case we have the form in /gui/)
             $admin = Admin::newInstance()->findByIdSecret(Params::getParam('adminId'), Params::getParam('code'));
             if (!$admin) {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             $this->doView('gui/forgot_password.php');
             break;
         case 'forgot_post':
             $admin = Admin::newInstance()->findByIdSecret(Params::getParam('adminId'), Params::getParam('code'));
             if (!$admin) {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             if (Params::getParam('new_password', false, false) == Params::getParam('new_password2', false, false)) {
                 Admin::newInstance()->update(array('s_secret' => osc_genRandomPassword(), 's_password' => sha1(Params::getParam('new_password', false, false))), array('pk_i_id' => $admin['pk_i_id']));
                 osc_add_flash_ok_message(_m('The password has been changed'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             } else {
                 osc_add_flash_error_message(_m("Error, the password don't match"), 'admin');
                 $this->redirectTo(osc_forgot_admin_password_confirm_url(Params::getParam('adminId'), Params::getParam('code')));
             }
             break;
     }
 }
Пример #12
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add':
             $this->doView("appearance/add.php");
             break;
         case 'add_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_themes_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The theme folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     $msg = _m('The theme has been installed correctly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_error_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the theme');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'widgets':
             $info = WebThemes::newInstance()->loadThemeInfo(osc_theme());
             $this->_exportVariableToView("info", $info);
             $this->doView('appearance/widgets.php');
             break;
         case 'add_widget':
             $this->doView('appearance/add_widget.php');
             break;
         case 'edit_widget':
             $id = Params::getParam('id');
             $widget = Widget::newInstance()->findByPrimaryKey($id);
             $this->_exportVariableToView("widget", $widget);
             $this->doView('appearance/add_widget.php');
             break;
         case 'delete_widget':
             Widget::newInstance()->delete(array('pk_i_id' => Params::getParam('id')));
             osc_add_flash_ok_message(_m('Widget removed correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'edit_widget_post':
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             $res = Widget::newInstance()->update(array('s_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)), array('pk_i_id' => Params::getParam('id')));
             if ($res) {
                 osc_add_flash_ok_message(_m('Widget updated correctly'), 'admin');
             } else {
                 osc_add_flash_ok_message(_m('Widget cannot be updated correctly'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'add_widget_post':
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             Widget::newInstance()->insert(array('s_location' => Params::getParam('location'), 'e_kind' => 'html', 's_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)));
             osc_add_flash_ok_message(_m('Widget added correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'activate':
             Preference::newInstance()->update(array('s_value' => Params::getParam('theme')), array('s_section' => 'osclass', 's_name' => 'theme'));
             osc_add_flash_ok_message(_m('Theme activated correctly'), 'admin');
             osc_run_hook("theme_activate", Params::getParam('theme'));
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         default:
             $themes = WebThemes::newInstance()->getListThemes();
             $info = WebThemes::newInstance()->loadThemeInfo(osc_theme());
             //preparing variables for the view
             $this->_exportVariableToView("themes", $themes);
             $this->_exportVariableToView("info", $info);
             $this->doView('appearance/index.php');
     }
 }
Пример #13
0
 function doModel()
 {
     switch ($this->action) {
         case 'dashboard':
             //dashboard...
             $max_items = Params::getParam('max_items') != '' ? Params::getParam('max_items') : 5;
             $aItems = Item::newInstance()->findByUserIDEnabled(Session::newInstance()->_get('userId'), 0, $max_items);
             //calling the view...
             $this->_exportVariableToView('items', $aItems);
             $this->_exportVariableToView('max_items', $max_items);
             $this->doView('user-dashboard.php');
             break;
         case 'profile':
             //profile...
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($user['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->findByCountry($user['fk_c_country_code']);
             } elseif (count($aCountries) > 0) {
                 $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
             }
             $aCities = array();
             if ($user['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->findByRegion($user['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
                 }
             }
             //calling the view...
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('user', $user);
             $this->doView('user-profile.php');
             break;
         case 'profile_post':
             //profile post...
             $userId = Session::newInstance()->_get('userId');
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(false);
             $success = $userActions->edit($userId);
             osc_add_flash_ok_message(_m('Your profile has been updated successfully'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'alerts':
             //alerts
             $aAlerts = Alerts::newInstance()->findByUser(Session::newInstance()->_get('userId'));
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             foreach ($aAlerts as $k => $a) {
                 $search = osc_unserialize(base64_decode($a['s_search']));
                 $search->limit(0, 3);
                 $aAlerts[$k]['items'] = $search->doSearch();
             }
             $this->_exportVariableToView('alerts', $aAlerts);
             View::newInstance()->_reset('alerts');
             $this->_exportVariableToView('user', $user);
             $this->doView('user-alerts.php');
             break;
         case 'change_email':
             //change email
             $this->doView('user-change_email.php');
             break;
         case 'change_email_post':
             //change email post
             if (!preg_match("/^[_a-z0-9-\\+]+(\\.[_a-z0-9-\\+]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})\$/", Params::getParam('new_email'))) {
                 osc_add_flash_error_message(_m('The specified e-mail is not valid'));
                 $this->redirectTo(osc_change_user_email_url());
             } else {
                 $user = User::newInstance()->findByEmail(Params::getParam('new_email'));
                 if (!isset($user['pk_i_id'])) {
                     $userEmailTmp = array();
                     $userEmailTmp['fk_i_user_id'] = Session::newInstance()->_get('userId');
                     $userEmailTmp['s_new_email'] = Params::getParam('new_email');
                     UserEmailTmp::newInstance()->insertOrUpdate($userEmailTmp);
                     $code = osc_genRandomPassword(30);
                     $date = date('Y-m-d H:i:s');
                     $userManager = new User();
                     $userManager->update(array('s_pass_code' => $code, 's_pass_date' => $date, 's_pass_ip' => $_SERVER['REMOTE_ADDR']), array('pk_i_id' => Session::newInstance()->_get('userId')));
                     $validation_url = osc_change_user_email_confirm_url(Session::newInstance()->_get('userId'), $code);
                     osc_run_hook('hook_email_new_email', Params::getParam('new_email'), $validation_url);
                     $this->redirectTo(osc_user_profile_url());
                 } else {
                     osc_add_flash_error_message(_m('The specified e-mail is already in use'));
                     $this->redirectTo(osc_change_user_email_url());
                 }
             }
             break;
         case 'change_password':
             //change password
             $this->doView('user-change_password.php');
             break;
         case 'change_password_post':
             //change password post
             $user = User::newInstance()->findByPrimaryKey(Session::newInstance()->_get('userId'));
             if (Params::getParam('password') == '' || Params::getParam('new_password') == '' || Params::getParam('new_password2') == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if ($user['s_password'] != sha1(Params::getParam('password'))) {
                 osc_add_flash_error_message(_m('Current password doesn\'t match'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (!Params::getParam('new_password')) {
                 osc_add_flash_error_message(_m('Passwords can\'t be empty'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             if (Params::getParam('new_password') != Params::getParam('new_password2')) {
                 osc_add_flash_error_message(_m('Passwords don\'t match'));
                 $this->redirectTo(osc_change_user_password_url());
             }
             User::newInstance()->update(array('s_password' => sha1(Params::getParam('new_password'))), array('pk_i_id' => Session::newInstance()->_get('userId')));
             osc_add_flash_ok_message(_m('Password has been changed'));
             $this->redirectTo(osc_user_profile_url());
             break;
         case 'items':
             // view items user
             $itemsPerPage = Params::getParam('itemsPerPage') != '' ? Params::getParam('itemsPerPage') : 5;
             $page = Params::getParam('iPage') != '' ? Params::getParam('iPage') : 0;
             $total_items = Item::newInstance()->countByUserIDEnabled($_SESSION['userId']);
             $total_pages = ceil($total_items / $itemsPerPage);
             $items = Item::newInstance()->findByUserIDEnabled($_SESSION['userId'], $page * $itemsPerPage, $itemsPerPage);
             $this->_exportVariableToView('items', $items);
             $this->_exportVariableToView('list_total_pages', $total_pages);
             $this->_exportVariableToView('list_total_items', $total_items);
             $this->_exportVariableToView('items_per_page', $itemsPerPage);
             $this->_exportVariableToView('list_page', $page);
             $this->doView('user-items.php');
             break;
         case 'activate_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             $result = 0;
             if ($email != '' && $secret != '') {
                 $result = Alerts::newInstance()->activate($email, $secret);
             }
             if ($result == 1) {
                 osc_add_flash_ok_message(_m('Alert activated'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to activate alert. Please contact the administrator'));
             }
             $this->redirectTo(osc_base_url(true));
             break;
         case 'unsub_alert':
             $email = Params::getParam('email');
             $secret = Params::getParam('secret');
             if ($email != '' && $secret != '') {
                 Alerts::newInstance()->delete(array('s_email' => $email, 's_secret' => $secret));
                 osc_add_flash_ok_message(_m('Unsubscribed correctly'));
             } else {
                 osc_add_flash_error_message(_m('Ops! There was a problem trying to unsubscribe you. Please contact the administrator'));
             }
             $this->redirectTo(osc_user_alerts_url());
             break;
         case 'deleteResource':
             $id = Params::getParam('id');
             $name = Params::getParam('name');
             $fkid = Params::getParam('fkid');
             osc_deleteResource($id);
             ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $fkid, 's_name' => $name));
             $this->redirectTo(osc_base_url(true) . "?page=item&action=item_edit&id=" . $fkid);
             break;
     }
 }
Пример #14
0
 function doModel()
 {
     switch ($this->action) {
         case 'login_post':
             //post execution for the login
             osc_csrf_check();
             osc_run_hook('before_login_admin');
             $url_redirect = osc_get_http_referer();
             $page_redirect = '';
             $password = Params::getParam('password', false, false);
             if (preg_match('|[\\?&]page=([^&]+)|', $url_redirect . '&', $match)) {
                 $page_redirect = $match[1];
             }
             if ($page_redirect == '' || $page_redirect == 'login' || $url_redirect == '') {
                 $url_redirect = osc_admin_base_url();
             }
             if (Params::getParam('user') == '') {
                 osc_add_flash_error_message(_m('The username field is empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=login");
             }
             if (Params::getParam('password', false, false) == '') {
                 osc_add_flash_error_message(_m('The password field is empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=login");
             }
             // fields are not empty
             $admin = Admin::newInstance()->findByUsername(Params::getParam('user'));
             if (!$admin) {
                 osc_add_flash_error_message(sprintf(_m('Sorry, incorrect username. <a href="%s">Have you lost your password?</a>'), osc_admin_base_url(true) . '?page=login&amp;action=recover'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=login");
             }
             if (!osc_verify_password($password, $admin['s_password'])) {
                 osc_add_flash_error_message(sprintf(_m('Sorry, incorrect password. <a href="%s">Have you lost your password?</a>'), osc_admin_base_url(true) . '?page=login&amp;action=recover'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=login");
             } else {
                 if (@$admin['s_password'] != '') {
                     if (preg_match('|\\$2y\\$([0-9]{2})\\$|', $admin['s_password'], $cost)) {
                         if ($cost[1] != BCRYPT_COST) {
                             Admin::newInstance()->update(array('s_password' => osc_hash_password($password)), array('pk_i_id' => $admin['pk_i_id']));
                         }
                     } else {
                         Admin::newInstance()->update(array('s_password' => osc_hash_password($password)), array('pk_i_id' => $admin['pk_i_id']));
                     }
                 }
             }
             if (Params::getParam('remember')) {
                 // this include contains de osc_genRandomPassword function
                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                 $secret = osc_genRandomPassword();
                 Admin::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $admin['pk_i_id']));
                 Cookie::newInstance()->set_expires(osc_time_cookie());
                 Cookie::newInstance()->push('oc_adminId', $admin['pk_i_id']);
                 Cookie::newInstance()->push('oc_adminSecret', $secret);
                 Cookie::newInstance()->push('oc_adminLocale', Params::getParam('locale'));
                 Cookie::newInstance()->set();
             }
             // we are logged in... let's go!
             Session::newInstance()->_set('adminId', $admin['pk_i_id']);
             Session::newInstance()->_set('adminUserName', $admin['s_username']);
             Session::newInstance()->_set('adminName', $admin['s_name']);
             Session::newInstance()->_set('adminEmail', $admin['s_email']);
             Session::newInstance()->_set('adminLocale', Params::getParam('locale'));
             osc_run_hook('login_admin', $admin);
             $this->redirectTo($url_redirect);
             break;
         case 'recover':
             // form to recover the password (in this case we have the form in /gui/)
             $this->doView('gui/recover.php');
             break;
         case 'recover_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             osc_csrf_check();
             // post execution to recover the password
             $admin = Admin::newInstance()->findByEmail(Params::getParam('email'));
             if ($admin) {
                 if (osc_recaptcha_private_key() != '') {
                     if (!osc_check_recaptcha()) {
                         osc_add_flash_error_message(_m('The reCAPTCHA code is wrong'), 'admin');
                         $this->redirectTo(osc_admin_base_url(true) . '?page=login&action=recover');
                         return false;
                         // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                     }
                 }
                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                 $newPassword = osc_genRandomPassword(40);
                 Admin::newInstance()->update(array('s_secret' => $newPassword), array('pk_i_id' => $admin['pk_i_id']));
                 $password_url = osc_forgot_admin_password_confirm_url($admin['pk_i_id'], $newPassword);
                 osc_run_hook('hook_email_user_forgot_password', $admin, $password_url);
             }
             osc_add_flash_ok_message(_m('A new password has been sent to your e-mail'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=login');
             break;
         case 'forgot':
             // form to recover the password (in this case we have the form in /gui/)
             $admin = Admin::newInstance()->findByIdSecret(Params::getParam('adminId'), Params::getParam('code'));
             if (!$admin) {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             $this->doView('gui/forgot_password.php');
             break;
         case 'forgot_post':
             osc_csrf_check();
             $admin = Admin::newInstance()->findByIdSecret(Params::getParam('adminId'), Params::getParam('code'));
             if (!$admin) {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'), 'admin');
                 $this->redirectTo(osc_admin_base_url());
             }
             if (Params::getParam('new_password', false, false) == Params::getParam('new_password2', false, false)) {
                 Admin::newInstance()->update(array('s_secret' => osc_genRandomPassword(), 's_password' => osc_hash_password(Params::getParam('new_password', false, false))), array('pk_i_id' => $admin['pk_i_id']));
                 osc_add_flash_ok_message(_m('The password has been changed'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=login');
             } else {
                 osc_add_flash_error_message(_m("Error, the passwords don't match"), 'admin');
                 $this->redirectTo(osc_forgot_admin_password_confirm_url(Params::getParam('adminId'), Params::getParam('code')));
             }
             break;
         default:
             //osc_run_hook( 'init_admin' );
             Session::newInstance()->_setReferer(osc_get_http_referer());
             $this->doView('gui/login.php');
             break;
     }
 }
Пример #15
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add':
             $this->doView("appearance/add.php");
             break;
         case 'add_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             osc_csrf_check();
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_themes_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The theme folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     $msg = _m('The theme has been installed correctly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_error_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the theme');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'delete':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             osc_csrf_check();
             $theme = Params::getParam('webtheme');
             if ($theme != '') {
                 if ($theme != osc_current_web_theme()) {
                     if (osc_deleteDir(osc_content_path() . "themes/" . $theme . "/")) {
                         osc_add_flash_ok_message(_m("Theme removed successfully"), "admin");
                     } else {
                         osc_add_flash_error_message(_m("There was a problem removing the theme"), "admin");
                     }
                 } else {
                     osc_add_flash_error_message(_m("Current theme can not be deleted"), "admin");
                 }
             } else {
                 osc_add_flash_error_message(_m("No theme selected"), "admin");
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
             /* widgets */
         /* widgets */
         case 'widgets':
             $info = WebThemes::newInstance()->loadThemeInfo(osc_theme());
             $this->_exportVariableToView("info", $info);
             $this->doView('appearance/widgets.php');
             break;
         case 'add_widget':
             $this->doView('appearance/add_widget.php');
             break;
         case 'edit_widget':
             $id = Params::getParam('id');
             $widget = Widget::newInstance()->findByPrimaryKey($id);
             $this->_exportVariableToView("widget", $widget);
             $this->doView('appearance/add_widget.php');
             break;
         case 'delete_widget':
             osc_csrf_check();
             Widget::newInstance()->delete(array('pk_i_id' => Params::getParam('id')));
             osc_add_flash_ok_message(_m('Widget removed correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'edit_widget_post':
             osc_csrf_check();
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             $res = Widget::newInstance()->update(array('s_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)), array('pk_i_id' => Params::getParam('id')));
             if ($res) {
                 osc_add_flash_ok_message(_m('Widget updated correctly'), 'admin');
             } else {
                 osc_add_flash_ok_message(_m('Widget cannot be updated correctly'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'add_widget_post':
             osc_csrf_check();
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             Widget::newInstance()->insert(array('s_location' => Params::getParam('location'), 'e_kind' => 'html', 's_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)));
             osc_add_flash_ok_message(_m('Widget added correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
             /* /widget */
         /* /widget */
         case 'activate':
             osc_csrf_check();
             Preference::newInstance()->update(array('s_value' => Params::getParam('theme')), array('s_section' => 'osclass', 's_name' => 'theme'));
             osc_add_flash_ok_message(_m('Theme activated correctly'), 'admin');
             osc_run_hook("theme_activate", Params::getParam('theme'));
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'render':
             $this->_exportVariableToView('file', osc_base_path() . Params::getParam("file"));
             $this->doView('appearance/view.php');
             break;
         default:
             //                    $marketError = Params::getParam('marketError');
             //                    $slug = Params::getParam('slug');
             //                    if($marketError!='') {
             //                        if($marketError == '0') { // no error installed ok
             //                            $help = '<br/><br/><b>' . __('You only need to activate or preview the theme').'</b>';
             //                            osc_add_flash_ok_message( __('Everything was OK!') . ' ( ' . $slug .' ) ' . $help, 'admin');
             //                        } else {
             //                            osc_add_flash_error_message( __('Error occurred') . ' ( ' . $slug .' ) ', 'admin');
             //                        }
             //                    }
             // force the recount of themes that need to be updated
             if (Params::getParam('checkUpdated') != '') {
                 osc_admin_toolbar_update_themes(true);
             }
             $themes = WebThemes::newInstance()->getListThemes();
             //preparing variables for the view
             $this->_exportVariableToView("themes", $themes);
             $this->doView('appearance/index.php');
             break;
     }
 }
Пример #16
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'create':
             // calling create view
             $aRegions = array();
             $aCities = array();
             $aCountries = Country::newInstance()->listAll();
             if (isset($aCountries[0]['pk_c_code'])) {
                 $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
             }
             if (isset($aRegions[0]['pk_i_id'])) {
                 $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
             }
             $this->_exportVariableToView('user', null);
             $this->_exportVariableToView('countries', $aCountries);
             $this->_exportVariableToView('regions', $aRegions);
             $this->_exportVariableToView('cities', $aCities);
             $this->_exportVariableToView('locales', OSCLocale::newInstance()->listAllEnabled());
             $this->doView("users/frm.php");
             break;
         case 'create_post':
             // creating the user...
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(true);
             $success = $userActions->add();
             switch ($success) {
                 case 1:
                     osc_add_flash_ok_message(_m("The user has been created. We've sent an activation e-mail"), 'admin');
                     break;
                 case 2:
                     osc_add_flash_ok_message(_m('The user has been created successfully'), 'admin');
                     break;
                 default:
                     osc_add_flash_error_message($success, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'edit':
             // calling the edit view
             $aUser = $this->userManager->findByPrimaryKey(Params::getParam("id"));
             $aCountries = Country::newInstance()->listAll();
             $aRegions = array();
             if ($aUser['fk_c_country_code'] != '') {
                 $aRegions = Region::newInstance()->findByCountry($aUser['fk_c_country_code']);
             } else {
                 if (count($aCountries) > 0) {
                     $aRegions = Region::newInstance()->findByCountry($aCountries[0]['pk_c_code']);
                 }
             }
             $aCities = array();
             if ($aUser['fk_i_region_id'] != '') {
                 $aCities = City::newInstance()->findByRegion($aUser['fk_i_region_id']);
             } else {
                 if (count($aRegions) > 0) {
                     $aCities = City::newInstance()->findByRegion($aRegions[0]['pk_i_id']);
                 }
             }
             $csrf_token = osc_csrf_token_url();
             if ($aUser['b_active']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=users&action=deactivate&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=INACTIVE">' . __('Deactivate') . '</a>';
             } else {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=users&action=activate&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=ACTIVE">' . __('Activate') . '</a>';
             }
             if ($aUser['b_enabled']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=users&action=disable&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=DISABLE">' . __('Block') . '</a>';
             } else {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=users&action=enable&id[]=' . $aUser['pk_i_id'] . '&' . $csrf_token . '&value=ENABLE">' . __('Unblock') . '</a>';
             }
             $this->_exportVariableToView("actions", $actions);
             $this->_exportVariableToView("user", $aUser);
             $this->_exportVariableToView("countries", $aCountries);
             $this->_exportVariableToView("regions", $aRegions);
             $this->_exportVariableToView("cities", $aCities);
             $this->_exportVariableToView("locales", OSCLocale::newInstance()->listAllEnabled());
             $this->doView("users/frm.php");
             break;
         case 'edit_post':
             // edit post
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(true);
             $success = $userActions->edit(Params::getParam("id"));
             if ($success == 1) {
                 osc_add_flash_ok_message(_m('The user has been updated'), 'admin');
             } else {
                 if ($success == 2) {
                     osc_add_flash_ok_message(_m('The user has been updated and activated'), 'admin');
                 } else {
                     osc_add_flash_error_message($success);
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('id'));
                 }
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'resend_activation':
             //activate
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->resend_activation($id);
             }
             if ($iUpdated == 0) {
                 osc_add_flash_error_message(_m('No users have been selected'), 'admin');
             } else {
                 osc_add_flash_ok_message(sprintf(_mn('Activation email sent to one user', 'Activation email sent to %s users', $iUpdated), $iUpdated), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'activate':
             //activate
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->activate($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been activated');
             } else {
                 $msg = sprintf(_mn('One user has been activated', '%s users have been activated', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'deactivate':
             //deactivate
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->deactivate($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been deactivated');
             } else {
                 $msg = sprintf(_mn('One user has been deactivated', '%s users have been deactivated', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'enable':
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->enable($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been enabled');
             } else {
                 $msg = sprintf(_mn('One user has been unblocked', '%s users have been unblocked', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'disable':
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             $iUpdated = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             $userActions = new UserActions(true);
             foreach ($userId as $id) {
                 $iUpdated += $userActions->disable($id);
             }
             if ($iUpdated == 0) {
                 $msg = _m('No users have been disabled');
             } else {
                 $msg = sprintf(_mn('One user has been blocked', '%s users have been blocked', $iUpdated), $iUpdated);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'delete':
             //delete
             osc_csrf_check();
             $iDeleted = 0;
             $userId = Params::getParam('id');
             if (!is_array($userId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             }
             foreach ($userId as $id) {
                 $user = $this->userManager->findByPrimaryKey($id);
                 Log::newInstance()->insertLog('user', 'delete', $id, $user['s_email'], 'admin', osc_logged_admin_id());
                 if ($this->userManager->deleteUser($id)) {
                     $iDeleted++;
                 }
             }
             if ($iDeleted == 0) {
                 $msg = _m('No users have been deleted');
             } else {
                 $msg = sprintf(_mn('One user has been deleted', '%s users have been deleted', $iDeleted), $iDeleted);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users');
             break;
         case 'delete_alerts':
             //delete
             $iDeleted = 0;
             $alertId = Params::getParam('alert_id');
             if (!is_array($alertId)) {
                 osc_add_flash_error_message(_m("Alert id isn't in the correct format"), 'admin');
                 if (Params::getParam('user_id') == '') {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
                 } else {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
                 }
             }
             $mAlerts = new Alerts();
             foreach ($alertId as $id) {
                 Log::newInstance()->insertLog('user', 'delete_alerts', $id, $id, 'admin', osc_logged_admin_id());
                 $iDeleted += $mAlerts->delete(array('pk_i_id' => $id));
             }
             if ($iDeleted == 0) {
                 $msg = _m('No alerts have been deleted');
             } else {
                 $msg = sprintf(_mn('One alert has been deleted', '%s alerts have been deleted', $iDeleted), $iDeleted);
             }
             osc_add_flash_ok_message($msg, 'admin');
             if (Params::getParam('user_id') == '') {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
             } else {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
             }
             break;
         case 'status_alerts':
             //delete
             $status = Params::getParam("status");
             $iUpdated = 0;
             $alertId = Params::getParam('alert_id');
             if (!is_array($alertId)) {
                 osc_add_flash_error_message(_m("Alert id isn't in the correct format"), 'admin');
                 if (Params::getParam('user_id') == '') {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
                 } else {
                     $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
                 }
             }
             $mAlerts = new Alerts();
             foreach ($alertId as $id) {
                 if ($status == 1) {
                     $iUpdated += $mAlerts->activate($id);
                 } else {
                     $iUpdated += $mAlerts->deactivate($id);
                 }
             }
             if ($status == 1) {
                 if ($iUpdated == 0) {
                     $msg = _m('No alerts have been activated');
                 } else {
                     $msg = sprintf(_mn('One alert has been activated', '%s alerts have been activated', $iUpdated), $iUpdated);
                 }
             } else {
                 if ($iUpdated == 0) {
                     $msg = _m('No alerts have been deactivated');
                 } else {
                     $msg = sprintf(_mn('One alert has been deactivated', '%s alerts have been deactivated', $iUpdated), $iUpdated);
                 }
             }
             osc_add_flash_ok_message($msg, 'admin');
             if (Params::getParam('user_id') == '') {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=alerts');
             } else {
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=edit&id=' . Params::getParam('user_id'));
             }
             break;
         case 'settings':
             // calling the users settings view
             $this->doView('users/settings.php');
             break;
         case 'settings_post':
             // updating users
             osc_csrf_check();
             $iUpdated = 0;
             $enabledUserValidation = Params::getParam('enabled_user_validation');
             $enabledUserValidation = $enabledUserValidation != '' ? true : false;
             $enabledUserRegistration = Params::getParam('enabled_user_registration');
             $enabledUserRegistration = $enabledUserRegistration != '' ? true : false;
             $enabledUsers = Params::getParam('enabled_users');
             $enabledUsers = $enabledUsers != '' ? true : false;
             $notifyNewUser = Params::getParam('notify_new_user');
             $notifyNewUser = $notifyNewUser != '' ? true : false;
             $usernameBlacklistTmp = explode(",", Params::getParam('username_blacklist'));
             foreach ($usernameBlacklistTmp as $k => $v) {
                 $usernameBlacklistTmp[$k] = strtolower(trim($v));
             }
             $usernameBlacklist = implode(",", $usernameBlacklistTmp);
             $iUpdated += osc_set_preference('enabled_user_validation', $enabledUserValidation);
             $iUpdated += osc_set_preference('enabled_user_registration', $enabledUserRegistration);
             $iUpdated += osc_set_preference('enabled_users', $enabledUsers);
             $iUpdated += osc_set_preference('notify_new_user', $notifyNewUser);
             $iUpdated += osc_set_preference('username_blacklist', $usernameBlacklist);
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(_m("User settings have been updated"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=settings');
             break;
         case 'alerts':
             // manage alerts view
             require_once osc_lib_path() . "osclass/classes/datatables/AlertsDataTable.php";
             // set default iDisplayLength
             if (Params::getParam('iDisplayLength') != '') {
                 Cookie::newInstance()->push('listing_iDisplayLength', Params::getParam('iDisplayLength'));
                 Cookie::newInstance()->set();
             } else {
                 // set a default value if it's set in the cookie
                 if (Cookie::newInstance()->get_value('listing_iDisplayLength') != '') {
                     Params::setParam('iDisplayLength', Cookie::newInstance()->get_value('listing_iDisplayLength'));
                 } else {
                     Params::setParam('iDisplayLength', 10);
                 }
             }
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             // Table header order by related
             if (Params::getParam('sort') == '') {
                 Params::setParam('sort', 'date');
             }
             if (Params::getParam('direction') == '') {
                 Params::setParam('direction', 'desc');
             }
             $page = (int) Params::getParam('iPage');
             if ($page == 0) {
                 $page = 1;
             }
             Params::setParam('iPage', $page);
             $params = Params::getParamsAsArray();
             $alertsDataTable = new AlertsDataTable();
             $alertsDataTable->table($params);
             $aData = $alertsDataTable->getData();
             if (count($aData['aRows']) == 0 && $page != 1) {
                 $total = (int) $aData['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $aData['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aData', $aData);
             $this->_exportVariableToView('aRawRows', $alertsDataTable->rawRows());
             $this->doView("users/alerts.php");
             break;
         case 'ban':
             // manage ban rules view
             if (Params::getParam("action") != "") {
                 osc_run_hook("ban_rules_bulk_" . Params::getParam("action"), Params::getParam('id'));
             }
             require_once osc_lib_path() . "osclass/classes/datatables/BanRulesDataTable.php";
             // set default iDisplayLength
             if (Params::getParam('iDisplayLength') != '') {
                 Cookie::newInstance()->push('listing_iDisplayLength', Params::getParam('iDisplayLength'));
                 Cookie::newInstance()->set();
             } else {
                 // set a default value if it's set in the cookie
                 if (Cookie::newInstance()->get_value('listing_iDisplayLength') != '') {
                     Params::setParam('iDisplayLength', Cookie::newInstance()->get_value('listing_iDisplayLength'));
                 } else {
                     Params::setParam('iDisplayLength', 10);
                 }
             }
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             // Table header order by related
             if (Params::getParam('sort') == '') {
                 Params::setParam('sort', 'date');
             }
             if (Params::getParam('direction') == '') {
                 Params::setParam('direction', 'desc');
             }
             $page = (int) Params::getParam('iPage');
             if ($page == 0) {
                 $page = 1;
             }
             Params::setParam('iPage', $page);
             $params = Params::getParamsAsArray();
             $banRulesDataTable = new BanRulesDataTable();
             $banRulesDataTable->table($params);
             $aData = $banRulesDataTable->getData();
             if (count($aData['aRows']) == 0 && $page != 1) {
                 $total = (int) $aData['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $aData['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aData', $aData);
             $this->_exportVariableToView('aRawRows', $banRulesDataTable->rawRows());
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'delete_ban_rule', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected ban rules?'), strtolower(__('Delete'))), 'label' => __('Delete')));
             $bulk_options = osc_apply_filter("ban_rule_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             //calling the view...
             $this->doView('users/ban.php');
             break;
         case 'edit_ban_rule':
             $this->_exportVariableToView('rule', BanRule::newInstance()->findByPrimaryKey(Params::getParam('id')));
             $this->doView('users/ban_frm.php');
             break;
         case 'edit_ban_rule_post':
             osc_csrf_check();
             if (Params::getParam('s_ip') == '' && Params::getParam('s_email') == '') {
                 osc_add_flash_warning_message(_m("Both rules can not be empty"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             }
             BanRule::newInstance()->update(array('s_name' => Params::getParam('s_name'), 's_ip' => Params::getParam('s_ip'), 's_email' => strtolower(Params::getParam('s_email'))), array('pk_i_id' => Params::getParam('id')));
             osc_add_flash_ok_message(_m('Rule updated correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             break;
         case 'create_ban_rule':
             $this->_exportVariableToView('rule', null);
             $this->doView('users/ban_frm.php');
             break;
         case 'create_ban_rule_post':
             osc_csrf_check();
             if (Params::getParam('s_ip') == '' && Params::getParam('s_email') == '') {
                 osc_add_flash_warning_message(_m("Both rules can not be empty"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             }
             BanRule::newInstance()->insert(array('s_name' => Params::getParam('s_name'), 's_ip' => Params::getParam('s_ip'), 's_email' => strtolower(Params::getParam('s_email'))));
             osc_add_flash_ok_message(_m('Rule saved correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             break;
         case 'delete_ban_rule':
             //delete ban rules
             osc_csrf_check();
             $iDeleted = 0;
             $ruleId = Params::getParam('id');
             if (!is_array($ruleId)) {
                 osc_add_flash_error_message(_m("User id isn't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             }
             $ruleMgr = BanRule::newInstance();
             foreach ($ruleId as $id) {
                 if ($ruleMgr->deleteByPrimaryKey($id)) {
                     $iDeleted++;
                 }
             }
             if ($iDeleted == 0) {
                 $msg = _m('No rules have been deleted');
             } else {
                 $msg = sprintf(_mn('One ban rule has been deleted', '%s ban rules have been deleted', $iDeleted), $iDeleted);
             }
             osc_add_flash_ok_message($msg, 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=users&action=ban');
             break;
         default:
             // manage users view
             if (Params::getParam("action") != "") {
                 osc_run_hook("user_bulk_" . Params::getParam("action"), Params::getParam('id'));
             }
             require_once osc_lib_path() . "osclass/classes/datatables/UsersDataTable.php";
             // set default iDisplayLength
             if (Params::getParam('iDisplayLength') != '') {
                 Cookie::newInstance()->push('listing_iDisplayLength', Params::getParam('iDisplayLength'));
                 Cookie::newInstance()->set();
             } else {
                 // set a default value if it's set in the cookie
                 if (Cookie::newInstance()->get_value('listing_iDisplayLength') != '') {
                     Params::setParam('iDisplayLength', Cookie::newInstance()->get_value('listing_iDisplayLength'));
                 } else {
                     Params::setParam('iDisplayLength', 10);
                 }
             }
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             // Table header order by related
             if (Params::getParam('sort') == '') {
                 Params::setParam('sort', 'date');
             }
             if (Params::getParam('direction') == '') {
                 Params::setParam('direction', 'desc');
             }
             $page = (int) Params::getParam('iPage');
             if ($page == 0) {
                 $page = 1;
             }
             Params::setParam('iPage', $page);
             $params = Params::getParamsAsArray();
             $usersDataTable = new UsersDataTable();
             $usersDataTable->table($params);
             $aData = $usersDataTable->getData();
             if (count($aData['aRows']) == 0 && $page != 1) {
                 $total = (int) $aData['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $aData['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aData', $aData);
             $this->_exportVariableToView('withFilters', $usersDataTable->withFilters());
             $this->_exportVariableToView('aRawRows', $usersDataTable->rawRows());
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'activate', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Activate'))), 'label' => __('Activate')), array('value' => 'deactivate', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Deactivate'))), 'label' => __('Deactivate')), array('value' => 'enable', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Unblock'))), 'label' => __('Unblock')), array('value' => 'disable', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Block'))), 'label' => __('Block')), array('value' => 'delete', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Delete'))), 'label' => __('Delete')));
             if (osc_user_validation_enabled()) {
                 $bulk_options[] = array('value' => 'resend_activation', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected users?'), strtolower(__('Resend the activation to'))), 'label' => __('Resend activation'));
             }
             $bulk_options = osc_apply_filter("user_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             //calling the view...
             $this->doView('users/index.php');
             break;
     }
 }
Пример #17
0
    function doModel()
    {
        switch ($this->action) {
            case 'permalinks':
                // calling the permalinks view
                $htaccess = Params::getParam('htaccess_status');
                $file = Params::getParam('file_status');
                $this->_exportVariableToView('htaccess', $htaccess);
                $this->_exportVariableToView('file', $file);
                $this->doView('settings/permalinks.php');
                break;
            case 'permalinks_post':
                // updating permalinks option
                osc_csrf_check();
                $htaccess_file = osc_base_path() . '.htaccess';
                $rewriteEnabled = Params::getParam('rewrite_enabled') ? true : false;
                $rewrite_base = REL_WEB_URL;
                $htaccess = <<<HTACCESS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase {$rewrite_base}
RewriteRule ^index\\.php\$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . {$rewrite_base}index.php [L]
</IfModule>
HTACCESS;
                if ($rewriteEnabled) {
                    osc_set_preference('rewriteEnabled', '1');
                    // 1. OK (ok)
                    // 2. OK no apache module detected (warning)
                    // 3. No se puede crear + apache
                    // 4. No se puede crear + no apache
                    // 5. .htaccess exists, no overwrite
                    $status = 3;
                    if (file_exists($htaccess_file)) {
                        $status = 5;
                    } else {
                        if (is_writable(osc_base_path()) && file_put_contents($htaccess_file, $htaccess)) {
                            $status = 1;
                        }
                    }
                    if (!@apache_mod_loaded('mod_rewrite')) {
                        $status++;
                    }
                    $errors = 0;
                    $item_url = substr(str_replace('//', '/', Params::getParam('rewrite_item_url') . '/'), 0, -1);
                    if (!osc_validate_text($item_url)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_url', $item_url);
                    }
                    $page_url = substr(str_replace('//', '/', Params::getParam('rewrite_page_url') . '/'), 0, -1);
                    if (!osc_validate_text($page_url)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_page_url', $page_url);
                    }
                    $cat_url = substr(str_replace('//', '/', Params::getParam('rewrite_cat_url') . '/'), 0, -1);
                    // DEPRECATED: backward compatibility, remove in 3.4
                    $cat_url = str_replace('{CATEGORY_SLUG}', '{CATEGORY_NAME}', $cat_url);
                    if (!osc_validate_text($cat_url)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_cat_url', $cat_url);
                    }
                    $search_url = substr(str_replace('//', '/', Params::getParam('rewrite_search_url') . '/'), 0, -1);
                    if (!osc_validate_text($search_url)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_url', $search_url);
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_country'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_country', Params::getParam('rewrite_search_country'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_region'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_region', Params::getParam('rewrite_search_region'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_city'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_city', Params::getParam('rewrite_search_city'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_city_area'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_city_area', Params::getParam('rewrite_search_city_area'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_category'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_category', Params::getParam('rewrite_search_category'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_user'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_user', Params::getParam('rewrite_search_user'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_pattern'))) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_search_pattern', Params::getParam('rewrite_search_pattern'));
                    }
                    $rewrite_contact = substr(str_replace('//', '/', Params::getParam('rewrite_contact') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_contact)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_contact', $rewrite_contact);
                    }
                    $rewrite_feed = substr(str_replace('//', '/', Params::getParam('rewrite_feed') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_feed)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_feed', $rewrite_feed);
                    }
                    $rewrite_language = substr(str_replace('//', '/', Params::getParam('rewrite_language') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_language)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_language', $rewrite_language);
                    }
                    $rewrite_item_mark = substr(str_replace('//', '/', Params::getParam('rewrite_item_mark') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_mark)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_mark', $rewrite_item_mark);
                    }
                    $rewrite_item_send_friend = substr(str_replace('//', '/', Params::getParam('rewrite_item_send_friend') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_send_friend)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_send_friend', $rewrite_item_send_friend);
                    }
                    $rewrite_item_contact = substr(str_replace('//', '/', Params::getParam('rewrite_item_contact') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_contact)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_contact', $rewrite_item_contact);
                    }
                    $rewrite_item_new = substr(str_replace('//', '/', Params::getParam('rewrite_item_new') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_new)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_new', $rewrite_item_new);
                    }
                    $rewrite_item_activate = substr(str_replace('//', '/', Params::getParam('rewrite_item_activate') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_activate)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_activate', $rewrite_item_activate);
                    }
                    $rewrite_item_edit = substr(str_replace('//', '/', Params::getParam('rewrite_item_edit') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_edit)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_edit', $rewrite_item_edit);
                    }
                    $rewrite_item_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_delete') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_delete)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_delete', $rewrite_item_delete);
                    }
                    $rewrite_item_resource_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_resource_delete') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_resource_delete)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_item_resource_delete', $rewrite_item_resource_delete);
                    }
                    $rewrite_user_login = substr(str_replace('//', '/', Params::getParam('rewrite_user_login') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_login)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_login', $rewrite_user_login);
                    }
                    $rewrite_user_dashboard = substr(str_replace('//', '/', Params::getParam('rewrite_user_dashboard') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_dashboard)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_dashboard', $rewrite_user_dashboard);
                    }
                    $rewrite_user_logout = substr(str_replace('//', '/', Params::getParam('rewrite_user_logout') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_logout)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_logout', $rewrite_user_logout);
                    }
                    $rewrite_user_register = substr(str_replace('//', '/', Params::getParam('rewrite_user_register') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_register)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_register', $rewrite_user_register);
                    }
                    $rewrite_user_activate = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_activate)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_activate', $rewrite_user_activate);
                    }
                    $rewrite_user_activate_alert = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate_alert') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_activate_alert)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_activate_alert', $rewrite_user_activate_alert);
                    }
                    $rewrite_user_profile = substr(str_replace('//', '/', Params::getParam('rewrite_user_profile') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_profile)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_profile', $rewrite_user_profile);
                    }
                    $rewrite_user_items = substr(str_replace('//', '/', Params::getParam('rewrite_user_items') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_items)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_items', $rewrite_user_items);
                    }
                    $rewrite_user_alerts = substr(str_replace('//', '/', Params::getParam('rewrite_user_alerts') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_alerts)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_alerts', $rewrite_user_alerts);
                    }
                    $rewrite_user_recover = substr(str_replace('//', '/', Params::getParam('rewrite_user_recover') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_recover)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_recover', $rewrite_user_recover);
                    }
                    $rewrite_user_forgot = substr(str_replace('//', '/', Params::getParam('rewrite_user_forgot') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_forgot)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_forgot', $rewrite_user_forgot);
                    }
                    $rewrite_user_change_password = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_password') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_password)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_change_password', $rewrite_user_change_password);
                    }
                    $rewrite_user_change_email = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_email)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_change_email', $rewrite_user_change_email);
                    }
                    $rewrite_user_change_username = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_username') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_username)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_change_username', $rewrite_user_change_username);
                    }
                    $rewrite_user_change_email_confirm = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email_confirm') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_email_confirm)) {
                        $errors += 1;
                    } else {
                        osc_set_preference('rewrite_user_change_email_confirm', $rewrite_user_change_email_confirm);
                    }
                    osc_reset_preferences();
                    $rewrite = Rewrite::newInstance();
                    osc_run_hook("before_rewrite_rules", array(&$rewrite));
                    $rewrite->clearRules();
                    /*****************************
                     ********* Add rules *********
                     *****************************/
                    // Contact rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_contact') . '/?$', 'index.php?page=contact');
                    // Feed rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/?$', 'index.php?page=search&sFeed=rss');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/(.+)/?$', 'index.php?page=search&sFeed=$1');
                    // Language rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_language') . '/(.*?)/?$', 'index.php?page=language&locale=$1');
                    // Search rules
                    $rewrite->addRule('^' . $search_url . '$', 'index.php?page=search');
                    $rewrite->addRule('^' . $search_url . '/(.*)$', 'index.php?page=search&sParams=$1');
                    // Item rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_mark') . '/(.*?)/([0-9]+)/?$', 'index.php?page=item&action=mark&as=$1&id=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_send_friend') . '/([0-9]+)/?$', 'index.php?page=item&action=send_friend&id=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_contact') . '/([0-9]+)/?$', 'index.php?page=item&action=contact&id=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/?$', 'index.php?page=item&action=item_add');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/([0-9]+)/?$', 'index.php?page=item&action=item_add&catId=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=activate&id=$1&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_edit') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_edit&id=$1&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_delete') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_delete&id=$1&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_resource_delete') . '/([0-9]+)/([0-9]+)/([0-9A-Za-z]+)/?(.*?)/?$', 'index.php?page=item&action=deleteResource&id=$1&item=$2&code=$3&secret=$4');
                    // Item rules
                    $id_pos = stripos($item_url, '{ITEM_ID}');
                    $title_pos = stripos($item_url, '{ITEM_TITLE}');
                    $cat_pos = stripos($item_url, '{CATEGORIES');
                    $param_pos = 1;
                    if ($title_pos !== false && $id_pos > $title_pos) {
                        $param_pos++;
                    }
                    if ($cat_pos !== false && $id_pos > $cat_pos) {
                        $param_pos++;
                    }
                    $comments_pos = 1;
                    if ($id_pos !== false) {
                        $comments_pos++;
                    }
                    if ($title_pos !== false) {
                        $comments_pos++;
                    }
                    if ($cat_pos !== false) {
                        $comments_pos++;
                    }
                    $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$3&lang=$1_$2&comments-page=$4');
                    $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$1&comments-page=$2');
                    $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$3&lang=$1_$2');
                    $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$1');
                    // User rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_login') . '/?$', 'index.php?page=login');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_dashboard') . '/?$', 'index.php?page=user&action=dashboard');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_logout') . '/?$', 'index.php?page=main&action=logout');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_register') . '/?$', 'index.php?page=register&action=register');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=register&action=validate&id=$1&code=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate_alert') . '/([0-9]+)/([a-zA-Z0-9]+)/(.+)$', 'index.php?page=user&action=activate_alert&id=$1&email=$3&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/?$', 'index.php?page=user&action=profile');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/([0-9]+)/?$', 'index.php?page=user&action=pub_profile&id=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/(.+)/?$', 'index.php?page=user&action=pub_profile&username=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_items') . '/?$', 'index.php?page=user&action=items');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_alerts') . '/?$', 'index.php?page=user&action=alerts');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_recover') . '/?$', 'index.php?page=login&action=recover');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_forgot') . '/([0-9]+)/(.*)/?$', 'index.php?page=login&action=forgot&userId=$1&code=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_password') . '/?$', 'index.php?page=user&action=change_password');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email') . '/?$', 'index.php?page=user&action=change_email');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_username') . '/?$', 'index.php?page=user&action=change_username');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email_confirm') . '/([0-9]+)/(.*?)/?$', 'index.php?page=user&action=change_email_confirm&userId=$1&code=$2');
                    // Page rules
                    $pos_pID = stripos($page_url, '{PAGE_ID}');
                    $pos_pSlug = stripos($page_url, '{PAGE_SLUG}');
                    $pID_pos = 1;
                    $pSlug_pos = 1;
                    if (is_numeric($pos_pID) && is_numeric($pos_pSlug)) {
                        // set the order of the parameters
                        if ($pos_pID > $pos_pSlug) {
                            $pID_pos++;
                        } else {
                            $pSlug_pos++;
                        }
                        $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&id=$' . $pID_pos . "&slug=\$" . $pSlug_pos);
                        $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&lang=$1_$2&id=$' . ($pID_pos + 2) . '&slug=$' . ($pSlug_pos + 2));
                    } else {
                        if (is_numeric($pos_pID)) {
                            $rewrite->addRule('^' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&id=$1');
                            $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&id=$3');
                        } else {
                            $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&slug=$1');
                            $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&slug=$3');
                        }
                    }
                    // Clean archive files
                    $rewrite->addRule('^(.+?)\\.php(.*)$', '$1.php$2');
                    // Category rules
                    $id_pos = stripos($item_url, '{CATEGORY_ID}');
                    $title_pos = stripos($item_url, '{CATEGORY_NAME}');
                    $cat_pos = stripos($item_url, '{CATEGORIES');
                    $param_pos = 1;
                    if ($title_pos !== false && $id_pos > $title_pos) {
                        $param_pos++;
                    }
                    if ($cat_pos !== false && $id_pos > $cat_pos) {
                        $param_pos++;
                    }
                    $rewrite->addRule('^' . str_replace('{CATEGORIES}', '(.+)', str_replace('{CATEGORY_NAME}', '([^/]+)', str_replace('{CATEGORY_ID}', '([0-9]+)', $cat_url))) . '/([0-9]+)$', 'index.php?page=search&sCategory=$' . $param_pos . '&iPage=$' . ($param_pos + 1));
                    $rewrite->addRule('^' . str_replace('{CATEGORIES}', '(.+)', str_replace('{CATEGORY_NAME}', '([^/]+)', str_replace('{CATEGORY_ID}', '([0-9]+)', $cat_url))) . '/?$', 'index.php?page=search&sCategory=$' . $param_pos);
                    $rewrite->addRule('^(.+)/([0-9]+)$', 'index.php?page=search&iPage=$2');
                    $rewrite->addRule('^(.+)$', 'index.php?page=search');
                    osc_run_hook("after_rewrite_rules", array(&$rewrite));
                    //Write rule to DB
                    $rewrite->setRules();
                    osc_set_preference('seo_url_search_prefix', rtrim(Params::getParam('seo_url_search_prefix'), '/'));
                    $msg_error = '<br/>' . _m('All fields are required.') . " " . sprintf(_mn('One field was not updated', '%s fields were not updated', $errors), $errors);
                    switch ($status) {
                        case 1:
                            $msg = _m("Permalinks structure updated");
                            if ($errors > 0) {
                                $msg .= $msg_error;
                                osc_add_flash_warning_message($msg, 'admin');
                            } else {
                                osc_add_flash_ok_message($msg, 'admin');
                            }
                            break;
                        case 2:
                            $msg = _m("Permalinks structure updated.");
                            $msg .= " ";
                            $msg .= _m("However, we can't check if Apache module <b>mod_rewrite</b> is loaded. If you experience some problems with the URLs, you should deactivate <em>Friendly URLs</em>");
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            osc_add_flash_warning_message($msg, 'admin');
                            break;
                        case 3:
                            $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content.");
                            $msg .= " ";
                            $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file, please deactivate the <em>Friendly URLs</em> option.");
                            $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>';
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            osc_add_flash_error_message($msg, 'admin');
                            break;
                        case 4:
                            $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content.");
                            $msg .= " ";
                            $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file or experience some problems with the URLs, please deactivate the <em>Friendly URLs</em> option.");
                            $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>';
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            osc_add_flash_error_message($msg, 'admin');
                            break;
                        case 5:
                            $warning = false;
                            if (file_exists($htaccess_file)) {
                                $htaccess_content = file_get_contents($htaccess_file);
                                if ($htaccess_content != $htaccess) {
                                    $msg = _m("File <b>.htaccess</b> already exists and was not modified.");
                                    $msg .= " ";
                                    $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't modify the file or experience some problems with the URLs, please deactivate the <em>Friendly URLs</em> option.");
                                    $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>';
                                    $warning = true;
                                } else {
                                    $msg = _m("Permalinks structure updated");
                                }
                            }
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            if ($errors > 0 || $warning) {
                                osc_add_flash_warning_message($msg, 'admin');
                            } else {
                                osc_add_flash_ok_message($msg, 'admin');
                            }
                            break;
                    }
                } else {
                    osc_set_preference('rewriteEnabled', 0);
                    osc_set_preference('mod_rewrite_loaded', 0);
                    $deleted = true;
                    if (file_exists($htaccess_file)) {
                        $htaccess_content = file_get_contents($htaccess_file);
                        if ($htaccess_content == $htaccess) {
                            $deleted = @unlink($htaccess_file);
                            $same_content = true;
                        } else {
                            $deleted = false;
                            $same_content = false;
                        }
                    }
                    if ($deleted) {
                        osc_add_flash_ok_message(_m('Friendly URLs successfully deactivated'), 'admin');
                    } else {
                        if ($same_content) {
                            osc_add_flash_warning_message(_m('Friendly URLs deactivated, but .htaccess file could not be deleted. Please, remove it manually'), 'admin');
                        } else {
                            osc_add_flash_warning_message(_m('Friendly URLs deactivated, but .htaccess file was modified outside Osclass and was not deleted'), 'admin');
                        }
                    }
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=permalinks');
                break;
        }
    }
Пример #18
0
 function doModel()
 {
     switch ($this->action) {
         case 'add':
             // caliing add view
             $this->doView('languages/add.php');
             break;
         case 'add_post':
             // adding a new language
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_translations_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The translation folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     if (osc_checkLocales()) {
                         $msg = _m('The language has been installed correctly');
                         osc_add_flash_ok_message($msg, 'admin');
                     } else {
                         $msg = _m('There was a problem adding the language');
                         osc_add_flash_error_message($msg, 'admin');
                     }
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_warning_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=languages&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the language');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'edit':
             // editing a language
             $sLocale = Params::getParam('id');
             if (!preg_match('/.{2}_.{2}/', $sLocale)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $aLocale = $this->localeManager->findByPrimaryKey($sLocale);
             if (count($aLocale) == 0) {
                 osc_add_flash_error_message(_m('Language id doesn\'t exist'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $this->_exportVariableToView("aLocale", $aLocale);
             $this->doView('languages/frm.php');
             break;
         case 'edit_post':
             // edit language post
             $iUpdated = 0;
             $languageCode = Params::getParam('pk_c_code');
             $enabledWebstie = Params::getParam('b_enabled');
             $enabledBackoffice = Params::getParam('b_enabled_bo');
             $languageName = Params::getParam('s_name');
             $languageShortName = Params::getParam('s_short_name');
             $languageDescription = Params::getParam('s_description');
             $languageCurrencyFormat = Params::getParam('s_currency_format');
             $languageDecPoint = Params::getParam('s_dec_point');
             $languageNumDec = Params::getParam('i_num_dec');
             $languageThousandsSep = Params::getParam('s_thousands_sep');
             $languageDateFormat = Params::getParam('s_date_format');
             $languageStopWords = Params::getParam('s_stop_words');
             // formatting variables
             if (!preg_match('/.{2}_.{2}/', $languageCode)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $enabledWebstie = $enabledWebstie != '' ? true : false;
             $enabledBackoffice = $enabledBackoffice != '' ? true : false;
             $languageName = strip_tags($languageName);
             $languageName = trim($languageName);
             if ($languageName == '') {
                 osc_add_flash_error_message(_m('Language name can\'t be empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $languageShortName = strip_tags($languageShortName);
             $languageShortName = trim($languageShortName);
             if ($languageShortName == '') {
                 osc_add_flash_error_message(_m('Language short name can\'t be empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $languageDescription = strip_tags($languageDescription);
             $languageDescription = trim($languageDescription);
             if ($languageDescription == '') {
                 osc_add_flash_error_message(_m('Language description can\'t be empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $languageCurrencyFormat = strip_tags($languageCurrencyFormat);
             $languageCurrencyFormat = trim($languageCurrencyFormat);
             $languageDateFormat = strip_tags($languageDateFormat);
             $languageDateFormat = trim($languageDateFormat);
             $languageStopWords = strip_tags($languageStopWords);
             $languageStopWords = trim($languageStopWords);
             $array = array('b_enabled' => $enabledWebstie, 'b_enabled_bo' => $enabledBackoffice, 's_name' => $languageName, 's_short_name' => $languageShortName, 's_description' => $languageDescription, 's_currency_format' => $languageCurrencyFormat, 's_dec_point' => $languageDecPoint, 'i_num_dec' => $languageNumDec, 's_thousands_sep' => $languageThousandsSep, 's_date_format' => $languageDateFormat, 's_stop_words' => $languageStopWords);
             $iUpdated = $this->localeManager->update($array, array('pk_c_code' => $languageCode));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(sprintf(_m('%s has been updated'), $languageShortName), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable':
         case 'enable_bo':
             $default_lang = osc_language();
             $id = Params::getParam('id');
             $enabled = Params::getParam('enabled');
             if ($id) {
                 if ($action == 'enable' && $default_lang == $id && $enabled == 0) {
                     osc_add_flash_error_message(sprintf(_m('The language can\'t be disabled because it\'s the default language. You can change modify it in General Settings'), $i), 'admin');
                 } else {
                     $msg = $enabled == 1 ? _m('The language has been enabled for the public website') : _m('The language has been disabled for the public website');
                     $aValues = array('b_enabled' => $enabled);
                     $this->localeManager->update($aValues, array('pk_c_code' => $id));
                 }
                 if ($action == 'enable_bo') {
                     $msg = $enabled == 1 ? _m('The language has been enabled for the backoffice (oc-admin)') : _m('The language has been disabled for the backoffice (oc-admin)');
                     $aValues = array('b_enabled_bo' => $enabled);
                     $this->localeManager->update($aValues, array('pk_c_code' => $id));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the language. The language id was lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_selected':
             $msg = _m('Selected languages have been enabled for the website');
             $aValues = array('b_enabled' => 1);
             $id = Params::getParam('id');
             if ($id != '') {
                 foreach ($id as $i) {
                     $this->localeManager->update($aValues, array('pk_c_code' => $i));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_selected':
             $msg = _m('Selected languages have been disabled for the website');
             $aValues = array('b_enabled' => 0);
             $id = Params::getParam('id');
             if ($id != '') {
                 $default_lang = osc_language();
                 foreach ($id as $i) {
                     if ($default_lang == $i) {
                         $msg = _m('The language can\'t be disabled because it\'s the default language. You can change the default language under General Settings in order to disable it');
                     } else {
                         $this->localeManager->update($aValues, array('pk_c_code' => $i));
                     }
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_bo_selected':
             $msg = _m('Selected languages have been enabled for the backoffice (oc-admin)');
             $aValues = array('b_enabled_bo' => 1);
             $id = Params::getParam('id');
             if ($id != '') {
                 foreach ($id as $i) {
                     $this->localeManager->update($aValues, array('pk_c_code' => $i));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_bo_selected':
             $msg = _m('Selected languages have been disabled for the backoffice (oc-admin)');
             $aValues = array('b_enabled_bo' => 0);
             $id = Params::getParam('id');
             if ($id != '') {
                 foreach ($id as $i) {
                     $this->localeManager->update($aValues, array('pk_c_code' => $i));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'delete':
             if (is_array(Params::getParam('id'))) {
                 $default_lang = osc_language();
                 foreach (Params::getParam('id') as $code) {
                     if ($default_lang != $code) {
                         $this->localeManager->deleteLocale($code);
                         if (!osc_deleteDir(osc_translations_path() . $code)) {
                             osc_add_flash_error_message(sprintf(_m('Directory "%s" couldn\'t be removed'), $code), 'admin');
                         } else {
                             osc_add_flash_ok_message(sprintf(_m('Directory "%s" has been successfully removed'), $code), 'admin');
                         }
                     } else {
                         osc_add_flash_error_message(sprintf(_m('Directory "%s" couldn\'t be removed because it\'s the default language. Set another language as default first and try again'), $code), 'admin');
                     }
                 }
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         default:
             $locales = OSCLocale::newInstance()->listAll();
             $this->_exportVariableToView("locales", $locales);
             $this->doView('languages/index.php');
             break;
     }
 }
Пример #19
0
    function doModel()
    {
        switch ($this->action) {
            case 'comments':
                //calling the comments settings view
                $this->doView('settings/comments.php');
                break;
            case 'comments_post':
                // updating comment
                $iUpdated = 0;
                $enabledComments = Params::getParam('enabled_comments');
                $enabledComments = $enabledComments != '' ? true : false;
                $moderateComments = Params::getParam('moderate_comments');
                $moderateComments = $moderateComments != '' ? true : false;
                $numModerateComments = Params::getParam('num_moderate_comments');
                $commentsPerPage = Params::getParam('comments_per_page');
                $notifyNewComment = Params::getParam('notify_new_comment');
                $notifyNewComment = $notifyNewComment != '' ? true : false;
                $notifyNewCommentUser = Params::getParam('notify_new_comment_user');
                $notifyNewCommentUser = $notifyNewCommentUser != '' ? true : false;
                $regUserPostComments = Params::getParam('reg_user_post_comments');
                $regUserPostComments = $regUserPostComments != '' ? true : false;
                $msg = '';
                if (!osc_validate_int(Params::getParam("num_moderate_comments"))) {
                    $msg .= _m("Number of moderate comments must only contain numeric characters") . "<br/>";
                }
                if (!osc_validate_int(Params::getParam("comments_per_page"))) {
                    $msg .= _m("Comments per page must only contain numeric characters") . "<br/>";
                }
                if ($msg != '') {
                    osc_add_flash_error_message($msg, 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments');
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledComments), array('s_name' => 'enabled_comments'));
                if ($moderateComments) {
                    $iUpdated += Preference::newInstance()->update(array('s_value' => $numModerateComments), array('s_name' => 'moderate_comments'));
                } else {
                    $iUpdated += Preference::newInstance()->update(array('s_value' => '-1'), array('s_name' => 'moderate_comments'));
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewComment), array('s_name' => 'notify_new_comment'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewCommentUser), array('s_name' => 'notify_new_comment_user'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $commentsPerPage), array('s_name' => 'comments_per_page'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPostComments), array('s_name' => 'reg_user_post_comments'));
                if ($iUpdated > 0) {
                    osc_add_flash_ok_message(_m("Comment settings have been updated"), 'admin');
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments');
                break;
            case 'locations':
                // calling the locations settings view
                $location_action = Params::getParam('type');
                $mCountries = new Country();
                switch ($location_action) {
                    case 'add_country':
                        // add country
                        $countryCode = strtoupper(Params::getParam('c_country'));
                        $countryName = Params::getParam('country');
                        $exists = $mCountries->findByCode($countryCode);
                        if (isset($exists['s_name'])) {
                            osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $countryName), 'admin');
                        } else {
                            $countries_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=country_code&term=' . urlencode($countryCode));
                            $countries = json_decode($countries_json);
                            $mCountries->insert(array('pk_c_code' => $countryCode, 's_name' => $countryName));
                            CountryStats::newInstance()->setNumItems($countryCode, 0);
                            if (isset($countries->error)) {
                                // Country is not in our GEO database
                                // We have no region for user-typed countries
                            } else {
                                // Country is in our GEO database, add regions and cities
                                $manager_region = new Region();
                                $regions_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=region&country_code=' . urlencode($countryCode) . '&term=all');
                                $regions = json_decode($regions_json);
                                if (!isset($regions->error)) {
                                    if (count($regions) > 0) {
                                        foreach ($regions as $r) {
                                            $manager_region->insert(array("fk_c_country_code" => $r->country_code, "s_name" => $r->name));
                                            $id = $manager_region->dao->insertedId();
                                            RegionStats::newInstance()->setNumItems($id, 0);
                                        }
                                    }
                                    unset($regions);
                                    unset($regions_json);
                                    $manager_city = new City();
                                    if (count($countries) > 0) {
                                        foreach ($countries as $c) {
                                            $regions = $manager_region->findByCountry($c->id);
                                            if (!isset($regions->error)) {
                                                if (count($regions) > 0) {
                                                    foreach ($regions as $region) {
                                                        $cities_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=city&country=' . urlencode($c->name) . '&region=' . urlencode($region['s_name']) . '&term=all');
                                                        $cities = json_decode($cities_json);
                                                        if (!isset($cities->error)) {
                                                            if (count($cities) > 0) {
                                                                foreach ($cities as $ci) {
                                                                    $manager_city->insert(array("fk_i_region_id" => $region['pk_i_id'], "s_name" => $ci->name, "fk_c_country_code" => $ci->country_code));
                                                                    $id = $manager_city->dao->insertedId();
                                                                    CityStats::newInstance()->setNumItems($id, 0);
                                                                }
                                                            }
                                                        }
                                                        unset($cities);
                                                        unset($cities_json);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                        break;
                    case 'edit_country':
                        // edit country
                        $ok = $mCountries->update(array('s_name' => Params::getParam('e_country')), array('pk_c_code' => Params::getParam('country_code')));
                        if ($ok) {
                            osc_add_flash_ok_message(_m('Country has been edited'), 'admin');
                        } else {
                            osc_add_flash_error_message(_m('There were some problems editing the country'), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                        break;
                    case 'delete_country':
                        // delete country
                        $countryId = Params::getParam('id');
                        Item::newInstance()->deleteByRegion($countryId);
                        $mRegions = new Region();
                        $mCities = new City();
                        $aCountries = $mCountries->findByCode($countryId);
                        $aRegions = $mRegions->findByCountry($aCountries['pk_c_code']);
                        foreach ($aRegions as $region) {
                            // remove city_stats
                            CityStats::newInstance()->deleteByRegion($region['pk_i_id']);
                            // remove region_stats
                            RegionStats::newInstance()->delete(array('fk_i_region_id' => $region['pk_i_id']));
                        }
                        //remove country stats
                        CountryStats::newInstance()->delete(array('fk_c_country_code' => $aCountries['pk_c_code']));
                        $ok = $mCountries->deleteByPrimaryKey($aCountries['pk_c_code']);
                        if ($ok) {
                            osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aCountries['s_name']), 'admin');
                        } else {
                            osc_add_flash_error_message(sprintf(_m('There was a problem deleting %s'), $aCountries['s_name']), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                        break;
                    case 'add_region':
                        // add region
                        if (!Params::getParam('r_manual')) {
                            $this->install_location_by_region();
                        } else {
                            $mRegions = new Region();
                            $regionName = Params::getParam('region');
                            $countryCode = Params::getParam('country_c_parent');
                            $country = Country::newInstance()->findByCode($countryCode);
                            $exists = $mRegions->findByName($regionName, $countryCode);
                            if (!isset($exists['s_name'])) {
                                $data = array('fk_c_country_code' => $countryCode, 's_name' => $regionName);
                                $mRegions->insert($data);
                                $id = $mRegions->dao->insertedId();
                                RegionStats::newInstance()->setNumItems($id, 0);
                                osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin');
                            } else {
                                osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $regionName), 'admin');
                            }
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$countryCode . "&country=" . @$country['s_name']);
                        break;
                    case 'edit_region':
                        // edit region
                        $mRegions = new Region();
                        $newRegion = Params::getParam('e_region');
                        $regionId = Params::getParam('region_id');
                        $exists = $mRegions->findByName($newRegion);
                        if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $regionId) {
                            if ($regionId != '') {
                                $aRegion = $mRegions->findByPrimaryKey($regionId);
                                $country = Country::newInstance()->findByCode($aRegion['fk_c_country_code']);
                                $mRegions->update(array('s_name' => $newRegion), array('pk_i_id' => $regionId));
                                ItemLocation::newInstance()->update(array('s_region' => $newRegion), array('fk_i_region_id' => $regionId));
                                osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newRegion), 'admin');
                            }
                        } else {
                            osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newRegion), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name']);
                        break;
                    case 'delete_region':
                        // delete region
                        $mRegion = new Region();
                        $mCities = new City();
                        $regionId = Params::getParam('id');
                        if ($regionId != '') {
                            Item::newInstance()->deleteByRegion($regionId);
                            $aRegion = $mRegion->findByPrimaryKey($regionId);
                            $country = Country::newInstance()->findByCode($aRegion['fk_c_country_code']);
                            // remove city_stats
                            CityStats::newInstance()->deleteByRegion($regionId);
                            $mCities->delete(array('fk_i_region_id' => $regionId));
                            // remove region_stats
                            RegionStats::newInstance()->delete(array('fk_i_region_id' => $regionId));
                            $mRegion->delete(array('pk_i_id' => $regionId));
                            osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aRegion['s_name']), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name']);
                        break;
                    case 'add_city':
                        // add city
                        $mRegion = new Region();
                        $mCities = new City();
                        $regionId = Params::getParam('region_parent');
                        $countryCode = Params::getParam('country_c_parent');
                        $newCity = Params::getParam('city');
                        $exists = $mCities->findByName($newCity, $regionId);
                        $region = $mRegion->findByPrimaryKey($regionId);
                        $country = Country::newInstance()->findByCode($region['fk_c_country_code']);
                        if (!isset($exists['s_name'])) {
                            $mCities->insert(array('fk_i_region_id' => $regionId, 's_name' => $newCity, 'fk_c_country_code' => $countryCode));
                            $id = $mCities->dao->insertedId();
                            CityStats::newInstance()->setNumItems($id, 0);
                            osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $newCity), 'admin');
                        } else {
                            osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "&region=" . $regionId);
                        break;
                    case 'edit_city':
                        // edit city
                        $mRegion = new Region();
                        $mCities = new City();
                        $newCity = Params::getParam('e_city');
                        $cityId = Params::getParam('city_id');
                        $exists = $mCities->findByName($newCity);
                        if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $cityId) {
                            $city = $mCities->findByPrimaryKey($cityId);
                            $region = $mRegion->findByPrimaryKey($city['fk_i_region_id']);
                            $country = Country::newInstance()->findByCode($region['fk_c_country_code']);
                            $mCities->update(array('s_name' => $newCity), array('pk_i_id' => $cityId));
                            ItemLocation::newInstance()->update(array('s_city' => $newCity), array('fk_i_city_id' => $cityId));
                            osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newCity), 'admin');
                        } else {
                            osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "&region=" . @$region['pk_i_id']);
                        break;
                    case 'delete_city':
                        // delete city
                        $mRegion = new Region();
                        $mCities = new City();
                        $cityId = Params::getParam('id');
                        Item::newInstance()->deleteByCity($cityId);
                        $aCity = $mCities->findByPrimaryKey($cityId);
                        // remove region_stats
                        $region = $mRegion->findByPrimaryKey($aCity['fk_i_region_id']);
                        $country = Country::newInstance()->findByCode($region['fk_c_country_code']);
                        CityStats::newInstance()->delete(array('fk_i_city_id' => $cityId));
                        $mCities->delete(array('pk_i_id' => $cityId));
                        osc_add_flash_ok_message(sprintf(_m('%s has been deleted'), $aCity['s_name']), 'admin');
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "&region=" . @$region['pk_i_id']);
                        break;
                }
                $aCountries = $mCountries->listAll();
                $this->_exportVariableToView('aCountries', $aCountries);
                $this->doView('settings/locations.php');
                break;
            case 'permalinks':
                // calling the permalinks view
                $htaccess = Params::getParam('htaccess_status');
                $file = Params::getParam('file_status');
                $this->_exportVariableToView('htaccess', $htaccess);
                $this->_exportVariableToView('file', $file);
                $this->doView('settings/permalinks.php');
                break;
            case 'permalinks_post':
                // updating permalinks option
                $htaccess_file = osc_base_path() . '.htaccess';
                $rewriteEnabled = Params::getParam('rewrite_enabled') ? true : false;
                if ($rewriteEnabled) {
                    Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'rewriteEnabled'));
                    $rewrite_base = REL_WEB_URL;
                    $htaccess = <<<HTACCESS
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase {$rewrite_base}
    RewriteRule ^index\\.php\$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . {$rewrite_base}index.php [L]
</IfModule>
HTACCESS;
                    // 1. OK (ok)
                    // 2. OK no apache module detected (warning)
                    // 3. No se puede crear + apache
                    // 4. No se puede crear + no apache
                    $status = 3;
                    if (file_exists($htaccess_file)) {
                        if (is_writable($htaccess_file) && file_put_contents($htaccess_file, $htaccess)) {
                            $status = 1;
                        }
                    } else {
                        if (is_writable(osc_base_path()) && file_put_contents($htaccess_file, $htaccess)) {
                            $status = 1;
                        }
                    }
                    if (!@apache_mod_loaded('mod_rewrite')) {
                        $status++;
                    }
                    $errors = 0;
                    $item_url = substr(str_replace('//', '/', Params::getParam('rewrite_item_url') . '/'), 0, -1);
                    if (!osc_validate_text($item_url)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $item_url), array('s_name' => 'rewrite_item_url'));
                    }
                    $page_url = substr(str_replace('//', '/', Params::getParam('rewrite_page_url') . '/'), 0, -1);
                    if (!osc_validate_text($page_url)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $page_url), array('s_name' => 'rewrite_page_url'));
                    }
                    $cat_url = substr(str_replace('//', '/', Params::getParam('rewrite_cat_url') . '/'), 0, -1);
                    if (!osc_validate_text($cat_url)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $cat_url), array('s_name' => 'rewrite_cat_url'));
                    }
                    $search_url = substr(str_replace('//', '/', Params::getParam('rewrite_search_url') . '/'), 0, -1);
                    if (!osc_validate_text($search_url)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $search_url), array('s_name' => 'rewrite_search_url'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_country'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_country')), array('s_name' => 'rewrite_search_country'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_region'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_region')), array('s_name' => 'rewrite_search_region'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_city'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_city')), array('s_name' => 'rewrite_search_city'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_city_area'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_city_area')), array('s_name' => 'rewrite_search_city_area'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_category'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_category')), array('s_name' => 'rewrite_search_category'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_user'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_user')), array('s_name' => 'rewrite_search_user'));
                    }
                    if (!osc_validate_text(Params::getParam('rewrite_search_pattern'))) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_pattern')), array('s_name' => 'rewrite_search_pattern'));
                    }
                    $rewrite_contact = substr(str_replace('//', '/', Params::getParam('rewrite_contact') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_contact)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_contact), array('s_name' => 'rewrite_contact'));
                    }
                    $rewrite_feed = substr(str_replace('//', '/', Params::getParam('rewrite_feed') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_feed)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_feed), array('s_name' => 'rewrite_feed'));
                    }
                    $rewrite_language = substr(str_replace('//', '/', Params::getParam('rewrite_language') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_language)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_language), array('s_name' => 'rewrite_language'));
                    }
                    $rewrite_item_mark = substr(str_replace('//', '/', Params::getParam('rewrite_item_mark') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_mark)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_mark), array('s_name' => 'rewrite_item_mark'));
                    }
                    $rewrite_item_send_friend = substr(str_replace('//', '/', Params::getParam('rewrite_item_send_friend') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_send_friend)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_send_friend), array('s_name' => 'rewrite_item_send_friend'));
                    }
                    $rewrite_item_contact = substr(str_replace('//', '/', Params::getParam('rewrite_item_contact') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_contact)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_contact), array('s_name' => 'rewrite_item_contact'));
                    }
                    $rewrite_item_new = substr(str_replace('//', '/', Params::getParam('rewrite_item_new') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_new)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_new), array('s_name' => 'rewrite_item_new'));
                    }
                    $rewrite_item_activate = substr(str_replace('//', '/', Params::getParam('rewrite_item_activate') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_activate)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_activate), array('s_name' => 'rewrite_item_activate'));
                    }
                    $rewrite_item_edit = substr(str_replace('//', '/', Params::getParam('rewrite_item_edit') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_edit)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_edit), array('s_name' => 'rewrite_item_edit'));
                    }
                    $rewrite_item_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_delete') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_delete)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_delete), array('s_name' => 'rewrite_item_delete'));
                    }
                    $rewrite_item_resource_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_resource_delete') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_item_resource_delete)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_item_resource_delete), array('s_name' => 'rewrite_item_resource_delete'));
                    }
                    $rewrite_user_login = substr(str_replace('//', '/', Params::getParam('rewrite_user_login') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_login)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_login), array('s_name' => 'rewrite_user_login'));
                    }
                    $rewrite_user_dashboard = substr(str_replace('//', '/', Params::getParam('rewrite_user_dashboard') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_dashboard)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_dashboard), array('s_name' => 'rewrite_user_dashboard'));
                    }
                    $rewrite_user_logout = substr(str_replace('//', '/', Params::getParam('rewrite_user_logout') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_logout)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_logout), array('s_name' => 'rewrite_user_logout'));
                    }
                    $rewrite_user_register = substr(str_replace('//', '/', Params::getParam('rewrite_user_register') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_register)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_register), array('s_name' => 'rewrite_user_register'));
                    }
                    $rewrite_user_activate = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_activate)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_activate), array('s_name' => 'rewrite_user_activate'));
                    }
                    $rewrite_user_activate_alert = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate_alert') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_activate_alert)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_activate_alert), array('s_name' => 'rewrite_user_activate_alert'));
                    }
                    $rewrite_user_profile = substr(str_replace('//', '/', Params::getParam('rewrite_user_profile') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_profile)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_profile), array('s_name' => 'rewrite_user_profile'));
                    }
                    $rewrite_user_items = substr(str_replace('//', '/', Params::getParam('rewrite_user_items') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_items)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_items), array('s_name' => 'rewrite_user_items'));
                    }
                    $rewrite_user_alerts = substr(str_replace('//', '/', Params::getParam('rewrite_user_alerts') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_alerts)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_alerts), array('s_name' => 'rewrite_user_alerts'));
                    }
                    $rewrite_user_recover = substr(str_replace('//', '/', Params::getParam('rewrite_user_recover') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_recover)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_recover), array('s_name' => 'rewrite_user_recover'));
                    }
                    $rewrite_user_forgot = substr(str_replace('//', '/', Params::getParam('rewrite_user_forgot') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_forgot)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_forgot), array('s_name' => 'rewrite_user_forgot'));
                    }
                    $rewrite_user_change_password = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_password') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_password)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_change_password), array('s_name' => 'rewrite_user_change_password'));
                    }
                    $rewrite_user_change_email = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_email)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_change_email), array('s_name' => 'rewrite_user_change_email'));
                    }
                    $rewrite_user_change_email_confirm = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email_confirm') . '/'), 0, -1);
                    if (!osc_validate_text($rewrite_user_change_email_confirm)) {
                        $errors += 1;
                    } else {
                        Preference::newInstance()->update(array('s_value' => $rewrite_user_change_email_confirm), array('s_name' => 'rewrite_user_change_email_confirm'));
                    }
                    osc_reset_preferences();
                    $rewrite = Rewrite::newInstance();
                    osc_run_hook("before_rewrite_rules", array(&$rewrite));
                    $rewrite->clearRules();
                    /*****************************
                     ********* Add rules *********
                     *****************************/
                    // Contact rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_contact') . '/?$', 'index.php?page=contact');
                    // Feed rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/?$', 'index.php?page=search&sFeed=rss');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/(.+)/?$', 'index.php?page=search&sFeed=$1');
                    // Language rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_language') . '/(.*?)/?$', 'index.php?page=language&locale=$1');
                    // Search rules
                    $rewrite->addRule('^' . $search_url . '$', 'index.php?page=search');
                    $rewrite->addRule('^' . $search_url . '/(.*)$', 'index.php?page=search&sParams=$1');
                    // Item rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_mark') . '/(.*?)/([0-9]+)/?$', 'index.php?page=item&action=mark&as=$1&id=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_send_friend') . '/([0-9]+)/?$', 'index.php?page=item&action=send_friend&id=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_contact') . '/([0-9]+)/?$', 'index.php?page=item&action=contact&id=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/?$', 'index.php?page=item&action=item_add');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/([0-9]+)/?$', 'index.php?page=item&action=item_add&catId=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=activate&id=$1&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_edit') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_edit&id=$1&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_delete') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_delete&id=$1&secret=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_item_resource_delete') . '/([0-9]+)/([0-9]+)/([0-9A-Za-z]+)/?(.*?)/?$', 'index.php?page=item&action=deleteResource&id=$1&item=$2&code=$3&secret=$4');
                    // Item rules
                    $id_pos = stripos($item_url, '{ITEM_ID}');
                    $title_pos = stripos($item_url, '{ITEM_TITLE}');
                    $cat_pos = stripos($item_url, '{CATEGORIES');
                    $param_pos = 1;
                    if ($title_pos !== false && $id_pos > $title_pos) {
                        $param_pos++;
                    }
                    if ($cat_pos !== false && $id_pos > $cat_pos) {
                        $param_pos++;
                    }
                    $comments_pos = 1;
                    if ($id_pos !== false) {
                        $comments_pos++;
                    }
                    if ($title_pos !== false) {
                        $comments_pos++;
                    }
                    if ($cat_pos !== false) {
                        $comments_pos++;
                    }
                    $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$1&comments-page=$2');
                    $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$3&lang=$1_$2&comments-page=$4');
                    $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$1');
                    $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$3&lang=$1_$2');
                    // User rules
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_login') . '/?$', 'index.php?page=login');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_dashboard') . '/?$', 'index.php?page=user&action=dashboard');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_logout') . '/?$', 'index.php?page=main&action=logout');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_register') . '/?$', 'index.php?page=register&action=register');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=register&action=validate&id=$1&code=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate_alert') . '/([a-zA-Z0-9]+)/(.+)$', 'index.php?page=user&action=activate_alert&email=$2&secret=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/?$', 'index.php?page=user&action=profile');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/([0-9]+)/?$', 'index.php?page=user&action=pub_profile&id=$1');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_items') . '/?$', 'index.php?page=user&action=items');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_alerts') . '/?$', 'index.php?page=user&action=alerts');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_recover') . '/?$', 'index.php?page=login&action=recover');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_forgot') . '/([0-9]+)/(.*)/?$', 'index.php?page=login&action=forgot&userId=$1&code=$2');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_password') . '/?$', 'index.php?page=user&action=change_password');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email') . '/?$', 'index.php?page=user&action=change_email');
                    $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email_confirm') . '/([0-9]+)/(.*?)/?$', 'index.php?page=user&action=change_email_confirm&userId=$1&code=$2');
                    // Page rules
                    $pos_pID = stripos($page_url, '{PAGE_ID}');
                    $pos_pSlug = stripos($page_url, '{PAGE_SLUG}');
                    $pID_pos = 1;
                    $pSlug_pos = 1;
                    if (is_numeric($pos_pID) && is_numeric($pos_pSlug)) {
                        // set the order of the parameters
                        if ($pos_pID > $pos_pSlug) {
                            $pID_pos++;
                        } else {
                            $pSlug_pos++;
                        }
                        $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&id=$' . $pID_pos . "&slug=\$" . $pSlug_pos);
                        $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&lang=$1_$2&id=$' . ($pID_pos + 2) . '&slug=$' . ($pSlug_pos + 2));
                    } else {
                        if (is_numeric($pos_pID)) {
                            $rewrite->addRule('^' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&id=$1');
                            $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&id=$3');
                        } else {
                            $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&slug=$1');
                            $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&slug=$3');
                        }
                    }
                    // Clean archive files
                    $rewrite->addRule('^(.+?)\\.php(.*)$', '$1.php$2');
                    // Category rules
                    $id_pos = stripos($item_url, '{CATEGORY_ID}');
                    $title_pos = stripos($item_url, '{CATEGORY_SLUG}');
                    $cat_pos = stripos($item_url, '{CATEGORIES');
                    $param_pos = 1;
                    if ($title_pos !== false && $id_pos > $title_pos) {
                        $param_pos++;
                    }
                    if ($cat_pos !== false && $id_pos > $cat_pos) {
                        $param_pos++;
                    }
                    $rewrite->addRule('^' . str_replace('{CATEGORIES}', '(.+)', str_replace('{CATEGORY_SLUG}', '([^/]+)', str_replace('{CATEGORY_ID}', '([0-9]+)', $cat_url))) . '$', 'index.php?page=search&sCategory=$' . $param_pos);
                    osc_run_hook("after_rewrite_rules", array(&$rewrite));
                    //Write rule to DB
                    $rewrite->setRules();
                    $msg_error = '<br/>' . _m('All fields are required.') . " " . sprintf(_mn('One field was not updated', '%s fields were not updated', $errors), $errors);
                    switch ($status) {
                        case 1:
                            $msg = _m("Permalinks structure updated");
                            if ($errors > 0) {
                                $msg .= $msg_error;
                                osc_add_flash_warning_message($msg, 'admin');
                            } else {
                                osc_add_flash_ok_message($msg, 'admin');
                            }
                            break;
                        case 2:
                            $msg = _m("Permalinks structure updated.");
                            $msg .= " ";
                            $msg .= _m("However, we can't check if Apache module <b>mod_rewrite</b> is loaded. If you experience some problems with the URLs, you should deactivate <em>Friendly URLs</em>");
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            osc_add_flash_warning_message($msg, 'admin');
                            break;
                        case 3:
                            $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content.");
                            $msg .= " ";
                            $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file, please deactivate the <em>Friendly URLs</em> option.");
                            $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>';
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            osc_add_flash_error_message($msg, 'admin');
                            break;
                        case 4:
                            $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content.");
                            $msg .= " ";
                            $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file or experience some problems with the URLs, please deactivate the <em>Friendly URLs</em> option.");
                            $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>';
                            if ($errors > 0) {
                                $msg .= $msg_error;
                            }
                            osc_add_flash_error_message($msg, 'admin');
                            break;
                    }
                } else {
                    Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'rewriteEnabled'));
                    Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded'));
                    osc_add_flash_ok_message(_m('Friendly URLs successfully deactivated'), 'admin');
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=permalinks');
                break;
            case 'spamNbots':
                // calling the spam and bots view
                $akismet_key = osc_akismet_key();
                $akismet_status = 3;
                if ($akismet_key != '') {
                    require_once osc_lib_path() . 'Akismet.class.php';
                    $akismet_obj = new Akismet(osc_base_url(), $akismet_key);
                    $akismet_status = 2;
                    if ($akismet_obj->isKeyValid()) {
                        $akismet_status = 1;
                    }
                }
                View::newInstance()->_exportVariableToView('akismet_status', $akismet_status);
                $this->doView('settings/spamNbots.php');
                break;
            case 'akismet_post':
                // updating spam and bots option
                $updated = 0;
                $akismetKey = Params::getParam('akismetKey');
                $akismetKey = trim($akismetKey);
                $updated = Preference::newInstance()->update(array('s_value' => $akismetKey), array('s_name' => 'akismetKey'));
                if ($akismetKey == '') {
                    osc_add_flash_info_message(_m('Your Akismet key has been cleared'), 'admin');
                } else {
                    osc_add_flash_ok_message(_m('Your Akismet key has been updated'), 'admin');
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots');
                break;
            case 'recaptcha_post':
                // updating spam and bots option
                $iUpdated = 0;
                $recaptchaPrivKey = Params::getParam('recaptchaPrivKey');
                $recaptchaPrivKey = trim($recaptchaPrivKey);
                $recaptchaPubKey = Params::getParam('recaptchaPubKey');
                $recaptchaPubKey = trim($recaptchaPubKey);
                $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPrivKey), array('s_name' => 'recaptchaPrivKey'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPubKey), array('s_name' => 'recaptchaPubKey'));
                if ($recaptchaPubKey == '') {
                    osc_add_flash_info_message(_m('Your reCAPTCHA key has been cleared'), 'admin');
                } else {
                    osc_add_flash_ok_message(_m('Your reCAPTCHA key has been updated'), 'admin');
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots');
                break;
            case 'currencies':
                // currencies settings
                $currencies_action = Params::getParam('type');
                switch ($currencies_action) {
                    case 'add':
                        // calling add currency view
                        $aCurrency = array('pk_c_code' => '', 's_name' => '', 's_description' => '');
                        $this->_exportVariableToView('aCurrency', $aCurrency);
                        $this->_exportVariableToView('typeForm', 'add_post');
                        $this->doView('settings/currency_form.php');
                        break;
                    case 'add_post':
                        // adding a new currency
                        $currencyCode = Params::getParam('pk_c_code');
                        $currencyName = Params::getParam('s_name');
                        $currencyDescription = Params::getParam('s_description');
                        // cleaning parameters
                        $currencyName = strip_tags($currencyName);
                        $currencyDescription = strip_tags($currencyDescription);
                        $currencyCode = strip_tags($currencyCode);
                        $currencyCode = trim($currencyCode);
                        if (!preg_match('/^.{1,3}$/', $currencyCode)) {
                            osc_add_flash_error_message(_m('The currency code is not in the correct format'), 'admin');
                            $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        }
                        $fields = array('pk_c_code' => $currencyCode, 's_name' => $currencyName, 's_description' => $currencyDescription);
                        $isInserted = Currency::newInstance()->insert($fields);
                        if ($isInserted) {
                            osc_add_flash_ok_message(_m('Currency added'), 'admin');
                        } else {
                            osc_add_flash_error_message(_m("Currency couldn't be added"), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        break;
                    case 'edit':
                        // calling edit currency view
                        $currencyCode = Params::getParam('code');
                        $currencyCode = strip_tags($currencyCode);
                        $currencyCode = trim($currencyCode);
                        if ($currencyCode == '') {
                            osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin');
                            $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        }
                        $aCurrency = Currency::newInstance()->findByPrimaryKey($currencyCode);
                        if (!$aCurrency) {
                            osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin');
                            $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        }
                        $this->_exportVariableToView('aCurrency', $aCurrency);
                        $this->_exportVariableToView('typeForm', 'edit_post');
                        $this->doView('settings/currency_form.php');
                        break;
                    case 'edit_post':
                        // updating currency
                        $currencyName = Params::getParam('s_name');
                        $currencyDescription = Params::getParam('s_description');
                        $currencyCode = Params::getParam('pk_c_code');
                        // cleaning parameters
                        $currencyName = strip_tags($currencyName);
                        $currencyDescription = strip_tags($currencyDescription);
                        $currencyCode = strip_tags($currencyCode);
                        $currencyCode = trim($currencyCode);
                        if (!preg_match('/.{1,3}/', $currencyCode)) {
                            osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin');
                            $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        }
                        $updated = Currency::newInstance()->update(array('s_name' => $currencyName, 's_description' => $currencyDescription), array('pk_c_code' => $currencyCode));
                        if ($updated == 1) {
                            osc_add_flash_ok_message(_m('Currency updated'), 'admin');
                        } else {
                            osc_add_flash_info_message(_m('No changes were made'), 'admin');
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        break;
                    case 'delete':
                        // deleting a currency
                        $rowChanged = 0;
                        $aCurrencyCode = Params::getParam('code');
                        if (!is_array($aCurrencyCode)) {
                            $aCurrencyCode = array($aCurrencyCode);
                        }
                        $msg_current = '';
                        foreach ($aCurrencyCode as $currencyCode) {
                            if (preg_match('/.{1,3}/', $currencyCode) && $currencyCode != osc_currency()) {
                                $rowChanged += Currency::newInstance()->delete(array('pk_c_code' => $currencyCode));
                            }
                            // foreign key error
                            if (Currency::newInstance()->getErrorLevel() == '1451') {
                                $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it has listings associated to it"), $currencyCode);
                            } else {
                                if ($currencyCode == osc_currency()) {
                                    $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it's the default currency"), $currencyCode);
                                }
                            }
                        }
                        $msg = '';
                        $status = '';
                        switch ($rowChanged) {
                            case '0':
                                $msg = _m('No currencies have been deleted');
                                $status = 'error';
                                break;
                            case '1':
                                $msg = _m('One currency has been deleted');
                                $status = 'ok';
                                break;
                            default:
                                $msg = sprintf(_m('%s currencies have been deleted'), $rowChanged);
                                $status = 'ok';
                                break;
                        }
                        if ($status == 'ok' && $msg_current != '') {
                            $status = 'warning';
                        }
                        switch ($status) {
                            case 'error':
                                osc_add_flash_error_message($msg . $msg_current, 'admin');
                                break;
                            case 'warning':
                                osc_add_flash_warning_message($msg . $msg_current, 'admin');
                                break;
                            case 'ok':
                                osc_add_flash_ok_message($msg, 'admin');
                                break;
                        }
                        $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                        break;
                    default:
                        // calling the currencies view
                        $aCurrencies = Currency::newInstance()->listAll();
                        $this->_exportVariableToView('aCurrencies', $aCurrencies);
                        $this->doView('settings/currencies.php');
                        break;
                }
                break;
            case 'mailserver':
                // calling the mailserver view
                $this->doView('settings/mailserver.php');
                break;
            case 'mailserver_post':
                if (defined('DEMO')) {
                    osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver');
                }
                // updating mailserver
                $iUpdated = 0;
                $mailserverAuth = Params::getParam('mailserver_auth');
                $mailserverAuth = $mailserverAuth != '' ? true : false;
                $mailserverPop = Params::getParam('mailserver_pop');
                $mailserverPop = $mailserverPop != '' ? true : false;
                $mailserverType = Params::getParam('mailserver_type');
                $mailserverHost = Params::getParam('mailserver_host');
                $mailserverPort = Params::getParam('mailserver_port');
                $mailserverUsername = Params::getParam('mailserver_username');
                $mailserverPassword = Params::getParam('mailserver_password');
                $mailserverSsl = Params::getParam('mailserver_ssl');
                if (!in_array($mailserverType, array('custom', 'gmail'))) {
                    osc_add_flash_error_message(_m('Mail server type is incorrect'), 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver');
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverAuth), array('s_name' => 'mailserver_auth'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPop), array('s_name' => 'mailserver_pop'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverType), array('s_name' => 'mailserver_type'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverHost), array('s_name' => 'mailserver_host'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPort), array('s_name' => 'mailserver_port'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverUsername), array('s_name' => 'mailserver_username'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPassword), array('s_name' => 'mailserver_password'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverSsl), array('s_name' => 'mailserver_ssl'));
                if ($iUpdated > 0) {
                    osc_add_flash_ok_message(_m('Mail server configuration has changed'), 'admin');
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver');
                break;
            case 'media':
                // calling the media view
                $max_upload = (int) ini_get('upload_max_filesize');
                $max_post = (int) ini_get('post_max_size');
                $memory_limit = (int) ini_get('memory_limit');
                $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024;
                $this->_exportVariableToView('max_size_upload', $upload_mb);
                $this->doView('settings/media.php');
                break;
            case 'media_post':
                // updating the media config
                $status = 'ok';
                $error = '';
                $iUpdated = 0;
                $maxSizeKb = Params::getParam('maxSizeKb');
                $allowedExt = Params::getParam('allowedExt');
                $dimThumbnail = Params::getParam('dimThumbnail');
                $dimPreview = Params::getParam('dimPreview');
                $dimNormal = Params::getParam('dimNormal');
                $keepOriginalImage = Params::getParam('keep_original_image');
                $use_imagick = Params::getParam('use_imagick');
                $type_watermark = Params::getParam('watermark_type');
                $watermark_color = Params::getParam('watermark_text_color');
                $watermark_text = Params::getParam('watermark_text');
                switch ($type_watermark) {
                    case 'none':
                        $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image'));
                        break;
                    case 'text':
                        $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_color), array('s_name' => 'watermark_text_color'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_text), array('s_name' => 'watermark_text'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_text_place')), array('s_name' => 'watermark_place'));
                        break;
                    case 'image':
                        // upload image & move to path
                        if ($_FILES['watermark_image']['error'] == UPLOAD_ERR_OK) {
                            if ($_FILES['watermark_image']['type'] == 'image/png') {
                                $tmpName = $_FILES['watermark_image']['tmp_name'];
                                $path = osc_content_path() . 'uploads/watermark.png';
                                if (move_uploaded_file($tmpName, $path)) {
                                    $iUpdated += Preference::newInstance()->update(array('s_value' => $path), array('s_name' => 'watermark_image'));
                                } else {
                                    $error .= _m('There was a problem uploading the watermark image') . "<br />";
                                }
                            } else {
                                $error .= _m('The watermark image has to be a .PNG file') . "<br />";
                            }
                        } else {
                            $error .= _m('There was a problem uploading the watermark image') . "<br />";
                        }
                        $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text'));
                        $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_image_place')), array('s_name' => 'watermark_place'));
                        break;
                    default:
                        break;
                }
                // format parameters
                $maxSizeKb = strip_tags($maxSizeKb);
                $allowedExt = strip_tags($allowedExt);
                $dimThumbnail = strip_tags($dimThumbnail);
                $dimPreview = strip_tags($dimPreview);
                $dimNormal = strip_tags($dimNormal);
                $keepOriginalImage = $keepOriginalImage != '' ? true : false;
                $use_imagick = $use_imagick != '' ? true : false;
                // is imagick extension loaded?
                if (!@extension_loaded('imagick')) {
                    $use_imagick = false;
                }
                // max size allowed by PHP configuration?
                $max_upload = (int) ini_get('upload_max_filesize');
                $max_post = (int) ini_get('post_max_size');
                $memory_limit = (int) ini_get('memory_limit');
                $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024;
                // set maxSizeKB equals to PHP configuration if it's bigger
                if ($maxSizeKb > $upload_mb) {
                    $status = 'warning';
                    $maxSizeKb = $upload_mb;
                    // flash message text warning
                    $error .= sprintf(_m("You cannot set a maximum file size higher than the one allowed in the PHP configuration: <b>%d KB</b>"), $upload_mb);
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $maxSizeKb), array('s_name' => 'maxSizeKb'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $allowedExt), array('s_name' => 'allowedExt'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $dimThumbnail), array('s_name' => 'dimThumbnail'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $dimPreview), array('s_name' => 'dimPreview'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $dimNormal), array('s_name' => 'dimNormal'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $keepOriginalImage), array('s_name' => 'keep_original_image'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $use_imagick), array('s_name' => 'use_imagick'));
                if ($error != '') {
                    switch ($status) {
                        case 'error':
                            osc_add_flash_error_message($error, 'admin');
                            break;
                        case 'warning':
                            osc_add_flash_warning_message($error, 'admin');
                            break;
                        default:
                            osc_add_flash_ok_message($error, 'admin');
                            break;
                    }
                } else {
                    osc_add_flash_ok_message(_m('Media config has been updated'), 'admin');
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
                break;
            case 'images_post':
                if (defined('DEMO')) {
                    osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
                }
                $wat = new Watermark();
                $aResources = ItemResource::newInstance()->getAllResources();
                foreach ($aResources as $resource) {
                    osc_run_hook('regenerate_image', $resource);
                    $path = osc_content_path() . 'uploads/';
                    // comprobar que no haya original
                    $img_original = $path . $resource['pk_i_id'] . "_original*";
                    $aImages = glob($img_original);
                    // there is original image
                    if (count($aImages) == 1) {
                        $image_tmp = $aImages[0];
                    } else {
                        $img_normal = $path . $resource['pk_i_id'] . ".*";
                        $aImages = glob($img_normal);
                        if (count($aImages) == 1) {
                            $image_tmp = $aImages[0];
                        } else {
                            $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*";
                            $aImages = glob($img_thumbnail);
                            $image_tmp = $aImages[0];
                        }
                    }
                    // extension
                    preg_match('/\\.(.*)$/', $image_tmp, $matches);
                    if (isset($matches[1])) {
                        $extension = $matches[1];
                        // Create normal size
                        $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg';
                        $size = explode('x', osc_normal_dimensions());
                        ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path);
                        if (osc_is_watermark_text()) {
                            $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg');
                        } elseif (osc_is_watermark_image()) {
                            $wat->doWatermarkImage($path, 'image/jpeg');
                        }
                        // Create preview
                        $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg';
                        $size = explode('x', osc_preview_dimensions());
                        ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                        // Create thumbnail
                        $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg';
                        $size = explode('x', osc_thumbnail_dimensions());
                        ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                        // update resource info
                        ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id']));
                        osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id']));
                        // si extension es direfente a jpg, eliminar las imagenes con $extension si hay
                        if ($extension != 'jpg') {
                            @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "." . $extension);
                            @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_original." . $extension);
                            @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_preview." . $extension);
                            @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_thumbnail." . $extension);
                        }
                        // ....
                    } else {
                        // no es imagen o imagen sin extesión
                    }
                }
                osc_add_flash_ok_message(_m('Re-generation complete'), 'admin');
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
                break;
            case 'update':
                // update index view
                $iUpdated = 0;
                $sPageTitle = Params::getParam('pageTitle');
                $sPageDesc = Params::getParam('pageDesc');
                $sContactEmail = Params::getParam('contactEmail');
                $sLanguage = Params::getParam('language');
                $sDateFormat = Params::getParam('dateFormat');
                $sCurrency = Params::getParam('currency');
                $sWeekStart = Params::getParam('weekStart');
                $sTimeFormat = Params::getParam('timeFormat');
                $sTimezone = Params::getParam('timezone');
                $sNumRssItems = Params::getParam('num_rss_items');
                $maxLatestItems = Params::getParam('max_latest_items_at_home');
                $numItemsSearch = Params::getParam('default_results_per_page');
                $contactAttachment = Params::getParam('enabled_attachment');
                $selectableParent = Params::getParam('selectable_parent_categories');
                $bAutoCron = Params::getParam('auto_cron');
                $bMarketSources = Params::getParam('market_external_sources') == 1 ? 1 : 0;
                // preparing parameters
                $sPageTitle = strip_tags($sPageTitle);
                $sPageDesc = strip_tags($sPageDesc);
                $sContactEmail = strip_tags($sContactEmail);
                $sLanguage = strip_tags($sLanguage);
                $sDateFormat = strip_tags($sDateFormat);
                $sCurrency = strip_tags($sCurrency);
                $sWeekStart = strip_tags($sWeekStart);
                $sTimeFormat = strip_tags($sTimeFormat);
                $sNumRssItems = (int) strip_tags($sNumRssItems);
                $maxLatestItems = (int) strip_tags($maxLatestItems);
                $numItemsSearch = (int) $numItemsSearch;
                $contactAttachment = $contactAttachment != '' ? true : false;
                $bAutoCron = $bAutoCron != '' ? true : false;
                $error = "";
                $msg = '';
                if (!osc_validate_text($sPageTitle)) {
                    $msg .= _m("Page title field is required") . "<br/>";
                }
                if (!osc_validate_text($sContactEmail)) {
                    $msg .= _m("Contact email field is required") . "<br/>";
                }
                if (!osc_validate_int($sNumRssItems)) {
                    $msg .= _m("Number of listings in the RSS has to be a numeric value") . "<br/>";
                }
                if (!osc_validate_int($maxLatestItems)) {
                    $msg .= _m("Max latest listings has to be a numeric value") . "<br/>";
                }
                if (!osc_validate_int($numItemsSearch)) {
                    $msg .= _m("Number of listings on search has to be a numeric value") . "<br/>";
                }
                if ($msg != '') {
                    osc_add_flash_error_message($msg, 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings');
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageTitle), array('s_section' => 'osclass', 's_name' => 'pageTitle'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageDesc), array('s_section' => 'osclass', 's_name' => 'pageDesc'));
                if (!defined('DEMO')) {
                    $iUpdated += Preference::newInstance()->update(array('s_value' => $sContactEmail), array('s_section' => 'osclass', 's_name' => 'contactEmail'));
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sLanguage), array('s_section' => 'osclass', 's_name' => 'language'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sDateFormat), array('s_section' => 'osclass', 's_name' => 'dateFormat'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sCurrency), array('s_section' => 'osclass', 's_name' => 'currency'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sWeekStart), array('s_section' => 'osclass', 's_name' => 'weekStart'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimeFormat), array('s_section' => 'osclass', 's_name' => 'timeFormat'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimezone), array('s_section' => 'osclass', 's_name' => 'timezone'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $bMarketSources), array('s_section' => 'osclass', 's_name' => 'marketAllowExternalSources'));
                if (is_int($sNumRssItems)) {
                    $iUpdated += Preference::newInstance()->update(array('s_value' => $sNumRssItems), array('s_section' => 'osclass', 's_name' => 'num_rss_items'));
                } else {
                    if ($error != '') {
                        $error .= "</p><p>";
                    }
                    $error .= _m('Number of listings in the RSS must be an integer');
                }
                if (is_int($maxLatestItems)) {
                    $iUpdated += Preference::newInstance()->update(array('s_value' => $maxLatestItems), array('s_section' => 'osclass', 's_name' => 'maxLatestItems@home'));
                } else {
                    if ($error != '') {
                        $error .= "</p><p>";
                    }
                    $error .= _m('Number of recent listings displayed at home must be an integer');
                }
                $iUpdated += Preference::newInstance()->update(array('s_value' => $numItemsSearch), array('s_section' => 'osclass', 's_name' => 'defaultResultsPerPage@search'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $contactAttachment), array('s_name' => 'contact_attachment'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $bAutoCron), array('s_name' => 'auto_cron'));
                $iUpdated += Preference::newInstance()->update(array('s_value' => $selectableParent), array('s_name' => 'selectable_parent_categories'));
                if ($iUpdated > 0) {
                    if ($error != '') {
                        osc_add_flash_error_message($error . "</p><p>" . _m('General settings have been updated'), 'admin');
                    } else {
                        osc_add_flash_ok_message(_m('General settings have been updated'), 'admin');
                    }
                } else {
                    if ($error != '') {
                        osc_add_flash_error_message($error, 'admin');
                    }
                }
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings');
                break;
            case 'check_updates':
                osc_admin_toolbar_update_themes(true);
                osc_admin_toolbar_update_plugins(true);
                osc_add_flash_ok_message(_m('Last check') . ':   ' . date("Y-m-d H:i"), 'admin');
                $this->redirectTo(osc_admin_base_url(true) . '?page=settings');
                break;
            case 'latestsearches':
                //calling the comments settings view
                $this->doView('settings/searches.php');
                break;
            case 'latestsearches_post':
                // updating comment
                if (Params::getParam('save_latest_searches') == 'on') {
                    Preference::newInstance()->update(array('s_value' => 1), array('s_name' => 'save_latest_searches'));
                } else {
                    Preference::newInstance()->update(array('s_value' => 0), array('s_name' => 'save_latest_searches'));
                }
                if (Params::getParam('customPurge') == '') {
                    osc_add_flash_error_message(_m('Custom number could not be left empty'), 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches');
                } else {
                    Preference::newInstance()->update(array('s_value' => Params::getParam('customPurge')), array('s_name' => 'purge_latest_searches'));
                    osc_add_flash_ok_message(_m('Last search settings have been updated'), 'admin');
                    $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches');
                }
                break;
            default:
                // calling the view
                $aLanguages = OSCLocale::newInstance()->listAllEnabled();
                $aCurrencies = Currency::newInstance()->listAll();
                $this->_exportVariableToView('aLanguages', $aLanguages);
                $this->_exportVariableToView('aCurrencies', $aCurrencies);
                $this->doView('settings/index.php');
                break;
        }
    }
Пример #20
0
 function doModel()
 {
     switch ($this->action) {
         case 'import':
             // calling import view
             $this->doView('tools/import.php');
             break;
         case 'import_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import');
             }
             // calling
             $sql = Params::getFiles('sql');
             if (isset($sql['size']) && $sql['size'] != 0) {
                 $content_file = file_get_contents($sql['tmp_name']);
                 $conn = DBConnectionClass::newInstance();
                 $c_db = $conn->getOsclassDb();
                 $comm = new DBCommandClass($c_db);
                 if ($comm->importSQL($content_file)) {
                     osc_add_flash_ok_message(_m('Import complete'), 'admin');
                 } else {
                     osc_add_flash_error_message(_m('There was a problem importing data to the database'), 'admin');
                 }
             } else {
                 osc_add_flash_error_message(_m('No file was uploaded'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=import');
             break;
         case 'images':
             // calling images view
             $this->doView('tools/images.php');
             break;
         case 'images_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images');
             }
             $preferences = Preference::newInstance()->toArray();
             $wat = new Watermark();
             $aResources = ItemResource::newInstance()->getAllResources();
             foreach ($aResources as $resource) {
                 osc_run_hook('regenerate_image', $resource);
                 $path = osc_content_path() . 'uploads/';
                 // comprobar que no haya original
                 $img_original = $path . $resource['pk_i_id'] . "_original*";
                 $aImages = glob($img_original);
                 // there is original image
                 if (count($aImages) == 1) {
                     $image_tmp = $aImages[0];
                 } else {
                     $img_normal = $path . $resource['pk_i_id'] . ".*";
                     $aImages = glob($img_normal);
                     if (count($aImages) == 1) {
                         $image_tmp = $aImages[0];
                     } else {
                         $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*";
                         $aImages = glob($img_thumbnail);
                         $image_tmp = $aImages[0];
                     }
                 }
                 // extension
                 preg_match('/\\.(.*)$/', $image_tmp, $matches);
                 if (isset($matches[1])) {
                     $extension = $matches[1];
                     // Create normal size
                     $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg';
                     $size = explode('x', osc_normal_dimensions());
                     ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path);
                     if (osc_is_watermark_text()) {
                         $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg');
                     } elseif (osc_is_watermark_image()) {
                         $wat->doWatermarkImage($path, 'image/jpeg');
                     }
                     // Create preview
                     $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg';
                     $size = explode('x', osc_preview_dimensions());
                     ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                     // Create thumbnail
                     $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg';
                     $size = explode('x', osc_thumbnail_dimensions());
                     ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                     // update resource info
                     ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id']));
                     osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id']));
                     // si extension es direfente a jpg, eliminar las imagenes con $extension si hay
                     if ($extension != 'jpg') {
                         $files_to_remove = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "*" . $extension;
                         $fs = glob($files_to_remove);
                         if (is_array($fs)) {
                             array_map("unlink", $fs);
                         }
                     }
                     // ....
                 } else {
                     // no es imagen o imagen sin extesión
                 }
             }
             osc_add_flash_ok_message(_m('Re-generation complete'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=images');
             break;
         case 'upgrade':
             $this->doView('tools/upgrade.php');
             break;
         case 'backup':
             $this->doView('tools/backup.php');
             break;
         case 'backup-sql':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             }
             //databasse dump...
             if (Params::getParam('bck_dir') != '') {
                 $path = trim(Params::getParam('bck_dir'));
                 if (substr($path, -1, 1) != "/") {
                     $path .= '/';
                 }
             } else {
                 $path = osc_base_path();
             }
             $filename = 'OSClass_mysqlbackup.' . date('YmdHis') . '.sql';
             switch (osc_dbdump($path, $filename)) {
                 case -1:
                     $msg = _m('Path is empty');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -2:
                     $msg = sprintf(_m('Could not connect with the database. Error: %s'), mysql_error());
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -3:
                     $msg = sprintf(_m('Could not select the database. Error: %s'), mysql_error());
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -4:
                     $msg = _m('There are no tables to back up');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case -5:
                     $msg = _m('The folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 default:
                     $msg = _m('Backup has been done properly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             break;
         case 'backup-zip':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             }
             //zip of the code just to back it up
             if (Params::getParam('bck_dir') != '') {
                 $archive_name = trim(Params::getParam('bck_dir'));
                 if (substr(trim($archive_name), -1, 1) != "/") {
                     $archive_name .= '/';
                 }
                 $archive_name = Params::getParam('bck_dir') . '/OSClass_backup.' . date('YmdHis') . '.zip';
             } else {
                 $archive_name = osc_base_path() . "OSClass_backup." . date('YmdHis') . ".zip";
             }
             $archive_folder = osc_base_path();
             if (osc_zip_folder($archive_folder, $archive_name)) {
                 $msg = _m('Archiving successful!');
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 $msg = _m('Error, the zip file was not created at the specified directory');
                 osc_add_flash_error_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=backup');
             break;
         case 'backup_post':
             $this->doView('tools/backup.php');
             break;
         case 'maintenance':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->doView('tools/maintenance.php');
                 break;
             }
             $mode = Params::getParam('mode');
             if ($mode == 'on') {
                 $maintenance_file = ABS_PATH . '.maintenance';
                 $fileHandler = @fopen($maintenance_file, 'w');
                 if ($fileHandler) {
                     osc_add_flash_ok_message(_m('Maintenance mode is ON'), 'admin');
                 } else {
                     osc_add_flash_error_message(_m('There was an error creating .maintenance file, please create it manually at the root folder'), 'admin');
                 }
                 fclose($fileHandler);
                 $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance');
             } else {
                 if ($mode == 'off') {
                     $deleted = @unlink(ABS_PATH . '.maintenance');
                     if ($deleted) {
                         osc_add_flash_ok_message(_m('Maintenance mode is OFF'), 'admin');
                     } else {
                         osc_add_flash_error_message(_m('There was an error removing .maintenance file, please remove it manually from the root folder'), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=tools&action=maintenance');
                 }
             }
             $this->doView('tools/maintenance.php');
             break;
         default:
     }
 }
Пример #21
0
 function doModel()
 {
     switch ($this->action) {
         case 'register':
             //register user
             $this->doView('user-register.php');
             break;
         case 'register_post':
             //register user
             osc_csrf_check();
             if (!osc_users_enabled()) {
                 osc_add_flash_error_message(_m('Users are not enabled'));
                 $this->redirectTo(osc_base_url());
             }
             osc_run_hook('before_user_register');
             $banned = osc_is_banned(Params::getParam('s_email'));
             if ($banned == 1) {
                 osc_add_flash_error_message(_m('Your current email is not allowed'));
                 $this->redirectTo(osc_register_account_url());
             } else {
                 if ($banned == 2) {
                     osc_add_flash_error_message(_m('Your current IP is not allowed'));
                     $this->redirectTo(osc_register_account_url());
                 }
             }
             require_once LIB_PATH . 'osclass/UserActions.php';
             $userActions = new UserActions(false);
             $success = $userActions->add();
             switch ($success) {
                 case 1:
                     osc_add_flash_ok_message(_m('The user has been created. An activation email has been sent'));
                     $this->redirectTo(osc_base_url());
                     break;
                 case 2:
                     osc_add_flash_ok_message(_m('Your account has been created successfully'));
                     $this->doView('user-login.php');
                     break;
                 case 3:
                     osc_add_flash_warning_message(_m('The specified e-mail is already in use'));
                     $this->doView('user-register.php');
                     break;
                 case 4:
                     osc_add_flash_error_message(_m('The reCAPTCHA was not entered correctly'));
                     $this->doView('user-register.php');
                     break;
                 case 5:
                     osc_add_flash_warning_message(_m('The email is not valid'));
                     $this->doView('user-register.php');
                     break;
                 case 6:
                     osc_add_flash_warning_message(_m('The password cannot be empty'));
                     $this->doView('user-register.php');
                     break;
                 case 7:
                     osc_add_flash_warning_message(_m("Passwords don't match"));
                     $this->doView('user-register.php');
                     break;
                 case 8:
                     osc_add_flash_warning_message(_m("Username is already taken"));
                     $this->doView('user-register.php');
                     break;
                 case 9:
                     osc_add_flash_warning_message(_m("The specified username is not valid, it contains some invalid words"));
                     $this->doView('user-register.php');
                     break;
             }
             break;
         case 'validate':
             //validate account
             $id = intval(Params::getParam('id'));
             $code = Params::getParam('code');
             $userManager = new User();
             $user = $userManager->findByIdSecret($id, $code);
             if (!$user) {
                 osc_add_flash_error_message(_m('The link is not valid anymore. Sorry for the inconvenience!'));
                 $this->redirectTo(osc_base_url());
             }
             if ($user['b_active'] == 1) {
                 osc_add_flash_error_message(_m('Your account has already been validated'));
                 $this->redirectTo(osc_base_url());
             }
             $userManager = new User();
             $userManager->update(array('b_active' => '1'), array('pk_i_id' => $id, 's_secret' => $code));
             // Auto-login
             Session::newInstance()->_set('userId', $user['pk_i_id']);
             Session::newInstance()->_set('userName', $user['s_name']);
             Session::newInstance()->_set('userEmail', $user['s_email']);
             $phone = $user['s_phone_mobile'] ? $user['s_phone_mobile'] : $user['s_phone_land'];
             Session::newInstance()->_set('userPhone', $phone);
             osc_run_hook('hook_email_user_registration', $user);
             osc_run_hook('validate_user', $user);
             osc_add_flash_ok_message(_m('Your account has been validated'));
             $this->redirectTo(osc_base_url());
             break;
     }
 }
Пример #22
0
 function doModel()
 {
     switch ($this->action) {
         case 'media':
             // calling the media view
             $max_upload = (int) ini_get('upload_max_filesize');
             $max_post = (int) ini_get('post_max_size');
             $memory_limit = (int) ini_get('memory_limit');
             $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024;
             $this->_exportVariableToView('max_size_upload', $upload_mb);
             $this->doView('settings/media.php');
             break;
         case 'media_post':
             // updating the media config
             osc_csrf_check();
             $status = 'ok';
             $error = '';
             $iUpdated = 0;
             $maxSizeKb = Params::getParam('maxSizeKb');
             $dimThumbnail = strtolower(Params::getParam('dimThumbnail'));
             $dimPreview = strtolower(Params::getParam('dimPreview'));
             $dimNormal = strtolower(Params::getParam('dimNormal'));
             $keepOriginalImage = Params::getParam('keep_original_image');
             $forceAspectImage = Params::getParam('force_aspect_image');
             $forceJPEG = Params::getParam('force_jpeg');
             $use_imagick = Params::getParam('use_imagick');
             $type_watermark = Params::getParam('watermark_type');
             $watermark_color = Params::getParam('watermark_text_color');
             $watermark_text = Params::getParam('watermark_text');
             switch ($type_watermark) {
                 case 'none':
                     $iUpdated += osc_set_preference('watermark_text_color', '');
                     $iUpdated += osc_set_preference('watermark_text', '');
                     $iUpdated += osc_set_preference('watermark_image', '');
                     break;
                 case 'text':
                     $iUpdated += osc_set_preference('watermark_text_color', $watermark_color);
                     $iUpdated += osc_set_preference('watermark_text', $watermark_text);
                     $iUpdated += osc_set_preference('watermark_image', '');
                     $iUpdated += osc_set_preference('watermark_place', Params::getParam('watermark_text_place'));
                     break;
                 case 'image':
                     // upload image & move to path
                     $watermark_file = Params::getFiles('watermark_image');
                     if ($watermark_file['tmp_name'] != '' && $watermark_file['size'] > 0) {
                         if ($watermark_file['error'] == UPLOAD_ERR_OK) {
                             if ($watermark_file['type'] == 'image/png') {
                                 $tmpName = $watermark_file['tmp_name'];
                                 $path = osc_content_path() . 'uploads/watermark.png';
                                 if (move_uploaded_file($tmpName, $path)) {
                                     $iUpdated += osc_set_preference('watermark_image', $path);
                                 } else {
                                     $status = 'error';
                                     $error .= _m('There was a problem uploading the watermark image') . "<br />";
                                 }
                             } else {
                                 $status = 'error';
                                 $error .= _m('The watermark image has to be a .PNG file') . "<br />";
                             }
                         } else {
                             $status = 'error';
                             $error .= _m('There was a problem uploading the watermark image') . "<br />";
                         }
                     }
                     $iUpdated += osc_set_preference('watermark_text_color', '');
                     $iUpdated += osc_set_preference('watermark_text', '');
                     $iUpdated += osc_set_preference('watermark_place', Params::getParam('watermark_image_place'));
                     break;
                 default:
                     break;
             }
             // format parameters
             $maxSizeKb = trim(strip_tags($maxSizeKb));
             $dimThumbnail = trim(strip_tags($dimThumbnail));
             $dimPreview = trim(strip_tags($dimPreview));
             $dimNormal = trim(strip_tags($dimNormal));
             $keepOriginalImage = $keepOriginalImage != '' ? true : false;
             $forceAspectImage = $forceAspectImage != '' ? true : false;
             $forceJPEG = $forceJPEG != '' ? true : false;
             $use_imagick = $use_imagick != '' ? true : false;
             if (!preg_match('|([0-9]+)x([0-9]+)|', $dimThumbnail, $match)) {
                 $dimThumbnail = is_numeric($dimThumbnail) ? $dimThumbnail . "x" . $dimThumbnail : "100x100";
             }
             if (!preg_match('|([0-9]+)x([0-9]+)|', $dimPreview, $match)) {
                 $dimPreview = is_numeric($dimPreview) ? $dimPreview . "x" . $dimPreview : "100x100";
             }
             if (!preg_match('|([0-9]+)x([0-9]+)|', $dimNormal, $match)) {
                 $dimNormal = is_numeric($dimNormal) ? $dimNormal . "x" . $dimNormal : "100x100";
             }
             // is imagick extension loaded?
             if (!@extension_loaded('imagick')) {
                 $use_imagick = false;
             }
             // max size allowed by PHP configuration?
             $max_upload = (int) ini_get('upload_max_filesize');
             $max_post = (int) ini_get('post_max_size');
             $memory_limit = (int) ini_get('memory_limit');
             $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024;
             // set maxSizeKB equals to PHP configuration if it's bigger
             if ($maxSizeKb > $upload_mb) {
                 $status = 'warning';
                 $maxSizeKb = $upload_mb;
                 // flash message text warning
                 $error .= sprintf(_m("You cannot set a maximum file size higher than the one allowed in the PHP configuration: <b>%d KB</b>"), $upload_mb);
             }
             $iUpdated += osc_set_preference('maxSizeKb', $maxSizeKb);
             $iUpdated += osc_set_preference('dimThumbnail', $dimThumbnail);
             $iUpdated += osc_set_preference('dimPreview', $dimPreview);
             $iUpdated += osc_set_preference('dimNormal', $dimNormal);
             $iUpdated += osc_set_preference('keep_original_image', $keepOriginalImage);
             $iUpdated += osc_set_preference('force_aspect_image', $forceAspectImage);
             $iUpdated += osc_set_preference('force_jpeg', $forceJPEG);
             $iUpdated += osc_set_preference('use_imagick', $use_imagick);
             if ($error != '') {
                 switch ($status) {
                     case 'error':
                         osc_add_flash_error_message($error, 'admin');
                         break;
                     case 'warning':
                         osc_add_flash_warning_message($error, 'admin');
                         break;
                     default:
                         osc_add_flash_ok_message($error, 'admin');
                         break;
                 }
             } else {
                 osc_add_flash_ok_message(_m('Media config has been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
             break;
         case 'images_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
             }
             osc_csrf_check();
             $aResources = ItemResource::newInstance()->getAllResources();
             foreach ($aResources as $resource) {
                 osc_run_hook('regenerate_image', $resource);
                 if (strpos($resource['s_content_type'], 'image') !== false) {
                     if (file_exists(osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_original." . $resource['s_extension'])) {
                         $image_tmp = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_original." . $resource['s_extension'];
                         $use_original = true;
                     } else {
                         if (file_exists(osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "." . $resource['s_extension'])) {
                             $image_tmp = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "." . $resource['s_extension'];
                             $use_original = false;
                         } else {
                             if (file_exists(osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_preview." . $resource['s_extension'])) {
                                 $image_tmp = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . "_preview." . $resource['s_extension'];
                                 $use_original = false;
                             } else {
                                 $use_original = false;
                                 continue;
                             }
                         }
                     }
                     // Create normal size
                     $path_normal = $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '.' . $resource['s_extension'];
                     $size = explode('x', osc_normal_dimensions());
                     $img = ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1]);
                     if ($use_original) {
                         if (osc_is_watermark_text()) {
                             $img->doWatermarkText(osc_watermark_text(), osc_watermark_text_color());
                         } elseif (osc_is_watermark_image()) {
                             $img->doWatermarkImage();
                         }
                     }
                     $img->saveToFile($path);
                     // Create preview
                     $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '_preview.' . $resource['s_extension'];
                     $size = explode('x', osc_preview_dimensions());
                     ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                     // Create thumbnail
                     $path = osc_base_path() . $resource['s_path'] . $resource['pk_i_id'] . '_thumbnail.' . $resource['s_extension'];
                     $size = explode('x', osc_thumbnail_dimensions());
                     ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path);
                     osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id']));
                 } else {
                     // no es imagen o imagen sin extesión
                 }
             }
             osc_add_flash_ok_message(_m('Re-generation complete'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
             break;
     }
 }
Пример #23
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add':
             $this->doView("plugins/add.php");
             break;
         case 'add_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action cannot be done because is a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=plugins');
             }
             $package = Params::getFiles("package");
             if (isset($package['size']) && $package['size'] != 0) {
                 $path = osc_plugins_path();
                 (int) ($status = osc_unzip_file($package['tmp_name'], $path));
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The plugin folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     $msg = _m('The plugin has been uploaded correctly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_error_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=plugins&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the plugin');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'install':
             $pn = Params::getParam("plugin");
             // CATCH FATAL ERRORS
             $old_value = error_reporting(0);
             register_shutdown_function(array($this, 'errorHandler'), $pn);
             $installed = Plugins::install($pn);
             if ($installed) {
                 //run this after installing the plugin
                 Plugins::runHook('install_' . $pn);
                 osc_add_flash_ok_message(_m('Plugin installed'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('Error: Plugin already installed'), 'admin');
             }
             error_reporting($old_value);
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'uninstall':
             $pn = Params::getParam("plugin");
             Plugins::runHook($pn . '_uninstall');
             Plugins::uninstall($pn);
             osc_add_flash_ok_message(_m('Plugin uninstalled'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'enable':
             $pn = Params::getParam("plugin");
             // CATCH FATAL ERRORS
             $old_value = error_reporting(0);
             register_shutdown_function(array($this, 'errorHandler'), $pn);
             $enabled = Plugins::activate($pn);
             if ($enabled) {
                 Plugins::runHook($pn . '_enable');
                 osc_add_flash_ok_message(_m('Plugin enabled'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('Error: Plugin already enabled'), 'admin');
             }
             error_reporting($old_value);
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'disable':
             $pn = Params::getParam("plugin");
             Plugins::runHook($pn . '_disable');
             Plugins::deactivate($pn);
             osc_add_flash_ok_message(_m('Plugin disabled'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         case 'admin':
             global $active_plugins;
             $plugin = Params::getParam("plugin");
             if ($plugin != "") {
                 Plugins::runHook($plugin . '_configure');
             }
             break;
         case 'admin_post':
             Plugins::runHook('admin_post');
         case 'renderplugin':
             global $active_plugins;
             $file = Params::getParam("file");
             if ($file != "") {
                 // We pass the GET variables (in case we have somes)
                 if (preg_match('|(.+?)\\?(.*)|', $file, $match)) {
                     $file = $match[1];
                     if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) {
                         for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) {
                             //$_GET[$get_vars[1][$var_k]] = $get_vars[2][$var_k];
                             //$_REQUEST[$get_vars[1][$var_k]] = $get_vars[2][$var_k];
                             Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]);
                         }
                     }
                 } else {
                     $file = $_REQUEST['file'];
                 }
                 $this->_exportVariableToView("file", osc_plugins_path() . $file);
                 //osc_renderPluginView($file);
                 $this->doView("plugins/view.php");
             }
             break;
         case 'render':
             $file = Params::getParam("file");
             if ($file != "") {
                 // We pass the GET variables (in case we have somes)
                 if (preg_match('|(.+?)\\?(.*)|', $file, $match)) {
                     $file = $match[1];
                     if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) {
                         for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) {
                             Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]);
                         }
                     }
                 } else {
                     $file = $_REQUEST['file'];
                 }
                 $this->_exportVariableToView("file", ABS_PATH . $file);
                 $this->doView("theme/view.php");
             }
             break;
         case 'configure':
             $plugin = Params::getParam("plugin");
             if ($plugin != '') {
                 $plugin_data = Plugins::getInfo($plugin);
                 $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll());
                 $this->_exportVariableToView("selected", PluginCategory::newInstance()->listSelected($plugin_data['short_name']));
                 $this->_exportVariableToView("plugin_data", $plugin_data);
                 $this->doView("plugins/configuration.php");
             } else {
                 $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             }
             break;
         case 'configure_post':
             $plugin_short_name = Params::getParam("plugin_short_name");
             $categories = Params::getParam("categories");
             if ($plugin_short_name != "") {
                 Plugins::cleanCategoryFromPlugin($plugin_short_name);
                 if (isset($categories)) {
                     Plugins::addToCategoryPlugin($categories, $plugin_short_name);
                 }
             } else {
                 osc_add_flash_error_message(_m('No plugin selected'), 'admin');
                 $this->doView("plugins/index.php");
             }
             osc_add_flash_ok_message(_m('Configuration was saved'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=plugins");
             break;
         default:
             $this->_exportVariableToView("plugins", Plugins::listAll());
             $this->doView("plugins/index.php");
     }
 }
Пример #24
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add':
             $this->doView("appearance/add.php");
             break;
         case 'add_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             osc_csrf_check();
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_themes_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
                 @unlink($filePackage['tmp_name']);
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The theme folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     $msg = _m('The theme has been installed correctly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_error_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the theme');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'delete':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             osc_csrf_check();
             $theme = Params::getParam('webtheme');
             if ($theme != '') {
                 if ($theme != osc_current_web_theme()) {
                     if (file_exists(osc_content_path() . "themes/" . $theme . "/functions.php")) {
                         include osc_content_path() . "themes/" . $theme . "/functions.php";
                     }
                     osc_run_hook("theme_delete_" . $theme);
                     if (osc_deleteDir(osc_content_path() . "themes/" . $theme . "/")) {
                         osc_add_flash_ok_message(_m("Theme removed successfully"), "admin");
                     } else {
                         osc_add_flash_error_message(_m("There was a problem removing the theme"), "admin");
                     }
                 } else {
                     osc_add_flash_error_message(_m("Current theme can not be deleted"), "admin");
                 }
             } else {
                 osc_add_flash_error_message(_m("No theme selected"), "admin");
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
             /* widgets */
         /* widgets */
         case 'widgets':
             $info = WebThemes::newInstance()->loadThemeInfo(osc_theme());
             $this->_exportVariableToView("info", $info);
             $this->doView('appearance/widgets.php');
             break;
         case 'add_widget':
             $this->doView('appearance/add_widget.php');
             break;
         case 'edit_widget':
             $id = Params::getParam('id');
             $widget = Widget::newInstance()->findByPrimaryKey($id);
             $this->_exportVariableToView("widget", $widget);
             $this->doView('appearance/add_widget.php');
             break;
         case 'delete_widget':
             osc_csrf_check();
             Widget::newInstance()->delete(array('pk_i_id' => Params::getParam('id')));
             osc_add_flash_ok_message(_m('Widget removed correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'edit_widget_post':
             osc_csrf_check();
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             $res = Widget::newInstance()->update(array('s_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)), array('pk_i_id' => Params::getParam('id')));
             if ($res) {
                 osc_add_flash_ok_message(_m('Widget updated correctly'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('Widget cannot be updated correctly'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'add_widget_post':
             osc_csrf_check();
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             Widget::newInstance()->insert(array('s_location' => Params::getParam('location'), 'e_kind' => 'html', 's_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)));
             osc_add_flash_ok_message(_m('Widget added correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
             /* /widget */
         /* /widget */
         case 'activate':
             osc_csrf_check();
             osc_set_preference('theme', Params::getParam('theme'));
             osc_add_flash_ok_message(_m('Theme activated correctly'), 'admin');
             osc_run_hook("theme_activate", Params::getParam('theme'));
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'render':
             if (Params::existParam('route')) {
                 $routes = Rewrite::newInstance()->getRoutes();
                 $rid = Params::getParam('route');
                 $file = '../';
                 if (isset($routes[$rid]) && isset($routes[$rid]['file'])) {
                     $file = $routes[$rid]['file'];
                 }
             } else {
                 // DEPRECATED: Disclosed path in URL is deprecated, use routes instead
                 // This will be REMOVED in 3.6
                 $file = Params::getParam('file');
                 // We pass the GET variables (in case we have somes)
                 if (preg_match('|(.+?)\\?(.*)|', $file, $match)) {
                     $file = $match[1];
                     if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) {
                         for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) {
                             Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]);
                         }
                     }
                 } else {
                     $file = Params::getParam('file');
                 }
             }
             if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || !file_exists(osc_base_path() . $file)) {
                 osc_add_flash_warning_message(__('Error loading theme custom file'), 'admin');
             }
             $this->_exportVariableToView('file', osc_base_path() . $file);
             $this->doView('appearance/view.php');
             break;
         default:
             if (Params::getParam('checkUpdated') != '') {
                 osc_admin_toolbar_update_themes(true);
             }
             $themes = WebThemes::newInstance()->getListThemes();
             //preparing variables for the view
             $this->_exportVariableToView("themes", $themes);
             $this->doView('appearance/index.php');
             break;
     }
 }
 public static function ajaxPayment()
 {
     $status = AuthorizePayment::processPayment();
     if ($status == PAYMENT_PRO_COMPLETED) {
         payment_pro_cart_drop();
         osc_add_flash_ok_message(sprintf(__('Success! Please write down this transaction ID in case you have any problem: %s', 'payment_pro'), Params::getParam('braintree_transaction_id')));
         payment_pro_js_redirect_to(osc_route_url('payment-pro-done', array('tx' => Params::getParam('braintree_transaction_id'))));
     } else {
         if ($status == PAYMENT_PRO_ALREADY_PAID) {
             payment_pro_cart_drop();
             osc_add_flash_warning_message(__('Warning! This payment was already paid', 'payment_pro'));
             payment_pro_js_redirect_to(osc_route_url('payment-pro-done', array('tx' => Params::getParam('authorize_transaction_id'))));
         } else {
             printf(__('There were an error processing your payment: %s', 'payment_pro'), Params::getParam('authorize_error'));
         }
     }
 }
Пример #26
0
        function doModel()
        {
            parent::doModel();

            switch($this->action) {
                case('add'):        // callin add view
                                    $this->_exportVariableToView( 'admin', null );
                                    $this->doView('admins/frm.php');
                break;
                case('add_post'):   if( defined('DEMO') ) {
                                        osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }
                                    osc_csrf_check();
                                    // adding a new admin
                                    $sPassword = Params::getParam('s_password', false, false);
                                    $sName     = Params::getParam('s_name');
                                    $sEmail    = Params::getParam('s_email');
                                    $sUserName = Params::getParam('s_username');
                                    $bModerator = Params::getParam('b_moderator')==0?0:1;

                                    // cleaning parameters
                                    $sPassword = strip_tags($sPassword);
                                    $sPassword = trim($sPassword);
                                    $sName     = strip_tags($sName);
                                    $sName     = trim($sName);
                                    $sEmail    = strip_tags($sEmail);
                                    $sEmail    = trim($sEmail);
                                    $sUserName = strip_tags($sUserName);
                                    $sUserName = trim($sUserName);

                                    // Checks for legit data
                                    if( !osc_validate_email($sEmail, true) ) {
                                        osc_add_flash_warning_message( _m("Email invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=add');
                                    }
                                    if( !osc_validate_username($sUserName) ) {
                                        osc_add_flash_warning_message( _m("Username invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=add');
                                    }
                                    if( $sName == '' ) {
                                        osc_add_flash_warning_message( _m("Name invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true).'?page=admins&action=add');
                                    }
                                    if( $sPassword == '' ) {
                                        osc_add_flash_warning_message( _m("Password invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=add');
                                    }
                                    $admin = $this->adminManager->findByEmail($sEmail);
                                    if( $admin ) {
                                        osc_add_flash_warning_message( _m("Email already in use"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=add');
                                    }
                                    $admin = $this->adminManager->findByUsername($sUserName);
                                    if( $admin ) {
                                        osc_add_flash_warning_message( _m("Username already in use"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=add');
                                    }

                                    $array = array(
                                        's_password'    =>  osc_hash_password($sPassword),
                                        's_name'        =>  $sName,
                                        's_email'       =>  $sEmail,
                                        's_username'    =>  $sUserName,
                                        'b_moderator'   =>  $bModerator
                                    );

                                    $isInserted = $this->adminManager->insert($array);

                                    if( $isInserted ) {
                                        // send email
                                        osc_run_hook('hook_email_new_admin', array(
                                            's_name'      => $sName,
                                            's_username'  => $sUserName,
                                            's_password'  => $sPassword,
                                            's_email'     => $sEmail
                                            )
                                        );
                                        osc_add_flash_ok_message( _m('The admin has been added'), 'admin');
                                    } else {
                                        osc_add_flash_error_message( _m('There has been an error adding a new admin'), 'admin');
                                    }
                                    $this->redirectTo(osc_admin_base_url(true).'?page=admins');
                break;
                case('edit'):       // calling edit admin view
                                    $adminEdit = null;
                                    $adminId   = Params::getParam('id');

                                    if( $adminId != '' ) {
                                        $adminEdit = $this->adminManager->findByPrimaryKey((int) $adminId);
                                    } elseif( Session::newInstance()->_get('adminId') != '') {
                                        $adminEdit = $this->adminManager->findByPrimaryKey( Session::newInstance()->_get('adminId') );
                                    }

                                    if( count($adminEdit) == 0 ) {
                                        osc_add_flash_error_message( _m('There is no admin with this id'), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }

                                    $this->_exportVariableToView("admin", $adminEdit);
                                    $this->doView('admins/frm.php');
                break;
                case('edit_post'):  if( defined('DEMO') ) {
                                        osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }
                                    osc_csrf_check();
                                    // updating a new admin
                                    $iUpdated = 0;
                                    $adminId  = Params::getParam('id');

                                    $sPassword    = Params::getParam('s_password', false, false);
                                    $sPassword2   = Params::getParam('s_password2', false, false);
                                    $sOldPassword = Params::getParam('old_password', false, false);
                                    $sName        = Params::getParam('s_name');
                                    $sEmail       = Params::getParam('s_email');
                                    $sUserName    = Params::getParam('s_username');
                                    $bModerator   = Params::getParam('b_moderator')==0?0:1;

                                    // cleaning parameters
                                    $sPassword   = strip_tags($sPassword);
                                    $sPassword   = trim($sPassword);
                                    $sPassword2  = strip_tags($sPassword2);
                                    $sPassword2  = trim($sPassword2);
                                    $sName       = strip_tags($sName);
                                    $sName       = trim($sName);
                                    $sEmail      = strip_tags($sEmail);
                                    $sEmail      = trim($sEmail);
                                    $sUserName   = strip_tags($sUserName);
                                    $sUserName   = trim($sUserName);

                                    // Checks for legit data
                                    if( !osc_validate_email($sEmail, true) ) {
                                        osc_add_flash_warning_message( _m("Email invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                    }
                                    if( !osc_validate_username($sUserName) ) {
                                        osc_add_flash_warning_message( _m("Username invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                    }
                                    if( $sName == '' ) {
                                        osc_add_flash_warning_message( _m("Name invalid"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                    }

                                    $aAdmin = $this->adminManager->findByPrimaryKey($adminId);

                                    if( count($aAdmin) == 0 ) {
                                        osc_add_flash_error_message( _m("This admin doesn't exist"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }

                                    if( $aAdmin['s_email'] != $sEmail ) {
                                        if($this->adminManager->findByEmail( $sEmail ) ) {
                                            osc_add_flash_warning_message( _m('Existing email'), 'admin');
                                            $this->redirectTo(osc_admin_base_url(true).'?page=admins&action=edit&id=' . $adminId);
                                        }
                                    }

                                    if( $aAdmin['s_username'] != $sUserName ) {
                                        if( $this->adminManager->findByUsername( $sUserName ) ) {
                                            osc_add_flash_warning_message( _m('Existing username'), 'admin');
                                            $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                        }
                                    }

                                    $conditions = array('pk_i_id' => $adminId);
                                    $array      = array();

                                    if(osc_logged_admin_id()==$adminId) {
                                        if($sOldPassword != '' ) {
                                            if( $sPassword=='' ) {
                                                osc_add_flash_warning_message( _m("Password invalid"), 'admin');
                                                $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                            } else {
                                                $firstCondition  = osc_verify_password($sOldPassword, $aAdmin['s_password']);
                                                $secondCondition = ( $sPassword == $sPassword2 );
                                                if( $firstCondition && $secondCondition ) {
                                                    $array['s_password'] = osc_hash_password($sPassword);
                                                } else {
                                                    osc_add_flash_warning_message( _m("The password couldn't be updated. Passwords don't match"), 'admin');
                                                    $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                                }
                                            }
                                        }
                                    } else {
                                        if( $sPassword!='') {
                                            if($sPassword == $sPassword2) {
                                                $array['s_password'] = osc_hash_password($sPassword);
                                            } else {
                                                osc_add_flash_warning_message( _m("The password couldn't be updated. Passwords don't match"), 'admin');
                                                $this->redirectTo(osc_admin_base_url(true) . '?page=admins&action=edit&id=' . $adminId);
                                            }
                                        }
                                    }

                                    if($adminId!=osc_logged_admin_id()) {
                                        $array['b_moderator'] = $bModerator;
                                    }

                                    $array['s_name']     = Params::getParam('s_name');
                                    $array['s_username'] = $sUserName;
                                    $array['s_email']    = $sEmail;

                                    $iUpdated = $this->adminManager->update($array, $conditions);

                                    if( $iUpdated > 0 ) {
                                        osc_add_flash_ok_message( _m('The admin has been updated'), 'admin');
                                    }

                                    if( $this->isModerator() ) {
                                        $this->redirectTo(osc_admin_base_url(true));
                                    } else {
                                        $this->redirectTo(osc_admin_base_url(true).'?page=admins');
                                    }
                break;
                case('delete'):     if( defined('DEMO') ) {
                                        osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }
                                    osc_csrf_check();
                                    // deleting and admin
                                    $isDeleted = false;
                                    $adminId   = Params::getParam('id');

                                    if( !is_array($adminId) ) {
                                        osc_add_flash_error_message( _m("The admin id isn't in the correct format"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }

                                    // Verification to avoid an administrator trying to remove to itself
                                    if( in_array(Session::newInstance()->_get('adminId'), $adminId) ) {
                                        osc_add_flash_error_message( _m("The operation hasn't been completed. You're trying to remove yourself!"), 'admin');
                                        $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                                    }

                                    $isDeleted = $this->adminManager->deleteBatch( $adminId );

                                    if( $isDeleted ) {
                                        osc_add_flash_ok_message( _m('The admin has been deleted correctly'), 'admin');
                                    } else {
                                        osc_add_flash_error_message( _m('The admin couldn\'t be deleted'), 'admin');
                                    }
                                    $this->redirectTo(osc_admin_base_url(true) . '?page=admins');
                break;
                default:

                                    if(Params::getParam("action")!="") {
                                        osc_run_hook("admin_bulk_".Params::getParam("action"), Params::getParam('id'));
                                    }

                                    if( Params::getParam('iDisplayLength') == '' ) {
                                        Params::setParam('iDisplayLength', 10 );
                                    }

                                    $p_iPage      = 1;
                                    if( is_numeric(Params::getParam('iPage')) && Params::getParam('iPage') >= 1 ) {
                                        $p_iPage = Params::getParam('iPage');
                                    }
                                    Params::setParam('iPage', $p_iPage);

                                    $admins = $this->adminManager->listAll();

                                    // pagination
                                    $start = ($p_iPage-1) * Params::getParam('iDisplayLength');
                                    $limit = Params::getParam('iDisplayLength');
                                    $count = count( $admins );

                                    $displayRecords = $limit;
                                    if( ($start+$limit ) > $count ) {
                                        $displayRecords = ($start+$limit) - $count;
                                    }
                                    // ----
                                    $aData = array();
                                    $max = ($start+$limit);
                                    if($max > $count) $max = $count;
                                    for($i = $start; $i < $max; $i++) {

                                        $admin = $admins[$i];

                                        $options = array();
                                        $options[] = '<a href="' . osc_admin_base_url(true) . '?page=admins&action=edit&amp;id='  . $admin['pk_i_id'] . '">' . __('Edit') . '</a>';
                                        $options[] = '<a onclick="return delete_dialog(\'' . $admin['pk_i_id'] . '\');" href="' . osc_admin_base_url(true) . '?page=admins&action=delete&amp;id[]=' . $admin['pk_i_id'] . '">' . __('Delete') . '</a>';
                                        $auxOptions = '<ul>'.PHP_EOL;
                                        foreach( $options as $actual ) {
                                            $auxOptions .= '<li>'.$actual.'</li>'.PHP_EOL;
                                        }
                                        $actions = '<div class="actions">'.$auxOptions.'</div>'.PHP_EOL;

                                        $row = array();
                                        $row[] = '<input type="checkbox" name="id[]" value="' . $admin['pk_i_id'] . '" />';
                                        $row[] = $admin['s_username'] . $actions;
                                        $row[] = $admin['s_name'];
                                        $row[] = $admin['s_email'];

                                        $aData[] = $row;
                                    }
                                    $array['iTotalRecords']         = $displayRecords;
                                    $array['iTotalDisplayRecords']  = count($admins);
                                    $array['iDisplayLength']        = $limit;
                                    $array['aaData'] = $aData;

                                    $page  = (int)Params::getParam('iPage');
                                    if(count($array['aaData']) == 0 && $page!=1) {
                                        $total = (int)$array['iTotalDisplayRecords'];
                                        $maxPage = ceil( $total / (int)$array['iDisplayLength'] );

                                        $url = osc_admin_base_url(true).'?'.$_SERVER['QUERY_STRING'];

                                        if($maxPage==0) {
                                            $url = preg_replace('/&iPage=(\d)+/', '&iPage=1', $url);
                                            $this->redirectTo($url);
                                        }

                                        if($page > 1) {
                                            $url = preg_replace('/&iPage=(\d)+/', '&iPage='.$maxPage, $url);
                                            $this->redirectTo($url);
                                        }
                                    }

                                    $bulk_options = array(
                                        array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')),
                                        array('value' => 'delete', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected admins?'), strtolower(__('Delete'))), 'label' => __('Delete'))
                                    );
                                    $bulk_options = osc_apply_filter("admin_bulk_filter", $bulk_options);
                                    $this->_exportVariableToView('bulk_options', $bulk_options);

                                    $this->_exportVariableToView('aAdmins', $array);
                                    // calling manage admins view
                                    $this->doView('admins/index.php');
                break;
            }
        }
Пример #27
0
 function doModel()
 {
     switch ($this->action) {
         case 'add':
             // caliing add view
             $this->doView('languages/add.php');
             break;
         case 'add_post':
             // adding a new language
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             osc_csrf_check();
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_translations_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
                 @unlink($filePackage['tmp_name']);
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The translation folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     if (osc_checkLocales()) {
                         $msg = _m('The language has been installed correctly');
                         osc_add_flash_ok_message($msg, 'admin');
                     } else {
                         $msg = _m('There was a problem adding the language');
                         osc_add_flash_error_message($msg, 'admin');
                     }
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_warning_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=languages&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the language');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'edit':
             // editing a language
             $sLocale = Params::getParam('id');
             if (!preg_match('/.{2}_.{2}/', $sLocale)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $aLocale = $this->localeManager->findByPrimaryKey($sLocale);
             if (count($aLocale) == 0) {
                 osc_add_flash_error_message(_m('Language id doesn\'t exist'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $this->_exportVariableToView("aLocale", $aLocale);
             $this->doView('languages/frm.php');
             break;
         case 'edit_post':
             // edit language post
             osc_csrf_check();
             $iUpdated = 0;
             $languageCode = Params::getParam('pk_c_code');
             $enabledWebstie = Params::getParam('b_enabled');
             $enabledBackoffice = Params::getParam('b_enabled_bo');
             $languageName = Params::getParam('s_name');
             $languageShortName = Params::getParam('s_short_name');
             $languageDescription = Params::getParam('s_description');
             $languageCurrencyFormat = Params::getParam('s_currency_format');
             $languageDecPoint = Params::getParam('s_dec_point');
             $languageNumDec = Params::getParam('i_num_dec');
             $languageThousandsSep = Params::getParam('s_thousands_sep');
             $languageDateFormat = Params::getParam('s_date_format');
             $languageStopWords = Params::getParam('s_stop_words');
             // formatting variables
             if (!preg_match('/.{2}_.{2}/', $languageCode)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $enabledWebstie = $enabledWebstie != '' ? true : false;
             $enabledBackoffice = $enabledBackoffice != '' ? true : false;
             $languageName = strip_tags($languageName);
             $languageName = trim($languageName);
             $languageShortName = strip_tags($languageShortName);
             $languageShortName = trim($languageShortName);
             $languageDescription = strip_tags($languageDescription);
             $languageDescription = trim($languageDescription);
             $languageCurrencyFormat = strip_tags($languageCurrencyFormat);
             $languageCurrencyFormat = trim($languageCurrencyFormat);
             $languageDateFormat = strip_tags($languageDateFormat);
             $languageDateFormat = trim($languageDateFormat);
             $languageStopWords = strip_tags($languageStopWords);
             $languageStopWords = trim($languageStopWords);
             $msg = '';
             if (!osc_validate_text($languageName)) {
                 $msg .= _m("Language name field is required") . "<br/>";
             }
             if (!osc_validate_text($languageShortName)) {
                 $msg .= _m("Language short name field is required") . "<br/>";
             }
             if (!osc_validate_text($languageDescription)) {
                 $msg .= _m("Language description field is required") . "<br/>";
             }
             if (!osc_validate_text($languageCurrencyFormat)) {
                 $msg .= _m("Currency format field is required") . "<br/>";
             }
             if (!osc_validate_int($languageNumDec)) {
                 $msg .= _m("Number of decimals must only contain numeric characters") . "<br/>";
             }
             if ($msg != '') {
                 osc_add_flash_error_message($msg, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages&action=edit&id=' . $languageCode);
             }
             $array = array('b_enabled' => $enabledWebstie, 'b_enabled_bo' => $enabledBackoffice, 's_name' => $languageName, 's_short_name' => $languageShortName, 's_description' => $languageDescription, 's_currency_format' => $languageCurrencyFormat, 's_dec_point' => $languageDecPoint, 'i_num_dec' => $languageNumDec, 's_thousands_sep' => $languageThousandsSep, 's_date_format' => $languageDateFormat, 's_stop_words' => $languageStopWords);
             $iUpdated = $this->localeManager->update($array, array('pk_c_code' => $languageCode));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(sprintf(_m('%s has been updated'), $languageShortName), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been enabled for the website');
             $iUpdated = 0;
             $aValues = array('b_enabled' => 1);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 osc_translate_categories($i);
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been disabled for the website');
             $msg_warning = '';
             $iUpdated = 0;
             $aValues = array('b_enabled' => 0);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 if (osc_language() == $i) {
                     $msg_warning = sprintf(_m("%s can't be disabled because it's the default language"), osc_language());
                     continue;
                 }
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($msg_warning != '') {
                 if ($iUpdated > 0) {
                     osc_add_flash_warning_message($msg . '</p><p>' . $msg_warning, 'admin');
                 } else {
                     osc_add_flash_warning_message($msg_warning, 'admin');
                 }
             } else {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_bo_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been enabled for the backoffice (oc-admin)');
             $iUpdated = 0;
             $aValues = array('b_enabled_bo' => 1);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 osc_translate_categories($i);
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_bo_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been disabled for the backoffice (oc-admin)');
             $msg_warning = '';
             $iUpdated = 0;
             $aValues = array('b_enabled_bo' => 0);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 if (osc_language() == $i) {
                     $msg_warning = sprintf(_m("%s can't be disabled because it's the default language"), osc_language());
                     continue;
                 }
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($msg_warning != '') {
                 if ($iUpdated > 0) {
                     osc_add_flash_warning_message($msg . '</p><p>' . $msg_warning, 'admin');
                 } else {
                     osc_add_flash_warning_message($msg_warning, 'admin');
                 }
             } else {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'delete':
             osc_csrf_check();
             if (is_array(Params::getParam('id'))) {
                 $default_lang = osc_language();
                 foreach (Params::getParam('id') as $code) {
                     if ($default_lang != $code) {
                         if ($this->localeManager->deleteLocale($code)) {
                             if (!osc_deleteDir(osc_translations_path() . $code)) {
                                 osc_add_flash_error_message(sprintf(_m("Directory '%s' couldn't be removed"), $code), 'admin');
                             } else {
                                 osc_add_flash_ok_message(sprintf(_m('Directory "%s" has been successfully removed'), $code), 'admin');
                             }
                         } else {
                             osc_add_flash_error_message(sprintf(_m("Directory '%s' couldn't be removed;)"), $code), 'admin');
                         }
                     } else {
                         osc_add_flash_error_message(sprintf(_m("Directory '%s' couldn't be removed because it's the default language. Set another language as default first and try again"), $code), 'admin');
                     }
                 }
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         default:
             if (Params::getParam('checkUpdated') != '') {
                 osc_admin_toolbar_update_languages(true);
             }
             if (Params::getParam("action") != "") {
                 osc_run_hook("language_bulk_" . Params::getParam("action"), Params::getParam('id'));
             }
             // -----
             if (Params::getParam('iDisplayLength') == '') {
                 Params::setParam('iDisplayLength', 10);
             }
             // ?
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             $p_iPage = 1;
             if (is_numeric(Params::getParam('iPage')) && Params::getParam('iPage') >= 1) {
                 $p_iPage = Params::getParam('iPage');
             }
             Params::setParam('iPage', $p_iPage);
             $aLanguages = OSCLocale::newInstance()->listAll();
             // pagination
             $start = ($p_iPage - 1) * Params::getParam('iDisplayLength');
             $limit = Params::getParam('iDisplayLength');
             $count = count($aLanguages);
             $displayRecords = $limit;
             if ($start + $limit > $count) {
                 $displayRecords = $start + $limit - $count;
             }
             // ----
             $aLanguagesToUpdate = json_decode(osc_get_preference('languages_to_update'));
             $bLanguagesToUpdate = is_array($aLanguagesToUpdate) ? true : false;
             // ----
             $aData = array();
             $max = $start + $limit;
             if ($max > $count) {
                 $max = $count;
             }
             for ($i = $start; $i < $max; $i++) {
                 $l = $aLanguages[$i];
                 $row = array();
                 $row[] = '<input type="checkbox" name="id[]" value="' . $l['pk_c_code'] . '" />';
                 $options = array();
                 $options[] = '<a href="' . osc_admin_base_url(true) . '?page=languages&amp;action=edit&amp;id=' . $l['pk_c_code'] . '">' . __('Edit') . '</a>';
                 $options[] = '<a href="' . osc_admin_base_url(true) . '?page=languages&amp;action=' . ($l['b_enabled'] == 1 ? 'disable_selected' : 'enable_selected') . '&amp;id[]=' . $l['pk_c_code'] . '&amp;' . osc_csrf_token_url() . '">' . ($l['b_enabled'] == 1 ? __('Disable (website)') : __('Enable (website)')) . '</a> ';
                 $options[] = '<a href="' . osc_admin_base_url(true) . '?page=languages&amp;action=' . ($l['b_enabled_bo'] == 1 ? 'disable_bo_selected' : 'enable_bo_selected') . '&amp;id[]=' . $l['pk_c_code'] . '&amp;' . osc_csrf_token_url() . '">' . ($l['b_enabled_bo'] == 1 ? __('Disable (oc-admin)') : __('Enable (oc-admin)')) . '</a>';
                 $options[] = '<a onclick="return delete_dialog(\'' . $l['pk_c_code'] . '\');"  href="' . osc_admin_base_url(true) . '?page=languages&amp;action=delete&amp;id[]=' . $l['pk_c_code'] . '&amp;' . osc_csrf_token_url() . '">' . __('Delete') . '</a>';
                 $auxOptions = '<ul>' . PHP_EOL;
                 foreach ($options as $actual) {
                     $auxOptions .= '<li>' . $actual . '</li>' . PHP_EOL;
                 }
                 $actions = '<div class="actions">' . $auxOptions . '</div>' . PHP_EOL;
                 $sUpdate = '';
                 // get languages to update from t_preference
                 if ($bLanguagesToUpdate) {
                     if (in_array($l['pk_c_code'], $aLanguagesToUpdate)) {
                         $sUpdate = '<a class="btn-market-update btn-market-popup" href="#' . htmlentities($l['pk_c_code']) . '">' . __("Update here") . '</a>';
                     }
                 }
                 $row[] = $l['s_name'] . $sUpdate . $actions;
                 $row[] = $l['s_short_name'];
                 $row[] = $l['s_description'];
                 $row[] = $l['b_enabled'] ? __('Yes') : __('No');
                 $row[] = $l['b_enabled_bo'] ? __('Yes') : __('No');
                 $aData[] = $row;
             }
             // ----
             $array['iTotalRecords'] = $displayRecords;
             $array['iTotalDisplayRecords'] = count($aLanguages);
             $array['iDisplayLength'] = $limit;
             $array['aaData'] = $aData;
             $page = (int) Params::getParam('iPage');
             if (count($array['aaData']) == 0 && $page != 1) {
                 $total = (int) $array['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $array['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aLanguages', $array);
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'enable_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Enable (Website)'))), 'label' => __('Enable (Website)')), array('value' => 'disable_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Disable (Website)'))), 'label' => __('Disable (Website)')), array('value' => 'enable_bo_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Enable (oc-admin)'))), 'label' => __('Enable (oc-admin)')), array('value' => 'disable_bo_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Disable (oc-admin)'))), 'label' => __('Disable (oc-admin)')), array('value' => 'delete', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Delete'))), 'label' => __('Delete')));
             $bulk_options = osc_apply_filter("language_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             $this->doView('languages/index.php');
             break;
     }
 }
Пример #28
0
 function doModel()
 {
     //calling the view...
     $locales = OSCLocale::newInstance()->listAllEnabled();
     $this->_exportVariableToView('locales', $locales);
     switch ($this->action) {
         case 'item_add':
             // post
             if (osc_reg_user_post() && $this->user == null) {
                 osc_add_flash_warning_message(_m('Only registered users are allowed to post items'));
                 $this->redirectTo(osc_user_login_url());
             }
             $countries = Country::newInstance()->listAll();
             $regions = array();
             if (isset($this->user['fk_c_country_code']) && $this->user['fk_c_country_code'] != '') {
                 $regions = Region::newInstance()->findByCountry($this->user['fk_c_country_code']);
             } else {
                 if (count($countries) > 0) {
                     $regions = Region::newInstance()->findByCountry($countries[0]['pk_c_code']);
                 }
             }
             $cities = array();
             if (isset($this->user['fk_i_region_id']) && $this->user['fk_i_region_id'] != '') {
                 $cities = City::newInstance()->findByRegion($this->user['fk_i_region_id']);
             } else {
                 if (count($regions) > 0) {
                     $cities = City::newInstance()->findByRegion($regions[0]['pk_i_id']);
                 }
             }
             $this->_exportVariableToView('countries', $countries);
             $this->_exportVariableToView('regions', $regions);
             $this->_exportVariableToView('cities', $cities);
             $form = count(Session::newInstance()->_getForm());
             $keepForm = count(Session::newInstance()->_getKeepForm());
             if ($form == 0 || $form == $keepForm) {
                 Session::newInstance()->_dropKeepForm();
             }
             if (Session::newInstance()->_getForm('countryId') != "") {
                 $countryId = Session::newInstance()->_getForm('countryId');
                 $regions = Region::newInstance()->findByCountry($countryId);
                 $this->_exportVariableToView('regions', $regions);
                 if (Session::newInstance()->_getForm('regionId') != "") {
                     $regionId = Session::newInstance()->_getForm('regionId');
                     $cities = City::newInstance()->findByRegion($regionId);
                     $this->_exportVariableToView('cities', $cities);
                 }
             }
             $this->_exportVariableToView('user', $this->user);
             osc_run_hook('post_item');
             $this->doView('item-post.php');
             break;
         case 'item_add_post':
             //post_item
             if (osc_reg_user_post() && $this->user == null) {
                 osc_add_flash_warning_message(_m('Only registered users are allowed to post items'));
                 $this->redirectTo(osc_base_url(true));
             }
             $mItems = new ItemActions(false);
             // prepare data for ADD ITEM
             $mItems->prepareData(true);
             // set all parameters into session
             foreach ($mItems->data as $key => $value) {
                 Session::newInstance()->_setForm($key, $value);
             }
             $meta = Params::getParam('meta');
             if (is_array($meta)) {
                 foreach ($meta as $key => $value) {
                     Session::newInstance()->_setForm('meta_' . $key, $value);
                     Session::newInstance()->_keepForm('meta_' . $key);
                 }
             }
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     $this->redirectTo(osc_item_post_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             // POST ITEM ( ADD ITEM )
             $success = $mItems->add();
             if ($success != 1 && $success != 2) {
                 osc_add_flash_error_message($success);
                 $this->redirectTo(osc_item_post_url());
             } else {
                 Session::newInstance()->_dropkeepForm('meta_' . $key);
                 if ($success == 1) {
                     osc_add_flash_ok_message(_m('Check your inbox to verify your email address'));
                 } else {
                     osc_add_flash_ok_message(_m('Your item has been published'));
                 }
                 $itemId = Params::getParam('itemId');
                 $item = $this->itemManager->findByPrimaryKey($itemId);
                 osc_run_hook('posted_item', $item);
                 $category = Category::newInstance()->findByPrimaryKey(Params::getParam('catId'));
                 View::newInstance()->_exportVariableToView('category', $category);
                 $this->redirectTo(osc_search_category_url());
             }
             break;
         case 'item_edit':
             // edit item
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s' AND i.fk_i_user_id IS NULL) OR (i.fk_i_user_id = '%d'))", $id, $secret, $this->userId);
             if (count($item) == 1) {
                 $item = Item::newInstance()->findByPrimaryKey($id);
                 $form = count(Session::newInstance()->_getForm());
                 $keepForm = count(Session::newInstance()->_getKeepForm());
                 if ($form == 0 || $form == $keepForm) {
                     Session::newInstance()->_dropKeepForm();
                 }
                 $this->_exportVariableToView('item', $item);
                 osc_run_hook("before_item_edit", $item);
                 $this->doView('item-edit.php');
             } else {
                 // add a flash message [ITEM NO EXISTE]
                 osc_add_flash_error_message(_m('Sorry, we don\'t have any items with that ID'));
                 if ($this->user != null) {
                     $this->redirectTo(osc_user_list_items_url());
                 } else {
                     $this->redirectTo(osc_base_url());
                 }
             }
             break;
         case 'item_edit_post':
             // recoger el secret y el
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s' AND i.fk_i_user_id IS NULL) OR (i.fk_i_user_id = '%d'))", $id, $secret, $this->userId);
             if (count($item) == 1) {
                 $this->_exportVariableToView('item', $item[0]);
                 $mItems = new ItemActions(false);
                 // prepare data for ADD ITEM
                 $mItems->prepareData(false);
                 // set all parameters into session
                 foreach ($mItems->data as $key => $value) {
                     Session::newInstance()->_setForm($key, $value);
                 }
                 $meta = Params::getParam('meta');
                 if (is_array($meta)) {
                     foreach ($meta as $key => $value) {
                         Session::newInstance()->_setForm('meta_' . $key, $value);
                         Session::newInstance()->_keepForm('meta_' . $key);
                     }
                 }
                 if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                     if (!osc_check_recaptcha()) {
                         osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                         $this->redirectTo(osc_item_post_url());
                         return false;
                         // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                     }
                 }
                 $success = $mItems->edit();
                 osc_run_hook('edited_item', Item::newInstance()->findByPrimaryKey($id));
                 if ($success == 1) {
                     osc_add_flash_ok_message(_m('Great! We\'ve just updated your item'));
                     $this->redirectTo(osc_base_url(true) . "?page=item&id={$id}");
                 } else {
                     osc_add_flash_error_message($success);
                     $this->redirectTo(osc_item_edit_url($secret));
                 }
             }
             break;
         case 'activate':
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s') OR (i.fk_i_user_id = '%d'))", $id, $secret, $this->userId);
             View::newInstance()->_exportVariableToView('item', $item[0]);
             if ($item[0]['b_active'] == 0) {
                 // ACTIVETE ITEM
                 $mItems = new ItemActions(false);
                 $success = $mItems->activate($item[0]['pk_i_id'], $item[0]['s_secret']);
                 if ($success) {
                     osc_add_flash_ok_message(_m('The item has been validated'));
                 } else {
                     osc_add_flash_error_message(_m('The item can\'t be validated'));
                 }
             } else {
                 osc_add_flash_error_message(_m('The item has already been validated'));
             }
             $this->redirectTo(osc_item_url());
             break;
         case 'item_delete':
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s') OR (i.fk_i_user_id = '%d'))", $id, $secret, $this->userId);
             if (count($item) == 1) {
                 $mItems = new ItemActions(false);
                 $success = $mItems->delete($item[0]['s_secret'], $item[0]['pk_i_id']);
                 if ($success) {
                     osc_add_flash_ok_message(_m('Your item has been deleted'));
                 } else {
                     osc_add_flash_error_message(_m('The item you are trying to delete couldn\'t be deleted'));
                 }
                 if ($this->user != null) {
                     $this->redirectTo(osc_user_list_items_url());
                 } else {
                     $this->redirectTo(osc_base_url());
                 }
             } else {
                 osc_add_flash_error_message(_m('The item you are trying to delete couldn\'t be deleted'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'mark':
             $mItem = new ItemActions(false);
             $id = Params::getParam('id');
             $as = Params::getParam('as');
             $item = Item::newInstance()->findByPrimaryKey($id);
             View::newInstance()->_exportVariableToView('item', $item);
             $mItem->mark($id, $as);
             osc_add_flash_ok_message(_m('Thanks! That\'s very helpful'));
             $this->redirectTo(osc_item_url());
             break;
         case 'send_friend':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             $this->_exportVariableToView('item', $item);
             $this->doView('item-send-friend.php');
             break;
         case 'send_friend_post':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             $this->_exportVariableToView('item', $item);
             Session::newInstance()->_setForm("yourEmail", Params::getParam('yourEmail'));
             Session::newInstance()->_setForm("yourName", Params::getParam('yourName'));
             Session::newInstance()->_setForm("friendName", Params::getParam('friendName'));
             Session::newInstance()->_setForm("friendEmail", Params::getParam('friendEmail'));
             Session::newInstance()->_setForm("message_body", Params::getParam('message'));
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     $this->redirectTo(osc_item_send_friend_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             $mItem = new ItemActions(false);
             $success = $mItem->send_friend();
             if ($success) {
                 Session::newInstance()->_clearVariables();
                 $this->redirectTo(osc_item_url());
             } else {
                 $this->redirectTo(osc_item_send_friend_url());
             }
             break;
         case 'contact':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             if (empty($item)) {
                 osc_add_flash_error_message(_m('This item doesn\'t exist'));
                 $this->redirectTo(osc_base_url(true));
             } else {
                 $this->_exportVariableToView('item', $item);
                 if (osc_item_is_expired()) {
                     osc_add_flash_error_message(_m('We\'re sorry, but the item has expired. You can\'t contact the seller'));
                     $this->redirectTo(osc_item_url());
                 }
                 if (osc_reg_user_can_contact() && osc_is_web_user_logged_in() || !osc_reg_user_can_contact()) {
                     $this->doView('item-contact.php');
                 } else {
                     osc_add_flash_error_message(_m('You can\'t contact the seller, only registered users can'));
                     $this->redirectTo(osc_item_url());
                 }
             }
             break;
         case 'contact_post':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             $this->_exportVariableToView('item', $item);
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     Session::newInstance()->_setForm("yourEmail", Params::getParam('yourEmail'));
                     Session::newInstance()->_setForm("yourName", Params::getParam('yourName'));
                     Session::newInstance()->_setForm("phoneNumber", Params::getParam('phoneNumber'));
                     Session::newInstance()->_setForm("message_body", Params::getParam('message'));
                     $this->redirectTo(osc_item_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             $category = Category::newInstance()->findByPrimaryKey($item['fk_i_category_id']);
             if ($category['i_expiration_days'] > 0) {
                 $item_date = strtotime($item['dt_pub_date']) + $category['i_expiration_days'] * (24 * 3600);
                 $date = time();
                 if ($item_date < $date && $item['b_premium'] != 1) {
                     // The item is expired, we can not contact the seller
                     osc_add_flash_error_message(_m('We\'re sorry, but the item has expired. You can\'t contact the seller'));
                     $this->redirectTo(osc_item_url());
                 }
             }
             $mItem = new ItemActions(false);
             $result = $mItem->contact();
             if (is_string($result)) {
                 osc_add_flash_error_message($result);
             } else {
                 osc_add_flash_ok_message(_m('We\'ve just sent an e-mail to the seller'));
             }
             $this->redirectTo(osc_item_url());
             break;
         case 'add_comment':
             $mItem = new ItemActions(false);
             $status = $mItem->add_comment();
             switch ($status) {
                 case -1:
                     $msg = _m('Sorry, we could not save your comment. Try again later');
                     osc_add_flash_error_message($msg);
                     break;
                 case 1:
                     $msg = _m('Your comment is awaiting moderation');
                     osc_add_flash_info_message($msg);
                     break;
                 case 2:
                     $msg = _m('Your comment has been approved');
                     osc_add_flash_ok_message($msg);
                     break;
                 case 3:
                     $msg = _m('Please fill the required fields (name, email)');
                     osc_add_flash_warning_message($msg);
                     break;
                 case 4:
                     $msg = _m('Please type a comment');
                     osc_add_flash_warning_message($msg);
                     break;
                 case 5:
                     $msg = _m('Your comment has been marked as spam');
                     osc_add_flash_error_message($msg);
                     break;
             }
             $this->redirectTo(osc_item_url());
             break;
         case 'delete_comment':
             $mItem = new ItemActions(false);
             $status = $mItem->add_comment();
             $itemId = Params::getParam('id');
             $commentId = Params::getParam('comment');
             $item = Item::newInstance()->findByPrimaryKey($itemId);
             if (count($item) == 0) {
                 osc_add_flash_error_message(_m('This item doesn\'t exist'));
                 $this->redirectTo(osc_base_url(true));
             }
             View::newInstance()->_exportVariableToView('item', $item);
             if ($this->userId == null) {
                 osc_add_flash_error_message(_m('You must be logged in to delete a comment'));
                 $this->redirectTo(osc_item_url());
             }
             $commentManager = ItemComment::newInstance();
             $aComment = $commentManager->findByPrimaryKey($commentId);
             if (count($aComment) == 0) {
                 osc_add_flash_error_message(_m('The comment doesn\'t exist'));
                 $this->redirectTo(osc_item_url());
             }
             if ($aComment['b_active'] != 1) {
                 osc_add_flash_error_message(_m('The comment is not active, you cannot delete it'));
                 $this->redirectTo(osc_item_url());
             }
             if ($aComment['fk_i_user_id'] != $this->userId) {
                 osc_add_flash_error_message(_m('The comment was not added by you, you cannot delete it'));
                 $this->redirectTo(osc_item_url());
             }
             $commentManager->deleteByPrimaryKey($commentId);
             osc_add_flash_ok_message(_m('The comment has been deleted'));
             $this->redirectTo(osc_item_url());
             break;
         default:
             if (Params::getParam('id') == '') {
                 $this->redirectTo(osc_base_url());
             }
             if (Params::getParam('lang') != '') {
                 Session::newInstance()->_set('userLocale', Params::getParam('lang'));
             }
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             // if item doesn't exist redirect to base url
             if (count($item) == 0) {
                 osc_add_flash_error_message(_m('This item doesn\'t exist'));
                 $this->redirectTo(osc_base_url(true));
             } else {
                 if ($item['b_active'] != 1) {
                     if ($this->userId == $item['fk_i_user_id']) {
                         osc_add_flash_error_message(_m('The item hasn\'t been validated. Please validate it in order to show it to the rest of users'));
                     } else {
                         osc_add_flash_error_message(_m('This item hasn\'t been validated'));
                         $this->redirectTo(osc_base_url(true));
                     }
                 } else {
                     if ($item['b_enabled'] == 0) {
                         osc_add_flash_error_message(_m('The item has been suspended'));
                         $this->redirectTo(osc_base_url(true));
                     }
                 }
                 $mStats = new ItemStats();
                 $mStats->increase('i_num_views', $item['pk_i_id']);
                 foreach ($item['locale'] as $k => $v) {
                     $item['locale'][$k]['s_title'] = osc_apply_filter('item_title', $v['s_title']);
                     $item['locale'][$k]['s_description'] = nl2br(osc_apply_filter('item_description', $v['s_description']));
                 }
                 $this->_exportVariableToView('items', array($item));
                 osc_run_hook('show_item', $item);
                 $this->doView('item.php');
             }
             break;
         case 'dashboard':
             //dashboard...
             break;
     }
 }
Пример #29
0
 function doModel()
 {
     //calling the view...
     $locales = OSCLocale::newInstance()->listAllEnabled();
     $this->_exportVariableToView('locales', $locales);
     switch ($this->action) {
         case 'item_add':
             // post
             if (osc_reg_user_post() && $this->user == null) {
                 osc_add_flash_warning_message(_m('Only registered users are allowed to post listings'));
                 $this->redirectTo(osc_user_login_url());
             }
             $countries = Country::newInstance()->listAll();
             $regions = array();
             if (isset($this->user['fk_c_country_code']) && $this->user['fk_c_country_code'] != '') {
                 $regions = Region::newInstance()->findByCountry($this->user['fk_c_country_code']);
             } else {
                 if (count($countries) > 0) {
                     $regions = Region::newInstance()->findByCountry($countries[0]['pk_c_code']);
                 }
             }
             $cities = array();
             if (isset($this->user['fk_i_region_id']) && $this->user['fk_i_region_id'] != '') {
                 $cities = City::newInstance()->findByRegion($this->user['fk_i_region_id']);
             } else {
                 if (count($regions) > 0) {
                     $cities = City::newInstance()->findByRegion($regions[0]['pk_i_id']);
                 }
             }
             $this->_exportVariableToView('countries', $countries);
             $this->_exportVariableToView('regions', $regions);
             $this->_exportVariableToView('cities', $cities);
             $form = count(Session::newInstance()->_getForm());
             $keepForm = count(Session::newInstance()->_getKeepForm());
             if ($form == 0 || $form == $keepForm) {
                 Session::newInstance()->_dropKeepForm();
             }
             if (Session::newInstance()->_getForm('countryId') != "") {
                 $countryId = Session::newInstance()->_getForm('countryId');
                 $regions = Region::newInstance()->findByCountry($countryId);
                 $this->_exportVariableToView('regions', $regions);
                 if (Session::newInstance()->_getForm('regionId') != "") {
                     $regionId = Session::newInstance()->_getForm('regionId');
                     $cities = City::newInstance()->findByRegion($regionId);
                     $this->_exportVariableToView('cities', $cities);
                 }
             }
             $this->_exportVariableToView('user', $this->user);
             osc_run_hook('post_item');
             $this->doView('item-post.php');
             break;
         case 'item_add_post':
             //post_item
             if (osc_reg_user_post() && $this->user == null) {
                 osc_add_flash_warning_message(_m('Only registered users are allowed to post listings'));
                 $this->redirectTo(osc_base_url(true));
             }
             $mItems = new ItemActions(false);
             // prepare data for ADD ITEM
             $mItems->prepareData(true);
             // set all parameters into session
             foreach ($mItems->data as $key => $value) {
                 Session::newInstance()->_setForm($key, $value);
             }
             $meta = Params::getParam('meta');
             if (is_array($meta)) {
                 foreach ($meta as $key => $value) {
                     Session::newInstance()->_setForm('meta_' . $key, $value);
                     Session::newInstance()->_keepForm('meta_' . $key);
                 }
             }
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     $this->redirectTo(osc_item_post_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             if (!osc_is_web_user_logged_in()) {
                 $user = User::newInstance()->findByEmail($mItems->data['contactEmail']);
                 // The user exists but it's not logged
                 if (isset($user['pk_i_id'])) {
                     foreach ($mItems->data as $key => $value) {
                         Session::newInstance()->_keepForm($key);
                     }
                     osc_add_flash_error_message(_m('A user with that email address already exists, if it is you, please log in'));
                     $this->redirectTo(osc_user_login_url());
                 }
             }
             // POST ITEM ( ADD ITEM )
             $success = $mItems->add();
             if ($success != 1 && $success != 2) {
                 osc_add_flash_error_message($success);
                 $this->redirectTo(osc_item_post_url());
             } else {
                 Session::newInstance()->_dropkeepForm('meta_' . $key);
                 if ($success == 1) {
                     osc_add_flash_ok_message(_m('Check your inbox to validate your listing'));
                 } else {
                     osc_add_flash_ok_message(_m('Your listing has been published'));
                 }
                 $itemId = Params::getParam('itemId');
                 $item = $this->itemManager->findByPrimaryKey($itemId);
                 osc_run_hook('posted_item', $item);
                 $category = Category::newInstance()->findByPrimaryKey(Params::getParam('catId'));
                 View::newInstance()->_exportVariableToView('category', $category);
                 $this->redirectTo(osc_search_category_url());
             }
             break;
         case 'item_edit':
             // edit item
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s' AND i.fk_i_user_id IS NULL) OR (i.fk_i_user_id = '%d'))", addslashes($id), addslashes($secret), addslashes($this->userId));
             if (count($item) == 1) {
                 $item = Item::newInstance()->findByPrimaryKey($id);
                 $form = count(Session::newInstance()->_getForm());
                 $keepForm = count(Session::newInstance()->_getKeepForm());
                 if ($form == 0 || $form == $keepForm) {
                     Session::newInstance()->_dropKeepForm();
                 }
                 $this->_exportVariableToView('item', $item);
                 osc_run_hook("before_item_edit", $item);
                 $this->doView('item-edit.php');
             } else {
                 // add a flash message [ITEM NO EXISTE]
                 osc_add_flash_error_message(_m("Sorry, we don't have any listings with that ID"));
                 if ($this->user != null) {
                     $this->redirectTo(osc_user_list_items_url());
                 } else {
                     $this->redirectTo(osc_base_url());
                 }
             }
             break;
         case 'item_edit_post':
             // recoger el secret y el
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s' AND i.fk_i_user_id IS NULL) OR (i.fk_i_user_id = '%d'))", addslashes($id), addslashes($secret), addslashes($this->userId));
             if (count($item) == 1) {
                 $this->_exportVariableToView('item', $item[0]);
                 $mItems = new ItemActions(false);
                 // prepare data for ADD ITEM
                 $mItems->prepareData(false);
                 // set all parameters into session
                 foreach ($mItems->data as $key => $value) {
                     Session::newInstance()->_setForm($key, $value);
                 }
                 $meta = Params::getParam('meta');
                 if (is_array($meta)) {
                     foreach ($meta as $key => $value) {
                         Session::newInstance()->_setForm('meta_' . $key, $value);
                         Session::newInstance()->_keepForm('meta_' . $key);
                     }
                 }
                 if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                     if (!osc_check_recaptcha()) {
                         osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                         $this->redirectTo(osc_item_edit_url());
                         return false;
                         // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                     }
                 }
                 $success = $mItems->edit();
                 osc_run_hook('edited_item', Item::newInstance()->findByPrimaryKey($id));
                 if ($success == 1) {
                     osc_add_flash_ok_message(_m("Great! We've just updated your listing"));
                     View::newInstance()->_exportVariableToView("item", Item::newInstance()->findByPrimaryKey($id));
                     $this->redirectTo(osc_item_url());
                 } else {
                     osc_add_flash_error_message($success);
                     $this->redirectTo(osc_item_edit_url($secret));
                 }
             }
             break;
         case 'activate':
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s') OR (i.fk_i_user_id = '%d'))", addslashes($id), addslashes($secret), addslashes($this->userId));
             // item doesn't exist
             if (count($item) == 0) {
                 $this->do404();
                 return;
             }
             View::newInstance()->_exportVariableToView('item', $item[0]);
             if ($item[0]['b_active'] == 0) {
                 // ACTIVETE ITEM
                 $mItems = new ItemActions(false);
                 $success = $mItems->activate($item[0]['pk_i_id'], $item[0]['s_secret']);
                 if ($success) {
                     osc_add_flash_ok_message(_m('The listing has been validated'));
                 } else {
                     osc_add_flash_error_message(_m("The listing can't be validated"));
                 }
             } else {
                 osc_add_flash_warning_message(_m('The listing has already been validated'));
             }
             $this->redirectTo(osc_item_url());
             break;
         case 'item_delete':
             $secret = Params::getParam('secret');
             $id = Params::getParam('id');
             $item = $this->itemManager->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s') OR (i.fk_i_user_id = '%d'))", addslashes($id), addslashes($secret), addslashes($this->userId));
             if (count($item) == 1) {
                 $mItems = new ItemActions(false);
                 $success = $mItems->delete($item[0]['s_secret'], $item[0]['pk_i_id']);
                 if ($success) {
                     osc_add_flash_ok_message(_m('Your listing has been deleted'));
                 } else {
                     osc_add_flash_error_message(_m("The listing you are trying to delete couldn't be deleted"));
                 }
                 if ($this->user != null) {
                     $this->redirectTo(osc_user_list_items_url());
                 } else {
                     $this->redirectTo(osc_base_url());
                 }
             } else {
                 osc_add_flash_error_message(_m("The listing you are trying to delete couldn't be deleted"));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'mark':
             $id = Params::getParam('id');
             $as = Params::getParam('as');
             $item = Item::newInstance()->findByPrimaryKey($id);
             View::newInstance()->_exportVariableToView('item', $item);
             require_once osc_lib_path() . 'osclass/user-agents.php';
             foreach ($user_agents as $ua) {
                 if (preg_match('|' . $ua . '|', @$_SERVER['HTTP_USER_AGENT'])) {
                     // mark item if it's not a bot
                     $mItem = new ItemActions(false);
                     $mItem->mark($id, $as);
                     break;
                 }
             }
             osc_add_flash_ok_message(_m("Thanks! That's very helpful"));
             $this->redirectTo(osc_item_url());
             break;
         case 'send_friend':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             $this->_exportVariableToView('item', $item);
             $this->doView('item-send-friend.php');
             break;
         case 'send_friend_post':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             $this->_exportVariableToView('item', $item);
             Session::newInstance()->_setForm("yourEmail", Params::getParam('yourEmail'));
             Session::newInstance()->_setForm("yourName", Params::getParam('yourName'));
             Session::newInstance()->_setForm("friendName", Params::getParam('friendName'));
             Session::newInstance()->_setForm("friendEmail", Params::getParam('friendEmail'));
             Session::newInstance()->_setForm("message_body", Params::getParam('message'));
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     $this->redirectTo(osc_item_send_friend_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             $mItem = new ItemActions(false);
             $success = $mItem->send_friend();
             if ($success) {
                 Session::newInstance()->_clearVariables();
                 $this->redirectTo(osc_item_url());
             } else {
                 $this->redirectTo(osc_item_send_friend_url());
             }
             break;
         case 'contact':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             if (empty($item)) {
                 osc_add_flash_error_message(_m("This listing doesn't exist"));
                 $this->redirectTo(osc_base_url(true));
             } else {
                 $this->_exportVariableToView('item', $item);
                 if (osc_item_is_expired()) {
                     osc_add_flash_error_message(_m("We're sorry, but the listing has expired. You can't contact the seller"));
                     $this->redirectTo(osc_item_url());
                 }
                 if (osc_reg_user_can_contact() && osc_is_web_user_logged_in() || !osc_reg_user_can_contact()) {
                     $this->doView('item-contact.php');
                 } else {
                     osc_add_flash_error_message(_m("You can't contact the seller, only registered users can"));
                     $this->redirectTo(osc_item_url());
                 }
             }
             break;
         case 'contact_post':
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             $this->_exportVariableToView('item', $item);
             if (osc_recaptcha_private_key() != '' && Params::existParam("recaptcha_challenge_field")) {
                 if (!osc_check_recaptcha()) {
                     osc_add_flash_error_message(_m('The Recaptcha code is wrong'));
                     Session::newInstance()->_setForm("yourEmail", Params::getParam('yourEmail'));
                     Session::newInstance()->_setForm("yourName", Params::getParam('yourName'));
                     Session::newInstance()->_setForm("phoneNumber", Params::getParam('phoneNumber'));
                     Session::newInstance()->_setForm("message_body", Params::getParam('message'));
                     $this->redirectTo(osc_item_url());
                     return false;
                     // BREAK THE PROCESS, THE RECAPTCHA IS WRONG
                 }
             }
             if (osc_isExpired($item['dt_expiration'])) {
                 osc_add_flash_error_message(_m("We're sorry, but the listing has expired. You can't contact the seller"));
                 $this->redirectTo(osc_item_url());
             }
             $mItem = new ItemActions(false);
             $result = $mItem->contact();
             if (is_string($result)) {
                 osc_add_flash_error_message($result);
             } else {
                 osc_add_flash_ok_message(_m("We've just sent an e-mail to the seller"));
             }
             $this->redirectTo(osc_item_url());
             break;
         case 'add_comment':
             $mItem = new ItemActions(false);
             $status = $mItem->add_comment();
             switch ($status) {
                 case -1:
                     $msg = _m('Sorry, we could not save your comment. Try again later');
                     osc_add_flash_error_message($msg);
                     break;
                 case 1:
                     $msg = _m('Your comment is awaiting moderation');
                     osc_add_flash_info_message($msg);
                     break;
                 case 2:
                     $msg = _m('Your comment has been approved');
                     osc_add_flash_ok_message($msg);
                     break;
                 case 3:
                     $msg = _m('Please fill the required field (email)');
                     osc_add_flash_warning_message($msg);
                     break;
                 case 4:
                     $msg = _m('Please type a comment');
                     osc_add_flash_warning_message($msg);
                     break;
                 case 5:
                     $msg = _m('Your comment has been marked as spam');
                     osc_add_flash_error_message($msg);
                     break;
             }
             $this->redirectTo(osc_item_url());
             break;
         case 'delete_comment':
             $mItem = new ItemActions(false);
             $status = $mItem->add_comment();
             $itemId = Params::getParam('id');
             $commentId = Params::getParam('comment');
             $item = Item::newInstance()->findByPrimaryKey($itemId);
             if (count($item) == 0) {
                 osc_add_flash_error_message(_m("This listing doesn't exist"));
                 $this->redirectTo(osc_base_url(true));
             }
             View::newInstance()->_exportVariableToView('item', $item);
             if ($this->userId == null) {
                 osc_add_flash_error_message(_m('You must be logged in to delete a comment'));
                 $this->redirectTo(osc_item_url());
             }
             $commentManager = ItemComment::newInstance();
             $aComment = $commentManager->findByPrimaryKey($commentId);
             if (count($aComment) == 0) {
                 osc_add_flash_error_message(_m("The comment doesn't exist"));
                 $this->redirectTo(osc_item_url());
             }
             if ($aComment['b_active'] != 1) {
                 osc_add_flash_error_message(_m('The comment is not active, you cannot delete it'));
                 $this->redirectTo(osc_item_url());
             }
             if ($aComment['fk_i_user_id'] != $this->userId) {
                 osc_add_flash_error_message(_m('The comment was not added by you, you cannot delete it'));
                 $this->redirectTo(osc_item_url());
             }
             $commentManager->deleteByPrimaryKey($commentId);
             osc_add_flash_ok_message(_m('The comment has been deleted'));
             $this->redirectTo(osc_item_url());
             break;
         default:
             // if there isn't ID, show an error 404
             if (Params::getParam('id') == '') {
                 $this->do404();
                 return;
             }
             if (Params::getParam('lang') != '') {
                 Session::newInstance()->_set('userLocale', Params::getParam('lang'));
             }
             $item = $this->itemManager->findByPrimaryKey(Params::getParam('id'));
             // if item doesn't exist show an error 404
             if (count($item) == 0) {
                 $this->do404();
                 return;
             }
             if ($item['b_active'] != 1) {
                 if ($this->userId == $item['fk_i_user_id']) {
                     osc_add_flash_warning_message(_m("The listing hasn't been validated. Please validate it in order to make it public"));
                 } else {
                     osc_add_flash_warning_message(_m("This listing hasn't been validated"));
                     $this->redirectTo(osc_base_url(true));
                 }
             } else {
                 if ($item['b_enabled'] == 0) {
                     osc_add_flash_warning_message(_m('The listing has been suspended'));
                     $this->redirectTo(osc_base_url(true));
                 }
             }
             if (!osc_is_admin_user_logged_in()) {
                 require_once osc_lib_path() . 'osclass/user-agents.php';
                 foreach ($user_agents as $ua) {
                     if (preg_match('|' . $ua . '|', @$_SERVER['HTTP_USER_AGENT'])) {
                         $mStats = new ItemStats();
                         $mStats->increase('i_num_views', $item['pk_i_id']);
                         break;
                     }
                 }
             }
             foreach ($item['locale'] as $k => $v) {
                 $item['locale'][$k]['s_title'] = osc_apply_filter('item_title', $v['s_title']);
                 $item['locale'][$k]['s_description'] = nl2br(osc_apply_filter('item_description', $v['s_description']));
             }
             if ($item['fk_i_user_id'] != '') {
                 $user = User::newInstance()->findByPrimaryKey($item['fk_i_user_id']);
                 $this->_exportVariableToView('user', $user);
             }
             $this->_exportVariableToView('item', $item);
             osc_run_hook('show_item', $item);
             // redirect to the correct url just in case it has changed
             $itemURI = str_replace(osc_base_url(), '', osc_item_url());
             $URI = preg_replace('|^' . REL_WEB_URL . '|', '', $_SERVER['REQUEST_URI']);
             // do not clean QUERY_STRING if permalink is not enabled
             if (osc_rewrite_enabled()) {
                 $URI = str_replace('?' . $_SERVER['QUERY_STRING'], '', $URI);
             } else {
                 $params_keep = array('page', 'id');
                 $params = array();
                 foreach (Params::getParamsAsArray('get') as $k => $v) {
                     if (in_array($k, $params_keep)) {
                         $params[] = "{$k}={$v}";
                     }
                 }
                 $URI = 'index.php?' . implode('&', $params);
             }
             // redirect to the correct url
             if ($itemURI != $URI) {
                 $this->redirectTo(osc_base_url() . $itemURI);
             }
             $this->doView('item.php');
             break;
     }
 }
Пример #30
0
 function doModel()
 {
     switch (Params::getParam('type')) {
         case 'add':
             // calling add currency view
             $aCurrency = array('pk_c_code' => '', 's_name' => '', 's_description' => '');
             $this->_exportVariableToView('aCurrency', $aCurrency);
             $this->_exportVariableToView('typeForm', 'add_post');
             $this->doView('settings/currency_form.php');
             break;
         case 'add_post':
             // adding a new currency
             osc_csrf_check();
             $currencyCode = Params::getParam('pk_c_code');
             $currencyName = Params::getParam('s_name');
             $currencyDescription = Params::getParam('s_description');
             // cleaning parameters
             $currencyName = trim(strip_tags($currencyName));
             $currencyDescription = trim(strip_tags($currencyDescription));
             $currencyCode = trim(strip_tags($currencyCode));
             if (!preg_match('/^.{1,3}$/', $currencyCode)) {
                 osc_add_flash_error_message(_m('The currency code is not in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             }
             $fields = array('pk_c_code' => $currencyCode, 's_name' => $currencyName, 's_description' => $currencyDescription);
             $isInserted = Currency::newInstance()->insert($fields);
             if ($isInserted) {
                 osc_add_flash_ok_message(_m('Currency added'), 'admin');
             } else {
                 osc_add_flash_error_message(_m("Currency couldn't be added"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             break;
         case 'edit':
             // calling edit currency view
             $currencyCode = Params::getParam('code');
             $currencyCode = trim(strip_tags($currencyCode));
             if ($currencyCode == '') {
                 osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             }
             $aCurrency = Currency::newInstance()->findByPrimaryKey($currencyCode);
             if (!$aCurrency) {
                 osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             }
             $this->_exportVariableToView('aCurrency', $aCurrency);
             $this->_exportVariableToView('typeForm', 'edit_post');
             $this->doView('settings/currency_form.php');
             break;
         case 'edit_post':
             // updating currency
             osc_csrf_check();
             $currencyName = Params::getParam('s_name');
             $currencyDescription = Params::getParam('s_description');
             $currencyCode = Params::getParam('pk_c_code');
             // cleaning parameters
             $currencyName = trim(strip_tags($currencyName));
             $currencyDescription = trim(strip_tags($currencyDescription));
             $currencyCode = trim(strip_tags($currencyCode));
             if (!preg_match('/.{1,3}/', $currencyCode)) {
                 osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             }
             $updated = Currency::newInstance()->update(array('s_name' => $currencyName, 's_description' => $currencyDescription), array('pk_c_code' => $currencyCode));
             if ($updated == 1) {
                 osc_add_flash_ok_message(_m('Currency updated'), 'admin');
             } else {
                 osc_add_flash_info_message(_m('No changes were made'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             break;
         case 'delete':
             // deleting a currency
             osc_csrf_check();
             $rowChanged = 0;
             $aCurrencyCode = Params::getParam('code');
             if (!is_array($aCurrencyCode)) {
                 $aCurrencyCode = array($aCurrencyCode);
             }
             $msg_current = '';
             foreach ($aCurrencyCode as $currencyCode) {
                 if (preg_match('/.{1,3}/', $currencyCode) && $currencyCode != osc_currency()) {
                     $rowChanged += Currency::newInstance()->delete(array('pk_c_code' => $currencyCode));
                 }
                 // foreign key error
                 if (Currency::newInstance()->getErrorLevel() == '1451') {
                     $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it has listings associated to it"), $currencyCode);
                 } else {
                     if ($currencyCode == osc_currency()) {
                         $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it's the default currency"), $currencyCode);
                     }
                 }
             }
             $msg = '';
             $status = '';
             switch ($rowChanged) {
                 case '0':
                     $msg = _m('No currencies have been deleted');
                     $status = 'error';
                     break;
                 case '1':
                     $msg = _m('One currency has been deleted');
                     $status = 'ok';
                     break;
                 default:
                     $msg = sprintf(_m('%s currencies have been deleted'), $rowChanged);
                     $status = 'ok';
                     break;
             }
             if ($status == 'ok' && $msg_current != '') {
                 $status = 'warning';
             }
             switch ($status) {
                 case 'error':
                     osc_add_flash_error_message($msg . $msg_current, 'admin');
                     break;
                 case 'warning':
                     osc_add_flash_warning_message($msg . $msg_current, 'admin');
                     break;
                 case 'ok':
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
             break;
         default:
             // calling the currencies view
             $aCurrencies = Currency::newInstance()->listAll();
             $this->_exportVariableToView('aCurrencies', $aCurrencies);
             $this->doView('settings/currencies.php');
             break;
     }
 }