Esempio n. 1
0
 function __construct()
 {
     parent::__construct();
     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');
             }
         }
     }
 }
Esempio n. 2
0
function basic_info()
{
    require_once ABS_PATH . 'oc-includes/osclass/model/Admin.php';
    require_once ABS_PATH . 'oc-includes/osclass/model/Preference.php';
    Admin::newInstance()->insert(array('s_name' => 'Administrator', 's_username' => 'admin', 's_password' => sha1('admin'), 's_email' => $_POST['email']));
    $mPreference = Preference::newInstance();
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'pageTitle', 's_value' => $_POST['webtitle'], 'e_type' => 'STRING'));
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'contactEmail', 's_value' => $_POST['email'], 'e_type' => 'STRING'));
}
Esempio n. 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');
     }
 }
Esempio n. 4
0
function customHead()
{
    $all = Preference::newInstance()->findValueByName('location_todo');
    if ($all == '') {
        $all = 0;
    }
    $worktodo = LocationsTmp::newInstance()->count();
    ?>
        <script type="text/javascript">
            function reload() {
                window.location = '<?php 
    echo osc_admin_base_url(true) . '?page=tools&action=locations';
    ?>
';
            }

            function ajax_() {
                $.ajax({
                    type: "POST",
                    url: '<?php 
    echo osc_admin_base_url(true);
    ?>
?page=ajax&action=location_stats&<?php 
    echo osc_csrf_token_url();
    ?>
',
                    dataType: 'json',
                    success: function(data) {
                        if(data.status=='done') {
                        }else{
                            var pending = data.pending;
                            var all = <?php 
    echo osc_esc_js($all);
    ?>
;
                            var percent = parseInt( ((all-pending)*100) / all );
                            $('span#percent').html(percent);
                            ajax_();
                        }
                    }
                });
            }

            $(document).ready(function(){
                if(<?php 
    echo $worktodo;
    ?>
> 0) {
                    ajax_();
                }
            });
        </script>
        <?php 
}
Esempio n. 5
0
function google_analytics_actions()
{
    $dao_preference = new Preference();
    $option = Params::getParam('option');
    if (Params::getParam('file') != 'google_analytics/admin.php') {
        return '';
    }
    if ($option == 'stepone') {
        $webid = Params::getParam('webid');
        Preference::newInstance()->update(array("s_value" => $webid), array("s_section" => "plugin-google_analytics", "s_name" => "google_analytics_id"));
        osc_add_flash_ok_message(__('The tracking ID has been updated', 'google_analytics'), 'admin');
        osc_redirect_to(osc_admin_render_plugin_url('google_analytics/admin.php'));
    }
}
Esempio n. 6
0
function basic_info()
{
    require_once LIB_PATH . 'osclass/model/Admin.php';
    require_once LIB_PATH . 'osclass/model/Preference.php';
    require_once LIB_PATH . 'osclass/helpers/hSecurity.php';
    if ($_POST['s_name'] == '') {
        $admin = 'admin';
    } else {
        $admin = $_POST['s_name'];
    }
    if ($_POST['s_passwd'] == '') {
        $password = osc_genRandomPassword();
    } else {
        $password = $_POST['s_passwd'];
    }
    Admin::newInstance()->insert(array('s_name' => 'Administrator', 's_username' => $admin, 's_password' => sha1($password), 's_email' => $_POST['email']));
    $mPreference = Preference::newInstance();
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'pageTitle', 's_value' => $_POST['webtitle'], 'e_type' => 'STRING'));
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'contactEmail', 's_value' => $_POST['email'], 'e_type' => 'STRING'));
    $body = 'Welcome ' . $_POST['webtitle'] . ',<br/><br/>';
    $body .= 'Your OSClass installation at ' . WEB_PATH . ' is up and running. You can access to the administration panel with this data access:<br/>';
    $body .= '<ul>';
    $body .= '<li>username: '******'</li>';
    $body .= '<li>password: '******'</li>';
    $body .= '</ul>';
    $body .= 'Regards,<br/>';
    $body .= 'The <a href=\'http://osclass.org/\'>OSClass</a> team';
    $sitename = strtolower($_SERVER['SERVER_NAME']);
    if (substr($sitename, 0, 4) == 'www.') {
        $sitename = substr($sitename, 4);
    }
    try {
        require_once LIB_PATH . 'phpmailer/class.phpmailer.php';
        $mail = new PHPMailer(true);
        $mail->CharSet = "utf-8";
        $mail->Host = "localhost";
        $mail->From = 'osclass@' . $sitename;
        $mail->FromName = 'OSClass';
        $mail->Subject = 'OSClass successfully installed!';
        $mail->AddAddress($_POST['email'], 'OSClass administrator');
        $mail->Body = $body;
        $mail->AltBody = $body;
        if (!$mail->Send()) {
            return array('email_status' => $_POST['email'] . "<br>" . $mail->ErrorInfo, 's_password' => $password);
        } else {
            return array('email_status' => '', 's_password' => $password);
        }
    } catch (phpmailerException $exception) {
    }
}
Esempio n. 7
0
function basic_info()
{
    require_once LIB_PATH . 'osclass/model/Admin.php';
    require_once LIB_PATH . 'osclass/helpers/hSecurity.php';
    $admin = Params::getParam('s_name');
    if ($admin == '') {
        $admin = 'admin';
    }
    $password = Params::getParam('s_passwd', false, false);
    if ($password == '') {
        $password = osc_genRandomPassword();
    }
    Admin::newInstance()->insert(array('s_name' => 'Administrator', 's_username' => $admin, 's_password' => osc_hash_password($password), 's_email' => Params::getParam('email')));
    $mPreference = Preference::newInstance();
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'pageTitle', 's_value' => Params::getParam('webtitle'), 'e_type' => 'STRING'));
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'contactEmail', 's_value' => Params::getParam('email'), 'e_type' => 'STRING'));
    $body = sprintf(__('Hi %s,'), Params::getParam('webtitle')) . "<br/><br/>";
    $body .= sprintf(__('Your Osclass installation at %s is up and running. You can access the administration panel with these details:'), WEB_PATH) . '<br/>';
    $body .= '<ul>';
    $body .= '<li>' . sprintf(__('username: %s'), $admin) . '</li>';
    $body .= '<li>' . sprintf(__('password: %s'), $password) . '</li>';
    $body .= '</ul>';
    $body .= sprintf(__('Remember that for any doubts you might have you can consult our <a href="%1$s">documentation</a>, <a href="%2$s">forum</a> or <a href="%3$s">blog</a>.'), 'http://doc.osclass.org/', 'http://forums.osclass.org/', 'http://blog.osclass.org/');
    $body .= sprintf(' ' . __('Osclass doesn’t run any developments but we can put you in touch with third party developers through a Premium Support. And hey, if you would like to contribute to Osclass - learn how <a href="%1$s">here</a>!'), 'http://blog.osclass.org/2012/11/22/how-to-collaborate-to-osclass/') . '<br/><br/>';
    $body .= __('Cheers,') . "<br/>";
    $body .= __('The <a href="http://osclass.org/">Osclass</a> team');
    $sitename = strtolower($_SERVER['SERVER_NAME']);
    if (substr($sitename, 0, 4) == 'www.') {
        $sitename = substr($sitename, 4);
    }
    try {
        require_once LIB_PATH . 'phpmailer/class.phpmailer.php';
        $mail = new PHPMailer(true);
        $mail->CharSet = "utf-8";
        $mail->Host = "localhost";
        $mail->From = 'osclass@' . $sitename;
        $mail->FromName = 'Osclass';
        $mail->Subject = 'Osclass successfully installed!';
        $mail->AddAddress(Params::getParam('email'), 'Osclass administrator');
        $mail->Body = $body;
        $mail->AltBody = $body;
        if (!$mail->Send()) {
            return array('email_status' => Params::getParam('email') . "<br>" . $mail->ErrorInfo, 's_password' => $password);
        }
        return array('email_status' => '', 's_password' => $password);
    } catch (phpmailerException $exception) {
        return array('email_status' => Params::getParam('email') . "<br>" . $exception->errorMessage(), 's_password' => $password);
    }
}
Esempio n. 8
0
function basic_info()
{
    require_once LIB_PATH . 'osclass/model/Admin.php';
    require_once LIB_PATH . 'osclass/helpers/hSecurity.php';
    $admin = Params::getParam('s_name');
    if ($admin == '') {
        $admin = 'admin';
    }
    $password = Params::getParam('s_passwd', false, false);
    if ($password == '') {
        $password = osc_genRandomPassword();
    }
    Admin::newInstance()->insert(array('s_name' => 'Administrator', 's_username' => $admin, 's_password' => osc_hash_password($password), 's_email' => Params::getParam('email')));
    $mPreference = Preference::newInstance();
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'pageTitle', 's_value' => Params::getParam('webtitle'), 'e_type' => 'STRING'));
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'contactEmail', 's_value' => Params::getParam('email'), 'e_type' => 'STRING'));
    $body = sprintf(__('Привет %s,'), Params::getParam('webtitle')) . "<br/><br/>";
    $body .= sprintf(__('Osclass успешно установлен %s и запущен. Вы можете получить доступ к панели администрирования:'), WEB_PATH) . '<br/>';
    $body .= '<ul>';
    $body .= '<li>' . sprintf(__('username: %s'), $admin) . '</li>';
    $body .= '<li>' . sprintf(__('password: %s'), $password) . '</li>';
    $body .= '</ul>';
    $body .= sprintf(__('Помните, если у вас появяться вопросы вы можете прочитать <a href="%1$s">документацию</a>, спросить на <a href="%2$s">форуме</a> или в <a href="%3$s">блоге</a>.'), 'http://os-class.ru/wiki', 'http://os-class.ru/frm', 'http://os-class.ru/category/articles');
    $body .= sprintf(' ' . __('Osclass doesn’t run any developments but we can put you in touch with third party developers through a Premium Support. And hey, if you would like to contribute to Osclass - learn how <a href="%1$s">here</a>!'), 'http://blog.osclass.org/2012/11/22/how-to-collaborate-to-osclass/') . '<br/><br/>';
    $body .= __('Аплодисменты,') . "<br/>";
    $body .= __('Ваш <a href="http://os-class.ru/">Osclass Rus Team</a> team');
    $sitename = strtolower($_SERVER['SERVER_NAME']);
    if (substr($sitename, 0, 4) == 'www.') {
        $sitename = substr($sitename, 4);
    }
    try {
        require_once LIB_PATH . 'phpmailer/class.phpmailer.php';
        $mail = new PHPMailer(true);
        $mail->CharSet = "utf-8";
        $mail->Host = "localhost";
        $mail->From = 'osclass@' . $sitename;
        $mail->FromName = 'Osclass';
        $mail->Subject = 'Osclass успешно установлен!';
        $mail->AddAddress(Params::getParam('email'), 'Osclass administrator');
        $mail->Body = $body;
        $mail->AltBody = $body;
        if (!$mail->Send()) {
            return array('email_status' => Params::getParam('email') . "<br>" . $mail->ErrorInfo, 's_password' => $password);
        }
        return array('email_status' => '', 's_password' => $password);
    } catch (phpmailerException $exception) {
        return array('email_status' => Params::getParam('email') . "<br>" . $exception->errorMessage(), 's_password' => $password);
    }
}
Esempio n. 9
0
function basic_info()
{
    require_once LIB_PATH . 'osclass/model/Admin.php';
    require_once LIB_PATH . 'osclass/helpers/hSecurity.php';
    $admin = Params::getParam('s_name');
    if ($admin == '') {
        $admin = 'admin';
    }
    $password = Params::getParam('s_passwd', false, false);
    if ($password == '') {
        $password = osc_genRandomPassword();
    }
    Admin::newInstance()->insert(array('s_name' => 'Administrator', 's_username' => $admin, 's_password' => sha1($password), 's_email' => Params::getParam('email')));
    $mPreference = Preference::newInstance();
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'pageTitle', 's_value' => Params::getParam('webtitle'), 'e_type' => 'STRING'));
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'contactEmail', 's_value' => Params::getParam('email'), 'e_type' => 'STRING'));
    $body = sprintf(__('Welcome %s,'), Params::getParam('webtitle')) . "<br/><br/>";
    $body .= sprintf(__('Your OSClass installation at %s is up and running. You can access the administration panel with these details:'), WEB_PATH) . "<br/>";
    $body .= '<ul>';
    $body .= '<li>' . sprintf(__('username: %s'), $admin) . '</li>';
    $body .= '<li>' . sprintf(__('password: %s'), $password) . '</li>';
    $body .= '</ul>';
    $body .= __('Regards,') . "<br/>";
    $body .= __('The <a href="http://osclass.org/">OSClass</a> team');
    $sitename = strtolower($_SERVER['SERVER_NAME']);
    if (substr($sitename, 0, 4) == 'www.') {
        $sitename = substr($sitename, 4);
    }
    try {
        require_once LIB_PATH . 'phpmailer/class.phpmailer.php';
        $mail = new PHPMailer(true);
        $mail->CharSet = "utf-8";
        $mail->Host = "localhost";
        $mail->From = 'osclass@' . $sitename;
        $mail->FromName = 'OSClass';
        $mail->Subject = 'OSClass successfully installed!';
        $mail->AddAddress(Params::getParam('email'), 'OSClass administrator');
        $mail->Body = $body;
        $mail->AltBody = $body;
        if (!$mail->Send()) {
            return array('email_status' => Params::getParam('email') . "<br>" . $mail->ErrorInfo, 's_password' => $password);
        }
        return array('email_status' => '', 's_password' => $password);
    } catch (phpmailerException $exception) {
        return array('email_status' => Params::getParam('email') . "<br>" . $exception->errorMessage(), 's_password' => $password);
    }
}
Esempio n. 10
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add_post_default':
             // add default category and reorder parent categories
             $fields['fk_i_parent_id'] = NULL;
             $fields['i_expiration_days'] = 0;
             $fields['i_position'] = 0;
             $fields['b_enabled'] = 1;
             $default_locale = osc_language();
             $aFieldsDescription[$default_locale]['s_name'] = "NEW CATEGORY, EDIT ME!";
             $categoryId = $this->categoryManager->insert($fields, $aFieldsDescription);
             // reorder parent categories. NEW category first
             $rootCategories = $this->categoryManager->findRootCategories();
             foreach ($rootCategories as $cat) {
                 $order = $cat['i_position'];
                 $order++;
                 $this->categoryManager->updateOrder($cat['pk_i_id'], $order);
             }
             $this->categoryManager->updateOrder($categoryId, '0');
             $this->redirectTo(osc_admin_base_url(true) . '?page=categories');
             break;
         case 'settings':
             // calling the categories settings view
             $this->doView('categories/settings.php');
             break;
         case 'settings_post':
             // updating categories option
             $selectableParent = Params::getParam('selectable_parent_categories');
             $updated = Preference::newInstance()->update(array('s_value' => $selectableParent), array('s_name' => 'selectable_parent_categories'));
             if ($updated > 0) {
                 osc_add_flash_ok_message(_m("Categories' settings have been updated"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=categories&action=settings');
             break;
         default:
             //
             $this->_exportVariableToView("categories", $this->categoryManager->toTreeAll());
             $this->doView("categories/index.php");
     }
 }
Esempio n. 11
0
 function doModel()
 {
     parent::doModel();
     if (osc_is_moderator() && ($this->action == 'settings' || $this->action == 'settings_post')) {
         osc_add_flash_error_message(_m("You don't have enough permissions"), "admin");
         $this->redirectTo(osc_admin_base_url());
     }
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             osc_csrf_check();
             $mItems = new ItemActions(true);
             switch (Params::getParam('bulk_actions')) {
                 case 'enable_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->enable($_id)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been enabled', '%d listings have been enabled', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'disable_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->disable((int) $_id)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been disabled', '%d listings have been disabled', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'activate_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->activate($_id)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been activated', '%d listings have been activated', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'deactivate_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->deactivate($_id)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_m('%d listing has been deactivated', '%d listings have been deactivated', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'premium_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->premium($_id)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been marked as premium', '%d listings have been marked as premium', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'depremium_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->premium($_id, false)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d change has been made', '%d changes have been made', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'spam_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->spam($_id)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been marked as spam', '%d listings have been marked as spam', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'despam_all':
                     $id = Params::getParam('id');
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $_id) {
                             if ($mItems->spam($_id, false)) {
                                 $numSuccess++;
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d change has been made', '%d changes have been made', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'delete_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $item = $this->itemManager->findByPrimaryKey($i);
                                 $success = $mItems->delete($item['s_secret'], $item['pk_i_id']);
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been deleted', '%d listings have been deleted', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'clear_spam_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $success = $this->itemManager->clearStat($i, 'spam');
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been unmarked as spam', '%d listings have been unmarked as spam', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'clear_bad_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $success = $this->itemManager->clearStat($i, 'bad');
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been unmarked as missclassified', '%d listings have been unmarked as missclassified', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'clear_dupl_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $success = $this->itemManager->clearStat($i, 'duplicated');
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been unmarked as duplicated', '%d listings have been unmarked as duplicated', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'clear_expi_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $success = $this->itemManager->clearStat($i, 'expired');
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been unmarked as expired', '%d listings have been unmarked as expired', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'clear_offe_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $success = $this->itemManager->clearStat($i, 'offensive');
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been unmarked as offensive', '%d listings have been unmarked as offensive', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 case 'clear_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id) {
                         $numSuccess = 0;
                         foreach ($id as $i) {
                             if ($i) {
                                 $success = $this->itemManager->clearStat($i, 'all');
                                 if ($success) {
                                     $numSuccess++;
                                 }
                             }
                         }
                         osc_add_flash_ok_message(sprintf(_mn('%d listing has been unmarked', '%d listings have been unmarked', $numSuccess), $numSuccess), 'admin');
                     }
                     break;
                 default:
                     if (Params::getParam("bulk_actions") != "") {
                         osc_run_hook("item_bulk_" . Params::getParam("bulk_actions"), Params::getParam('id'));
                     }
                     break;
             }
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'delete':
             //delete
             osc_csrf_check();
             $id = Params::getParam('id');
             $success = false;
             foreach ($id as $i) {
                 if ($i) {
                     $aItem = $this->itemManager->findByPrimaryKey($i);
                     $mItems = new ItemActions(true);
                     $success = $mItems->delete($aItem['s_secret'], $aItem['pk_i_id']);
                 }
             }
             if ($success) {
                 osc_add_flash_ok_message(_m('The listing has been deleted'), 'admin');
             } else {
                 osc_add_flash_error_message(_m("The listing couldn't be deleted"), 'admin');
             }
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'status':
             //status
             osc_csrf_check();
             $id = Params::getParam('id');
             $value = Params::getParam('value');
             if (!$id) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             if (!in_array($value, array('ACTIVE', 'INACTIVE', 'ENABLE', 'DISABLE'))) {
                 return false;
             }
             $item = $this->itemManager->findByPrimaryKey($id);
             $mItems = new ItemActions(true);
             switch ($value) {
                 case 'ACTIVE':
                     $success = $mItems->activate($id);
                     if ($success && $success > 0) {
                         osc_add_flash_ok_message(_m('The listing has been activated'), 'admin');
                     } else {
                         if (!$success) {
                             osc_add_flash_error_message(_m('An error has occurred'), 'admin');
                         } else {
                             osc_add_flash_error_message(_m("The listing can't be activated because it's blocked"), 'admin');
                         }
                     }
                     break;
                 case 'INACTIVE':
                     $success = $mItems->deactivate($id);
                     if ($success && $success > 0) {
                         osc_add_flash_ok_message(_m('The listing has been deactivated'), 'admin');
                     } else {
                         osc_add_flash_error_message(_m('An error has occurred'), 'admin');
                     }
                     break;
                 case 'ENABLE':
                     $success = $mItems->enable($id);
                     if ($success && $success > 0) {
                         osc_add_flash_ok_message(_m('The listing has been enabled'), 'admin');
                     } else {
                         osc_add_flash_error_message(_m('An error has occurred'), 'admin');
                     }
                     break;
                 case 'DISABLE':
                     $success = $mItems->disable($id);
                     if ($success && $success > 0) {
                         osc_add_flash_ok_message(_m('The listing has been disabled'), 'admin');
                     } else {
                         osc_add_flash_error_message(_m('An error has occurred'), 'admin');
                     }
                     break;
             }
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'status_premium':
             //status premium
             osc_csrf_check();
             $id = Params::getParam('id');
             $value = Params::getParam('value');
             if (!$id) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             if (!in_array($value, array(0, 1))) {
                 return false;
             }
             $mItems = new ItemActions(true);
             if ($mItems->premium($id, $value == 1 ? true : false)) {
                 osc_add_flash_ok_message(_m('Changes have been applied'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('An error has occurred'), 'admin');
             }
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'status_spam':
             //status spam
             osc_csrf_check();
             $id = Params::getParam('id');
             $value = Params::getParam('value');
             if (!$id) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             if (!in_array($value, array(0, 1))) {
                 return false;
             }
             $mItems = new ItemActions(true);
             if ($mItems->spam($id, $value == 1 ? true : false)) {
                 osc_add_flash_ok_message(_m('Changes have been applied'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('An error has occurred'), 'admin');
             }
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'clear_stat':
             osc_csrf_check();
             $id = Params::getParam('id');
             $stat = Params::getParam('stat');
             if (!$id) {
                 return false;
             }
             if (!$stat) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             $success = $this->itemManager->clearStat($id, $stat);
             if ($success) {
                 osc_add_flash_ok_message(_m('The listing has been unmarked as') . " {$stat}", 'admin');
             } else {
                 osc_add_flash_error_message(_m("The listing hasn't been unmarked as") . " {$stat}", 'admin');
             }
             $this->redirectTo($_SERVER['HTTP_REFERER']);
             break;
         case 'item_edit':
             // edit item
             $id = Params::getParam('id');
             $item = Item::newInstance()->findByPrimaryKey($id);
             if (count($item) <= 0) {
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             }
             $csrf_token = osc_csrf_token_url();
             if ($item['b_active']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=INACTIVE">' . __('Deactivate') . '</a>';
             } else {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=ACTIVE">' . __('Activate') . '</a>';
             }
             if ($item['b_enabled']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=DISABLE">' . __('Block') . '</a>';
             } else {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=ENABLE">' . __('Unblock') . '</a>';
             }
             if ($item['b_premium']) {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status_premium&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=0">' . __('Unmark as premium') . '</a>';
             } else {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status_premium&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=1">' . __('Mark as premium') . '</a>';
             }
             if ($item['b_spam']) {
                 $actions[] = '<a class="btn btn-red float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status_spam&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=0">' . __('Unmark as spam') . '</a>';
             } else {
                 $actions[] = '<a class="btn float-left" href="' . osc_admin_base_url(true) . '?page=items&amp;action=status_spam&amp;id=' . $item['pk_i_id'] . '&amp;' . $csrf_token . '&amp;value=1">' . __('Mark as spam') . '</a>';
             }
             $this->_exportVariableToView("actions", $actions);
             $form = count(Session::newInstance()->_getForm());
             $keepForm = count(Session::newInstance()->_getKeepForm());
             if ($form == 0 || $form == $keepForm) {
                 Session::newInstance()->_dropKeepForm();
             }
             // save referer if belongs to manage items
             // redirect only if ManageItems or ReportedListngs
             if (isset($_SERVER['HTTP_REFERER'])) {
                 $referer = $_SERVER['HTTP_REFERER'];
                 if (preg_match('/page=items/', $referer)) {
                     if (preg_match("/action=([\\p{L}|_|-]+)/u", $referer, $matches)) {
                         if ($matches[1] == 'items_reported') {
                             Session::newInstance()->_set('osc_admin_referer', $referer);
                         }
                     } else {
                         // no actions - Manage Listings
                         Session::newInstance()->_set('osc_admin_referer', $referer);
                     }
                 }
             }
             $this->_exportVariableToView("item", $item);
             $this->_exportVariableToView("new_item", FALSE);
             osc_run_hook("before_item_edit", $item);
             $this->doView('items/frm.php');
             break;
         case 'item_edit_post':
             osc_csrf_check();
             $mItems = new ItemActions(true);
             $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);
                 }
             }
             $success = $mItems->edit();
             if ($success == 1) {
                 osc_add_flash_ok_message(_m('Changes saved correctly'), 'admin');
                 $url = osc_admin_base_url(true) . "?page=items";
                 // if Referer is saved that means referer is ManageListings or ReportListings
                 if (Session::newInstance()->_get('osc_admin_referer') != '') {
                     $url = Session::newInstance()->_get('osc_admin_referer');
                 }
                 Session::newInstance()->_clearVariables();
                 $this->redirectTo($url);
             } else {
                 osc_add_flash_error_message($success, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items&action=item_edit&id=" . Params::getParam('id'));
             }
             break;
         case 'deleteResource':
             //delete resource
             osc_csrf_check();
             $id = Params::getParam('id');
             $name = Params::getParam('name');
             $fkid = Params::getParam('fkid');
             // delete files
             osc_deleteResource($id, true);
             Log::newInstance()->insertLog('items', 'deleteResource', $id, $id, 'admin', osc_logged_admin_id());
             $result = ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $fkid, 's_name' => $name));
             if ($result === false) {
                 osc_add_flash_error_message(_m('An error has occurred'), 'admin');
             } else {
                 osc_add_flash_ok_message(_m('Resource deleted'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'post':
             // add item
             $form = count(Session::newInstance()->_getForm());
             $keepForm = count(Session::newInstance()->_getKeepForm());
             if ($form == 0 || $form == $keepForm) {
                 Session::newInstance()->_dropKeepForm();
             }
             $this->_exportVariableToView("new_item", TRUE);
             osc_run_hook('post_item');
             $this->doView('items/frm.php');
             break;
         case 'post_item':
             //post item
             osc_csrf_check();
             $mItem = new ItemActions(true);
             $mItem->prepareData(true);
             // set all parameters into session
             foreach ($mItem->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);
                 }
             }
             $success = $mItem->add();
             if ($success == 1 || $success == 2) {
                 $url = osc_admin_base_url(true) . "?page=items";
                 // if Referer is saved that means referer is ManageListings or ReportListings
                 if (Session::newInstance()->_get('osc_admin_referer') != '') {
                     Session::newInstance()->_drop('osc_admin_referer');
                     $url = Session::newInstance()->_get('osc_admin_referer');
                 }
                 Session::newInstance()->_clearVariables();
                 osc_add_flash_ok_message(_m('A new listing has been added'), 'admin');
                 $this->redirectTo($url);
             } else {
                 osc_add_flash_error_message($success, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items&action=post");
             }
             break;
         case 'settings':
             // calling the items settings view
             $this->doView('items/settings.php');
             break;
         case 'settings_post':
             // update item settings
             osc_csrf_check();
             $iUpdated = 0;
             $enabledRecaptchaItems = Params::getParam('enabled_recaptcha_items');
             $enabledRecaptchaItems = $enabledRecaptchaItems == '1' ? true : false;
             $moderateItems = Params::getParam('moderate_items');
             $moderateItems = $moderateItems != '' ? true : false;
             $numModerateItems = Params::getParam('num_moderate_items');
             $itemsWaitTime = Params::getParam('items_wait_time');
             $loggedUserItemValidation = Params::getParam('logged_user_item_validation');
             $loggedUserItemValidation = $loggedUserItemValidation != '' ? true : false;
             $regUserPost = Params::getParam('reg_user_post');
             $regUserPost = $regUserPost != '' ? true : false;
             $notifyNewItem = Params::getParam('notify_new_item');
             $notifyNewItem = $notifyNewItem != '' ? true : false;
             $notifyContactItem = Params::getParam('notify_contact_item');
             $notifyContactItem = $notifyContactItem != '' ? true : false;
             $notifyContactFriends = Params::getParam('notify_contact_friends');
             $notifyContactFriends = $notifyContactFriends != '' ? true : false;
             $enabledFieldPriceItems = Params::getParam('enableField#f_price@items');
             $enabledFieldPriceItems = $enabledFieldPriceItems != '' ? true : false;
             $enabledFieldImagesItems = Params::getParam('enableField#images@items');
             $enabledFieldImagesItems = $enabledFieldImagesItems != '' ? true : false;
             $numImagesItems = Params::getParam('numImages@items');
             if ($numImagesItems == '') {
                 $numImagesItems = 0;
             }
             $regUserCanContact = Params::getParam('reg_user_can_contact');
             $regUserCanContact = $regUserCanContact != '' ? true : false;
             $contactItemAttachment = Params::getParam('item_attachment');
             $contactItemAttachment = $contactItemAttachment != '' ? true : false;
             $msg = '';
             if (!osc_validate_int(Params::getParam("items_wait_time"))) {
                 $msg .= _m("Wait time must only contain numeric characters") . "<br/>";
             }
             if (Params::getParam("num_moderate_items") != '' && !osc_validate_int(Params::getParam("num_moderate_items"))) {
                 $msg .= _m("Number of moderated listings must only contain numeric characters") . "<br/>";
             }
             if (!osc_validate_int($numImagesItems)) {
                 $msg .= _m("Images per listing must only contain numeric characters") . "<br/>";
             }
             if ($msg != '') {
                 osc_add_flash_error_message($msg, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=items&action=settings');
             }
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledRecaptchaItems), array('s_name' => 'enabled_recaptcha_items'));
             if ($moderateItems) {
                 $iUpdated += Preference::newInstance()->update(array('s_value' => $numModerateItems), array('s_name' => 'moderate_items'));
             } else {
                 $iUpdated += Preference::newInstance()->update(array('s_value' => '-1'), array('s_name' => 'moderate_items'));
             }
             $iUpdated += Preference::newInstance()->update(array('s_value' => $loggedUserItemValidation), array('s_name' => 'logged_user_item_validation'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPost), array('s_name' => 'reg_user_post'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewItem), array('s_name' => 'notify_new_item'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyContactItem), array('s_name' => 'notify_contact_item'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyContactFriends), array('s_name' => 'notify_contact_friends'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledFieldPriceItems), array('s_name' => 'enableField#f_price@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledFieldImagesItems), array('s_name' => 'enableField#images@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $itemsWaitTime), array('s_name' => 'items_wait_time'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $numImagesItems), array('s_name' => 'numImages@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserCanContact), array('s_name' => 'reg_user_can_contact'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $contactItemAttachment), array('s_name' => 'item_attachment'));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(_m("Listings' settings have been updated"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=items&action=settings');
             break;
         case 'items_reported':
             require_once osc_lib_path() . "osclass/classes/datatables/ItemsDataTable.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("get");
             $itemsDataTable = new ItemsDataTable();
             $itemsDataTable->tableReported($params);
             $aData = $itemsDataTable->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', $itemsDataTable->rawRows());
             //calling the view...
             $this->doView('items/reported.php');
             break;
         default:
             // default
             require_once osc_lib_path() . "osclass/classes/datatables/ItemsDataTable.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("get");
             $itemsDataTable = new ItemsDataTable();
             $itemsDataTable->table($params);
             $aData = $itemsDataTable->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', $itemsDataTable->withFilters());
             $this->_exportVariableToView('aRawRows', $itemsDataTable->rawRows());
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'delete_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Delete'))), 'label' => __('Delete')), array('value' => 'activate_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Activate'))), 'label' => __('Activate')), array('value' => 'deactivate_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Deactivate'))), 'label' => __('Deactivate')), array('value' => 'disable_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Block'))), 'label' => __('Block')), array('value' => 'enable_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Unblock'))), 'label' => __('Unblock')), array('value' => 'premium_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Mark as premium'))), 'label' => __('Mark as premium')), array('value' => 'depremium_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Unmark as premium'))), 'label' => __('Unmark as premium')), array('value' => 'spam_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Mark as spam'))), 'label' => __('Mark as spam')), array('value' => 'despam_all', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected listings?'), strtolower(__('Unmark as spam'))), 'label' => __('Unmark as spam')));
             $bulk_options = osc_apply_filter("item_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             //calling the view...
             $this->doView('items/index.php');
     }
 }
Esempio n. 12
0
        $title = __('OSClass &raquo; Has some errors');
        $message = __('We encountered some problems updating the database structure. The following queries failed:');
        $message .= "<br/><br/>" . implode("<br>", $error_queries[2]);
        $message .= "<br/><br/>" . sprintf(__('These errors could be false-positive errors. If you\'re sure that is the case, you could <a href="%s">continue with the upgrade</a>, or <a href="http://forums.osclass.org/">ask in our forums</a>.'), $skip_db_link);
        osc_die($title, $message);
    }
}
// UPDATE DATABASE
if (!defined('AUTO_UPGRADE')) {
    if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
        $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
        $conn = getConnection();
        $conn->osc_updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
    }
}
Preference::newInstance()->update(array('s_value' => time()), array('s_section' => 'osclass', 's_name' => 'last_version_check'));
$conn = getConnection();
if (osc_version() < 210) {
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'save_latest_searches', '0', 'BOOLEAN')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'purge_latest_searches', '1000', 'STRING')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'selectable_parent_categories', '1', 'BOOLEAN')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'ping_search_engines', '1', 'BOOLEAN')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'numImages@items', '0', 'BOOLEAN')", DB_TABLE_PREFIX));
    $enableItemValidation = getBoolPreference('enabled_item_validation') ? 0 : -1;
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'moderate_items', '{$enableItemValidation}', 'INTEGER')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'items_wait_time', '0', 'INTEGER')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'comments_per_page', '10', 'INTEGER')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'reg_user_post_comments', '0', 'BOOLEAN')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'reg_user_can_contact', '0', 'BOOLEAN')", DB_TABLE_PREFIX));
    $conn->osc_dbExec(sprintf("INSERT INTO %st_preference VALUES ('osclass', 'allow_report_osclass', '1', 'BOOLEAN')", DB_TABLE_PREFIX));
    $users = User::newInstance()->listAll();
Esempio n. 13
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             switch (Params::getParam('bulk_actions')) {
                 case 'enable_all':
                     $id = Params::getParam('id');
                     $value = 1;
                     try {
                         if ($id) {
                             $count = count($id);
                             foreach ($id as $_id) {
                                 $this->itemManager->update(array('b_enabled' => $value), array('pk_i_id' => $_id));
                                 $item = $this->itemManager->findByPrimaryKey($_id);
                                 CategoryStats::newInstance()->increaseNumItems($item['fk_i_category_id']);
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d item has been enabled', '%d items have been enabled', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'disable_all':
                     $id = Params::getParam('id');
                     $value = 0;
                     try {
                         if ($id) {
                             $count = count($id);
                             foreach ($id as $_id) {
                                 $this->itemManager->update(array('b_enabled' => $value), array('pk_i_id' => $_id));
                                 $item = $this->itemManager->findByPrimaryKey($_id);
                                 CategoryStats::newInstance()->decreaseNumItems($item['fk_i_category_id']);
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d item has been disabled', '%d items have been disabled', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'activate_all':
                     $id = Params::getParam('id');
                     $value = 1;
                     try {
                         if ($id) {
                             $count = count($id);
                             foreach ($id as $_id) {
                                 $this->itemManager->update(array('b_active' => $value), array('pk_i_id' => $_id));
                                 $item = $this->itemManager->findByPrimaryKey($_id);
                                 CategoryStats::newInstance()->increaseNumItems($item['fk_i_category_id']);
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d item has been activated', '%d items have been activated', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'deactivate_all':
                     $id = Params::getParam('id');
                     $value = 0;
                     try {
                         if ($id) {
                             $count = count($id);
                             foreach ($id as $_id) {
                                 $this->itemManager->update(array('b_active' => $value), array('pk_i_id' => $_id));
                                 $item = $this->itemManager->findByPrimaryKey($_id);
                                 CategoryStats::newInstance()->decreaseNumItems($item['fk_i_category_id']);
                             }
                             osc_add_flash_ok_message(sprintf(_m('%d item has been deactivated', '%d items have been deactivated', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'premium_all':
                     $id = Params::getParam('id');
                     $value = 1;
                     try {
                         if ($id) {
                             $count = count($id);
                             $mItems = new ItemActions(true);
                             foreach ($id as $_id) {
                                 $mItems->premium($_id);
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d item has been marked as premium', '%d items have been marked as premium', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'depremium_all':
                     $id = Params::getParam('id');
                     $value = 0;
                     try {
                         if ($id) {
                             $count = count($id);
                             $mItems = new ItemActions(true);
                             foreach ($id as $_id) {
                                 $mItems->premium($_id, false);
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d change has been made', '%d changes have been made', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'spam_all':
                     $id = Params::getParam('id');
                     $value = 1;
                     try {
                         if ($id) {
                             $count = count($id);
                             foreach ($id as $_id) {
                                 $this->itemManager->update(array('b_spam' => $value), array('pk_i_id' => $_id));
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d item has been marked as spam', '%d items have been marked as spam', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'despam_all':
                     $id = Params::getParam('id');
                     $value = 0;
                     try {
                         if ($id) {
                             $count = count($id);
                             foreach ($id as $_id) {
                                 $this->itemManager->update(array('b_spam' => $value), array('pk_i_id' => $_id));
                             }
                             osc_add_flash_ok_message(sprintf(_mn('%d change have been made', '%d changes have been made', $count), $count), 'admin');
                         }
                     } catch (Exception $e) {
                         osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
                     }
                     break;
                 case 'delete_all':
                     $id = Params::getParam('id');
                     $success = false;
                     if ($id != '') {
                         $count = count($id);
                         foreach ($id as $i) {
                             if ($i) {
                                 $item = $this->itemManager->findByPrimaryKey($i);
                                 $mItems = new ItemActions(true);
                                 $success = $mItems->delete($item['s_secret'], $item['pk_i_id']);
                             }
                         }
                     }
                     if ($success) {
                         osc_add_flash_ok_message(sprintf(_mn('%d item has been deleted', '%d items have been deleted', $count), $count), 'admin');
                     } else {
                         osc_add_flash_error_message(_m('The item couldn\'t be deleted'), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . "?page=items");
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'delete':
             //delete
             $id = Params::getParam('id');
             $success = false;
             foreach ($id as $i) {
                 if ($i) {
                     $item = $this->itemManager->findByPrimaryKey($i);
                     $mItems = new ItemActions(true);
                     $success = $mItems->delete($item['s_secret'], $item['pk_i_id']);
                 }
             }
             if ($success) {
                 osc_add_flash_ok_message(_m('The item has been deleted'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('The item couldn\'t be deleted'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'status':
             //status
             $id = Params::getParam('id');
             $value = Params::getParam('value');
             if (!$id) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             if (!in_array($value, array('ACTIVE', 'INACTIVE', 'ENABLE', 'DISABLE'))) {
                 return false;
             }
             try {
                 $item = $this->itemManager->findByPrimaryKey($id);
                 switch ($value) {
                     case 'ACTIVE':
                         $this->itemManager->update(array('b_active' => 1), array('pk_i_id' => $id));
                         osc_add_flash_ok_message(_m('The item has been activated'), 'admin');
                         if ($item['b_enabled'] == 1 && $item['b_active'] == 0) {
                             CategoryStats::newInstance()->increaseNumItems($item['fk_i_category_id']);
                             if ($item['fk_i_user_id'] != null) {
                                 $user = User::newInstance()->findByPrimaryKey($item['fk_i_user_id']);
                                 if ($user) {
                                     User::newInstance()->update(array('i_items' => $user['i_items'] + 1), array('pk_i_id' => $user['pk_i_id']));
                                 }
                             }
                         }
                         break;
                     case 'INACTIVE':
                         $this->itemManager->update(array('b_active' => 0), array('pk_i_id' => $id));
                         osc_add_flash_ok_message(_m('The item has been deactivated'), 'admin');
                         if ($item['b_enabled'] == 1 && $item['b_active'] == 1) {
                             CategoryStats::newInstance()->decreaseNumItems($item['fk_i_category_id']);
                             if ($item['fk_i_user_id'] != null) {
                                 $user = User::newInstance()->findByPrimaryKey($item['fk_i_user_id']);
                                 if ($user) {
                                     User::newInstance()->update(array('i_items' => $user['i_items'] - 1), array('pk_i_id' => $user['pk_i_id']));
                                 }
                             }
                         }
                         break;
                     case 'ENABLE':
                         $this->itemManager->update(array('b_enabled' => 1), array('pk_i_id' => $id));
                         osc_add_flash_ok_message(_m('The item has been enabled'), 'admin');
                         if ($item['b_enabled'] == 0 && $item['b_active'] == 1) {
                             CategoryStats::newInstance()->increaseNumItems($item['fk_i_category_id']);
                             if ($item['fk_i_user_id'] != null) {
                                 $user = User::newInstance()->findByPrimaryKey($item['fk_i_user_id']);
                                 if ($user) {
                                     User::newInstance()->update(array('i_items' => $user['i_items'] + 1), array('pk_i_id' => $user['pk_i_id']));
                                 }
                             }
                         }
                         break;
                     case 'DISABLE':
                         $this->itemManager->update(array('b_enabled' => 0), array('pk_i_id' => $id));
                         osc_add_flash_ok_message(_m('The item has been disabled'), 'admin');
                         if ($item['b_enabled'] == 1 && $item['b_active'] == 1) {
                             CategoryStats::newInstance()->decreaseNumItems($item['fk_i_category_id']);
                             if ($item['fk_i_user_id'] != null) {
                                 $user = User::newInstance()->findByPrimaryKey($item['fk_i_user_id']);
                                 if ($user) {
                                     User::newInstance()->update(array('i_items' => $user['i_items'] - 1), array('pk_i_id' => $user['pk_i_id']));
                                 }
                             }
                         }
                         break;
                 }
             } catch (Exception $e) {
                 osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'status_premium':
             //status premium
             $id = Params::getParam('id');
             $value = Params::getParam('value');
             if (!$id) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             if (!in_array($value, array(0, 1))) {
                 return false;
             }
             try {
                 $mItems = new ItemActions(true);
                 $mItems->premium($id, $value == 1 ? true : false);
                 /*$this->itemManager->update(
                           array('b_premium' => $value),
                           array('pk_i_id' => $id)
                   );*/
                 osc_add_flash_ok_message(_m('Changes have been applied'), 'admin');
             } catch (Exception $e) {
                 osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'status_spam':
             //status spam
             $id = Params::getParam('id');
             $value = Params::getParam('value');
             if (!$id) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             if (!in_array($value, array(0, 1))) {
                 return false;
             }
             try {
                 $this->itemManager->update(array('b_spam' => $value), array('pk_i_id' => $id));
                 osc_add_flash_ok_message(_m('Changes have been applied'), 'admin');
             } catch (Exception $e) {
                 osc_add_flash_error_message(sprintf(_m('Error: %s'), $e->getMessage()), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'clear_stat':
             $id = Params::getParam('id');
             $stat = Params::getParam('stat');
             if (!$id) {
                 return false;
             }
             if (!$stat) {
                 return false;
             }
             $id = (int) $id;
             if (!is_numeric($id)) {
                 return false;
             }
             $success = $this->itemManager->clearStat($id, $stat);
             if ($success) {
                 osc_add_flash_ok_message(_m('The item has been unmarked as') . " {$stat}", 'admin');
             } else {
                 osc_add_flash_error_message(_m('The item hasn\'t been unmarked as') . " {$stat}", 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=items&stat=" . $stat);
             break;
         case 'item_edit':
             // edit item
             $id = Params::getParam('id');
             $item = Item::newInstance()->findByPrimaryKey($id);
             if (count($item) <= 0) {
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             }
             $form = count(Session::newInstance()->_getForm());
             $keepForm = count(Session::newInstance()->_getKeepForm());
             if ($form == 0 || $form == $keepForm) {
                 Session::newInstance()->_dropKeepForm();
             }
             $this->_exportVariableToView("item", $item);
             $this->_exportVariableToView("new_item", FALSE);
             $this->doView('items/frm.php');
             break;
         case 'item_edit_post':
             $mItems = new ItemActions(true);
             $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);
                 }
             }
             $success = $mItems->edit();
             if ($success == 1) {
                 $id = Params::getParam('userId');
                 if ($id != '') {
                     $user = User::newInstance()->findByPrimaryKey($id);
                     Item::newInstance()->update(array('fk_i_user_id' => $id, 's_contact_name' => $user['s_name'], 's_contact_email' => $user['s_email']), array('pk_i_id' => Params::getParam('id'), 's_secret' => Params::getParam('secret')));
                 } else {
                     Item::newInstance()->update(array('fk_i_user_id' => NULL, 's_contact_name' => Params::getParam('contactName'), 's_contact_email' => Params::getParam('contactEmail')), array('pk_i_id' => Params::getParam('id'), 's_secret' => Params::getParam('secret')));
                 }
                 osc_add_flash_ok_message(_m('Changes saved correctly'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             } else {
                 osc_add_flash_error_message($success, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items&action=item_edit&id=" . Params::getParam('id'));
             }
             break;
         case 'deleteResource':
             //delete resource
             $id = Params::getParam('id');
             $name = Params::getParam('name');
             $fkid = Params::getParam('fkid');
             // delete files
             osc_deleteResource($id);
             ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $fkid, 's_name' => $name));
             osc_add_flash_ok_message(_m('Resource deleted'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             break;
         case 'post':
             // add item
             $form = count(Session::newInstance()->_getForm());
             $keepForm = count(Session::newInstance()->_getKeepForm());
             if ($form == 0 || $form == $keepForm) {
                 Session::newInstance()->_dropKeepForm();
             }
             $this->_exportVariableToView("new_item", TRUE);
             $this->doView('items/frm.php');
             break;
         case 'post_item':
             //post item
             $mItem = new ItemActions(true);
             $mItem->prepareData(true);
             // set all parameters into session
             foreach ($mItem->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);
                 }
             }
             $success = $mItem->add();
             if ($success == 1 || $success == 2) {
                 osc_add_flash_ok_message(_m('A new item has been added'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items");
             } else {
                 osc_add_flash_error_message($success, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=items&action=post");
             }
             break;
         case 'settings':
             // calling the items settings view
             $this->doView('items/settings.php');
             break;
         case 'settings_post':
             // update item settings
             $iUpdated = 0;
             $enabledRecaptchaItems = Params::getParam('enabled_recaptcha_items');
             $enabledRecaptchaItems = $enabledRecaptchaItems != '' ? true : false;
             $moderateItems = Params::getParam('moderate_items');
             $moderateItems = $moderateItems != '' ? true : false;
             $numModerateItems = Params::getParam('num_moderate_items');
             $itemsWaitTime = Params::getParam('items_wait_time');
             $loggedUserItemValidation = Params::getParam('logged_user_item_validation');
             $loggedUserItemValidation = $loggedUserItemValidation != '' ? true : false;
             $regUserPost = Params::getParam('reg_user_post');
             $regUserPost = $regUserPost != '' ? true : false;
             $notifyNewItem = Params::getParam('notify_new_item');
             $notifyNewItem = $notifyNewItem != '' ? true : false;
             $notifyContactItem = Params::getParam('notify_contact_item');
             $notifyContactItem = $notifyContactItem != '' ? true : false;
             $notifyContactFriends = Params::getParam('notify_contact_friends');
             $notifyContactFriends = $notifyContactFriends != '' ? true : false;
             $enabledFieldPriceItems = Params::getParam('enableField#f_price@items');
             $enabledFieldPriceItems = $enabledFieldPriceItems != '' ? true : false;
             $enabledFieldImagesItems = Params::getParam('enableField#images@items');
             $enabledFieldImagesItems = $enabledFieldImagesItems != '' ? true : false;
             $numImagesItems = Params::getParam('numImages@items');
             if ($numImagesItems == '') {
                 $numImagesItems = 0;
             }
             $regUserCanContact = Params::getParam('reg_user_can_contact');
             $regUserCanContact = $regUserCanContact != '' ? true : false;
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledRecaptchaItems), array('s_name' => 'enabled_recaptcha_items'));
             if ($moderateItems) {
                 $iUpdated += Preference::newInstance()->update(array('s_value' => $numModerateItems), array('s_name' => 'moderate_items'));
             } else {
                 $iUpdated += Preference::newInstance()->update(array('s_value' => '-1'), array('s_name' => 'moderate_items'));
             }
             $iUpdated += Preference::newInstance()->update(array('s_value' => $loggedUserItemValidation), array('s_name' => 'logged_user_item_validation'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPost), array('s_name' => 'reg_user_post'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewItem), array('s_name' => 'notify_new_item'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyContactItem), array('s_name' => 'notify_contact_item'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyContactFriends), array('s_name' => 'notify_contact_friends'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledFieldPriceItems), array('s_name' => 'enableField#f_price@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledFieldImagesItems), array('s_name' => 'enableField#images@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $itemsWaitTime), array('s_name' => 'items_wait_time'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $numImagesItems), array('s_name' => 'numImages@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserCanContact), array('s_name' => 'reg_user_can_contact'));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(_m('Items\' settings have been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=items&action=settings');
             break;
         default:
             //default
             $catId = Params::getParam('catId');
             $countries = Country::newInstance()->listAll();
             $regions = array();
             if (count($countries) > 0) {
                 $regions = Region::newInstance()->getByCountry($countries[0]['pk_c_code']);
             }
             $cities = array();
             if (count($regions) > 0) {
                 $cities = City::newInstance()->listWhere("fk_i_region_id = %d", $regions[0]['pk_i_id']);
             }
             //preparing variables for the view
             $this->_exportVariableToView("users", User::newInstance()->listAll());
             $this->_exportVariableToView("catId", $catId);
             $this->_exportVariableToView("stat", Params::getParam('stat'));
             $this->_exportVariableToView("countries", $countries);
             $this->_exportVariableToView("regions", $regions);
             $this->_exportVariableToView("cities", $cities);
             //calling the view...
             $this->doView('items/index.php');
     }
 }
function pop_delete()
{
    Preference::newInstance()->delete(array('s_section' => 'pop'));
}
Esempio n. 15
0
/**
 * Gets preference
 *
 * @param string $key
 * @param string $section
 * @return string
 */
function getPreference($key, $section = 'osclass')
{
    $_P = Preference::newInstance();
    return $_P->get($key, $section);
}
Esempio n. 16
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:
     }
 }
Esempio n. 17
0
function cookie_uninstall()
{
    Preference::newInstance()->delete(array('s_section' => 'cookie'));
}
Esempio n. 18
0
function osclasswizards_delete()
{
    Preference::newInstance()->delete(array('s_section' => OSCLASSWIZARDS_THEME_FOLDER));
}
Esempio n. 19
0
 static function reload()
 {
     Preference::newInstance()->toArray();
     self::init();
 }
Esempio n. 20
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;
     }
 }
Esempio n. 21
0
function ping_search_engines($bool)
{
    $mPreference = Preference::newInstance();
    if ($bool == 1) {
        $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'ping_search_engines', 's_value' => '1', 'e_type' => 'BOOLEAN'));
        // GOOGLE
        osc_doRequest('http://www.google.com/webmasters/sitemaps/ping?sitemap=' . urlencode(osc_search_url(array('sFeed' => 'rss'))), array());
        // BING
        osc_doRequest('http://www.bing.com/webmaster/ping.aspx?siteMap=' . urlencode(osc_search_url(array('sFeed' => 'rss'))), array());
        // YAHOO!
        osc_doRequest('http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=' . urlencode(osc_search_url(array('sFeed' => 'rss'))), array());
    } else {
        $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'ping_search_engines', 's_value' => '0', 'e_type' => 'BOOLEAN'));
    }
}
Esempio n. 22
0
function google_analytics_call_after_uninstall()
{
    Preference::newInstance()->delete(array("s_section" => "plugin-google_analytics", "s_name" => "google_analytics_id"));
}
Esempio n. 23
0
/**
 * Change version to param number
 *
 * @param mixed version
 */
function osc_changeVersionTo($version = null)
{
    if ($version != null) {
        Preference::newInstance()->update(array('s_value' => $version), array('s_section' => 'osclass', 's_name' => 'version'));
        //XXX: I don't know if it's really needed. Only for reload the values of the preferences
        Preference::newInstance()->toArray();
    }
}
Esempio n. 24
0
function finish_installation()
{
    require_once LIB_PATH . 'osclass/helpers/hSecurity.php';
    require_once LIB_PATH . 'osclass/model/Admin.php';
    require_once LIB_PATH . 'osclass/model/Preference.php';
    require_once LIB_PATH . 'osclass/model/Category.php';
    require_once LIB_PATH . 'osclass/model/Item.php';
    require_once LIB_PATH . 'osclass/core/Params.php';
    require_once LIB_PATH . 'osclass/compatibility.php';
    require_once LIB_PATH . 'osclass/utils.php';
    $data = array();
    $password = osc_genRandomPassword();
    $mAdmin = new Admin();
    $admin_user = '******';
    $admin = $mAdmin->update(array('s_password' => sha1($password)), array('s_username' => $admin_user));
    $mPreference = Preference::newInstance();
    $mPreference->insert(array('s_section' => 'osclass', 's_name' => 'osclass_installed', 's_value' => '1', 'e_type' => 'BOOLEAN'));
    // update categories
    $mCategories = new Category();
    if (Params::getParam('submit') != '') {
        $categories = Params::getParam('categories');
        if (is_array($categories)) {
            foreach ($categories as $category_id) {
                $mCategories->update(array('b_enabled' => '1'), array('pk_i_id' => $category_id));
            }
        }
    }
    $aCategoriesToDelete = $mCategories->listWhere("a.b_enabled = 0");
    foreach ($aCategoriesToDelete as $aCategory) {
        $mCategories->deleteByPrimaryKey($aCategory['pk_i_id']);
    }
    $admin = $mAdmin->findByPrimaryKey(1);
    $data['s_email'] = $admin['s_email'];
    $data['admin_user'] = $admin_user;
    $data['password'] = $password;
    $body = 'Welcome ' . $mPreference->get('pageTitle') . ',<br/><br/>';
    $body .= 'Your OSClass installation at ' . WEB_PATH . ' is up and running. You can access to the administration panel with this data access:<br/>';
    $body .= '<ul>';
    $body .= '<li>username: '******'</li>';
    $body .= '<li>password: '******'</li>';
    $body .= '</ul>';
    $body .= 'Regards,<br/>';
    $body .= 'The <a href=\'http://osclass.org/\'>OSClass</a> team';
    $sitename = strtolower($_SERVER['SERVER_NAME']);
    if (substr($sitename, 0, 4) == 'www.') {
        $sitename = substr($sitename, 4);
    }
    require_once LIB_PATH . 'phpmailer/class.phpmailer.php';
    $mail = new PHPMailer();
    $mail->CharSet = "utf-8";
    $mail->Host = "localhost";
    $mail->From = 'osclass@' . $sitename;
    $mail->FromName = 'OSClass';
    $mail->Subject = 'OSClass successfully installed!';
    $mail->AddAddress($admin['s_email'], 'OSClass administrator');
    $mail->Body = $body;
    $mail->AltBody = $body;
    if (!$mail->Send()) {
        echo $mail->ErrorInfo;
    }
    return $data;
}
Esempio n. 25
0
 public static function currency_select($currencies = null, $item = null)
 {
     if ($currencies == null) {
         $currencies = osc_get_currencies();
     }
     if ($item == null) {
         $item = osc_item();
     }
     if (Session::newInstance()->_getForm('currency') != "") {
         $item['fk_c_currency_code'] = Session::newInstance()->_getForm('currency');
     }
     if (count($currencies) > 1) {
         $default_key = null;
         $currency = Preference::newInstance()->findByConditions(array('s_section' => 'osclass', 's_name' => 'currency'));
         if (isset($item['fk_c_currency_code'])) {
             $default_key = $item['fk_c_currency_code'];
         } elseif (is_array($currency)) {
             if (isset($currency['s_value'])) {
                 $default_key = $currency['s_value'];
             }
         }
         parent::generic_select('currency', $currencies, 'pk_c_code', 's_description', null, $default_key);
     } else {
         if (count($currencies) == 1) {
             parent::generic_input_hidden("currency", $currencies[0]["pk_c_code"]);
             echo $currencies[0]['s_description'];
         }
     }
 }
Esempio n. 26
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:
     }
 }
Esempio n. 27
0
function butler_uninstall()
{
    Preference::newInstance()->delete(array('s_section' => 'butler'));
}
Esempio n. 28
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');
     }
 }
Esempio n. 29
0
 public function setRules()
 {
     Preference::newInstance()->update(array('s_value' => serialize($this->rules)), array('s_name' => 'rewrite_rules'));
 }
Esempio n. 30
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;
        }
    }