Beispiel #1
1
/**
 * Get section
 *
 * @return string
 */
function osc_get_osclass_section()
{
    return Rewrite::newInstance()->get_section();
}
Beispiel #2
1
 function doModel()
 {
     switch ($this->action) {
         case 'login_post':
             //post execution for the login
             if (!osc_users_enabled()) {
                 osc_add_flash_error_message(_m('Users are not enabled'));
                 $this->redirectTo(osc_base_url());
             }
             osc_csrf_check();
             osc_run_hook('before_validating_login');
             // e-mail or/and password is/are empty or incorrect
             $wrongCredentials = false;
             $email = Params::getParam('email');
             $password = Params::getParam('password', false, false);
             if ($email == '') {
                 osc_add_flash_error_message(_m('Please provide an email address'));
                 $wrongCredentials = true;
             }
             if ($password == '') {
                 osc_add_flash_error_message(_m('Empty passwords are not allowed. Please provide a password'));
                 $wrongCredentials = true;
             }
             if ($wrongCredentials) {
                 $this->redirectTo(osc_user_login_url());
             }
             if (osc_validate_email($email)) {
                 $user = User::newInstance()->findByEmail($email);
             }
             if (empty($user)) {
                 $user = User::newInstance()->findByUsername($email);
             }
             if (empty($user)) {
                 osc_add_flash_error_message(_m("The user doesn't exist"));
                 $this->redirectTo(osc_user_login_url());
             }
             if (!osc_verify_password($password, isset($user['s_password']) ? $user['s_password'] : '')) {
                 osc_add_flash_error_message(_m('The password is incorrect'));
                 $this->redirectTo(osc_user_login_url());
                 // @TODO if valid user, send email parameter back to the login form
             } else {
                 if (@$user['s_password'] != '') {
                     if (preg_match('|\\$2y\\$([0-9]{2})\\$|', $user['s_password'], $cost)) {
                         if ($cost[1] != BCRYPT_COST) {
                             User::newInstance()->update(array('s_password' => osc_hash_password($password)), array('pk_i_id' => $user['pk_i_id']));
                         }
                     } else {
                         User::newInstance()->update(array('s_password' => osc_hash_password($password)), array('pk_i_id' => $user['pk_i_id']));
                     }
                 }
             }
             // e-mail or/and IP is/are banned
             $banned = osc_is_banned($email);
             // int 0: not banned or unknown, 1: email is banned, 2: IP is banned, 3: both email & IP are banned
             if ($banned & 1) {
                 osc_add_flash_error_message(_m('Your current email is not allowed'));
             }
             if ($banned & 2) {
                 osc_add_flash_error_message(_m('Your current IP is not allowed'));
             }
             if ($banned !== 0) {
                 $this->redirectTo(osc_user_login_url());
             }
             osc_run_hook('before_login');
             $url_redirect = osc_get_http_referer();
             $page_redirect = '';
             if (osc_rewrite_enabled()) {
                 if ($url_redirect != '') {
                     $request_uri = urldecode(preg_replace('@^' . osc_base_url() . '@', "", $url_redirect));
                     $tmp_ar = explode("?", $request_uri);
                     $request_uri = $tmp_ar[0];
                     $rules = Rewrite::newInstance()->listRules();
                     foreach ($rules as $match => $uri) {
                         if (preg_match('#' . $match . '#', $request_uri, $m)) {
                             $request_uri = preg_replace('#' . $match . '#', $uri, $request_uri);
                             if (preg_match('|([&?]{1})page=([^&]*)|', '&' . $request_uri . '&', $match)) {
                                 $page_redirect = $match[2];
                                 if ($page_redirect == '' || $page_redirect == 'login') {
                                     $url_redirect = osc_user_dashboard_url();
                                 }
                             }
                             break;
                         }
                     }
                 }
             }
             require_once LIB_PATH . 'osclass/UserActions.php';
             $uActions = new UserActions(false);
             $logged = $uActions->bootstrap_login($user['pk_i_id']);
             if ($logged == 0) {
                 osc_add_flash_error_message(_m("The user doesn't exist"));
             } else {
                 if ($logged == 1) {
                     if (time() - strtotime($user['dt_access_date']) > 1200) {
                         // EACH 20 MINUTES
                         osc_add_flash_error_message(sprintf(_m('The user has not been validated yet. Would you like to re-send your <a href="%s">activation?</a>'), osc_user_resend_activation_link($user['pk_i_id'], $user['s_email'])));
                     } else {
                         osc_add_flash_error_message(_m('The user has not been validated yet'));
                     }
                 } else {
                     if ($logged == 2) {
                         osc_add_flash_error_message(_m('The user has been suspended'));
                     } else {
                         if ($logged == 3) {
                             if (Params::getParam('remember') == 1) {
                                 //this include contains de osc_genRandomPassword function
                                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                                 $secret = osc_genRandomPassword();
                                 User::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $user['pk_i_id']));
                                 Cookie::newInstance()->set_expires(osc_time_cookie());
                                 Cookie::newInstance()->push('oc_userId', $user['pk_i_id']);
                                 Cookie::newInstance()->push('oc_userSecret', $secret);
                                 Cookie::newInstance()->set();
                             }
                             if ($url_redirect == '') {
                                 $url_redirect = osc_user_dashboard_url();
                             }
                             osc_run_hook("after_login", $user, $url_redirect);
                             $this->redirectTo(osc_apply_filter('correct_login_url_redirect', $url_redirect));
                         } else {
                             osc_add_flash_error_message(_m('This should never happen'));
                         }
                     }
                 }
             }
             if (!$user['b_enabled']) {
                 $this->redirectTo(osc_user_login_url());
             }
             $this->redirectTo(osc_user_login_url());
             break;
         case 'resend':
             $id = Params::getParam('id');
             $email = Params::getParam('email');
             $user = User::newInstance()->findByPrimaryKey($id);
             if ($id == '' || $email == '' || !isset($user) || $user['b_active'] == 1 || $email != $user['s_email']) {
                 osc_add_flash_error_message(_m('Incorrect link'));
                 $this->redirectTo(osc_user_login_url());
             }
             if (time() - strtotime($user['dt_access_date']) > 1200) {
                 // EACH 20 MINUTES
                 if (osc_notify_new_user()) {
                     osc_run_hook('hook_email_admin_new_user', $user);
                 }
                 if (osc_user_validation_enabled()) {
                     osc_run_hook('hook_email_user_validation', $user, $user);
                 }
                 User::newInstance()->update(array('dt_access_date' => date('Y-m-d H:i:s')), array('pk_i_id' => $user['pk_i_id']));
                 osc_add_flash_ok_message(_m('Validation email re-sent'));
             } else {
                 osc_add_flash_warning_message(_m('We have just sent you an email to validate your account, you will have to wait a few minutes to resend it again'));
             }
             $this->redirectTo(osc_user_login_url());
             break;
         case 'recover':
             //form to recover the password (in this case we have the form in /gui/)
             $this->doView('user-recover.php');
             break;
         case 'recover_post':
             //post execution to recover the password
             osc_csrf_check();
             require_once LIB_PATH . 'osclass/UserActions.php';
             // e-mail is incorrect
             if (!preg_match('|^[a-z0-9\\.\\_\\+\\-]+@[a-z0-9\\.\\-]+\\.[a-z]{2,3}$|i', Params::getParam('s_email'))) {
                 osc_add_flash_error_message(_m('Invalid email address'));
                 $this->redirectTo(osc_recover_user_password_url());
             }
             $userActions = new UserActions(false);
             $success = $userActions->recover_password();
             switch ($success) {
                 case 0:
                     // recover ok
                     osc_add_flash_ok_message(_m('We have sent you an email with the instructions to reset your password'));
                     $this->redirectTo(osc_base_url());
                     break;
                 case 1:
                     // e-mail does not exist
                     osc_add_flash_error_message(_m('We were not able to identify you given the information provided'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
                 case 2:
                     // recaptcha wrong
                     osc_add_flash_error_message(_m('The recaptcha code is wrong'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
             }
             break;
         case 'forgot':
             //form to recover the password (in this case we have the form in /gui/)
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user) {
                 $this->doView('user-forgot_password.php');
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'forgot_post':
             osc_csrf_check();
             if (Params::getParam('new_password', false, false) == '' || Params::getParam('new_password2', false, false) == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
             }
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user['b_enabled'] == 1) {
                 if (Params::getParam('new_password', false, false) == Params::getParam('new_password2', false, false)) {
                     User::newInstance()->update(array('s_pass_code' => osc_genRandomPassword(50), 's_pass_date' => date('Y-m-d H:i:s', 0), 's_pass_ip' => Params::getServerParam('REMOTE_ADDR'), 's_password' => osc_hash_password(Params::getParam('new_password', false, false))), array('pk_i_id' => $user['pk_i_id']));
                     osc_add_flash_ok_message(_m('The password has been changed'));
                     $this->redirectTo(osc_user_login_url());
                 } else {
                     osc_add_flash_error_message(_m("Error, the password don't match"));
                     $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
             }
             $this->redirectTo(osc_base_url());
             break;
         default:
             //login
             Session::newInstance()->_setReferer(osc_get_http_referer());
             if (osc_logged_user_id() != '') {
                 $this->redirectTo(osc_user_dashboard_url());
             }
             $this->doView('user-login.php');
     }
 }
 public function analyzeUrl()
 {
     // Check if URL is set in general
     if (is_null($this->url)) {
         throw new Exception("No request URL set!");
         return;
     }
     // Check for rewrtite rules
     $rewrite = new Rewrite($this->url);
     $rewrite->applyRules();
     if ($rewrite->getTargetUrl() != $this->url) {
         if (!$rewrite->transportQueryParameter()) {
             $_GET = array();
             $_POST = array();
         }
         if ($rewrite->isRedirect()) {
             $this->redirectToUrl($rewrite->getTargetUrl(), $_POST);
         }
         $this->setUrl($rewrite->getTargetUrl());
         $this->analyzeRequest(!$rewrite->isLastForward());
     }
     // Check access rights to requested content
     $access = new AccessOfficer("content", $this->content_id, $this->session->getUser(), $this->content_parents);
     if (!$access->check()) {
         // Access denied
         if (!$access->getDeniedContentID()) {
             // No content to be shown as 403 page set
             // TODO set up default 403 (and 404) templates
             throw new Exception("Access denied and no denied content defined!");
             return;
         }
         // Should parameters be transported through the redirects / rewrites
         if (!$access->transportQueryParameter()) {
             $_GET = array();
             $_POST = array();
         }
         // Show 403 error page or redirect if neccessary
         $newcontent = new Content($access->getDeniedContentID());
         if ($access->isRedirect() && $newcontent->getID() != $this->content_id) {
             // Redirect, but keep requested URL as origin parameter
             // TODO: keep origin request parameters as well!
             $this->redirectToUrl("/" . $newcontent->getUrl() . "?origin=" . $this->url, $_POST);
         }
         $this->setUrl($newcontent->getUrl());
         $this->analyzeRequest(!$access->isLastForward());
     }
     // TODO: HookPoints to manipulate this behaviour
 }
Beispiel #4
0
 private function addTableHeader()
 {
     $arg_date = '&sort=date';
     if (Params::getParam('sort') == 'date') {
         if (Params::getParam('direction') == 'desc') {
             $arg_date .= '&direction=asc';
         }
     }
     $arg_item = '&sort=attached_to';
     if (Params::getParam('sort') == 'attached_to') {
         if (Params::getParam('direction') == 'desc') {
             $arg_item .= '&direction=asc';
         }
     }
     Rewrite::newInstance()->init();
     $page = (int) Params::getParam('iPage');
     if ($page == 0) {
         $page = 1;
     }
     Params::setParam('iPage', $page);
     $url_base = preg_replace('|&direction=([^&]*)|', '', preg_replace('|&sort=([^&]*)|', '', osc_base_url() . Rewrite::newInstance()->get_raw_request_uri()));
     $this->addColumn('bulkactions', '<input id="check_all" type="checkbox" />');
     $this->addColumn('file', __('File'));
     $this->addColumn('action', __('Action'));
     $this->addColumn('attached_to', '<a href="' . osc_esc_html($url_base . $arg_item) . '">' . __('Attached to') . '</a>');
     $this->addColumn('date', '<a href="' . osc_esc_html($url_base . $arg_date) . '">' . __('Date') . '</a>');
     $dummy =& $this;
     osc_run_hook("admin_media_table", $dummy);
 }
Beispiel #5
0
 function do410()
 {
     Rewrite::newInstance()->set_location('error');
     header('HTTP/1.1 410 Gone');
     osc_current_web_theme_path('404.php');
     exit;
 }
 public static function _init()
 {
     date_default_timezone_set(Conf::param('timezone'));
     //设置默认时区
     //地址重写
     Rewrite::init();
 }
Beispiel #7
0
function item_success_item_validate()
{
    if (Params::getParam('page') == 'item' && Params::getParam('action') == 'activate') {
        $secret = Params::getParam('secret');
        $id = Params::getParam('id');
        $item = Item::newInstance()->listWhere("i.pk_i_id = '%s' AND ((i.s_secret = '%s') OR (i.fk_i_user_id = '%d'))", addslashes($id), addslashes($secret), addslashes(osc_logged_user_id()));
        // item doesn't exist
        if (count($item) == 0) {
            Rewrite::newInstance()->set_location('error');
            header('HTTP/1.1 404 Not Found');
            osc_current_web_theme_path('404.php');
            exit;
        }
        View::newInstance()->_exportVariableToView('item', $item[0]);
        if ($item[0]['b_active'] == 0) {
            // ACTIVETE ITEM
            $mItems = new ItemActions(false);
            $success = $mItems->activate($item[0]['pk_i_id'], $item[0]['s_secret']);
            if ($success) {
                osc_add_flash_ok_message(_m('The listing has been validated'));
                item_success_redirect(Item::newInstance()->findByPrimaryKey($item[0]['pk_i_id']));
                exit;
            } else {
                osc_add_flash_error_message(_m("The listing can't be validated"));
            }
        } else {
            osc_add_flash_warning_message(_m('The listing has already been validated'));
        }
        osc_redirect_to(osc_item_url());
    }
}
Beispiel #8
0
 public function __construct($lang = array())
 {
     $this->location = Rewrite::newInstance()->get_location();
     $this->section = Rewrite::newInstance()->get_section();
     $this->aLevel = array();
     $this->setTitles($lang);
 }
Beispiel #9
0
 public static function newInstance()
 {
     if (!self::$instance instanceof self) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Beispiel #10
0
function social_bookmarks_header()
{
    $location = Rewrite::newInstance()->get_location();
    $section = Rewrite::newInstance()->get_section();
    if ($location == 'item' && $section == '') {
        echo '
            <style type="text/css">
                .social-bookmarks ul { margin: 10px 0; list-style: none; }
                .social-bookmarks ul li { float: left; }
                .social-bookmarks .clear { clear:both; }
            </style>';
    }
}
Beispiel #11
0
        function doModel()
        {
            $user_menu = false;
            if(Params::existParam('route')) {
                $routes = Rewrite::newInstance()->getRoutes();
                $rid = Params::getParam('route');
                $file = '../';
                if(isset($routes[$rid]) && isset($routes[$rid]['file'])) {
                    $file = $routes[$rid]['file'];
                    $user_menu = $routes[$rid]['user_menu'];
                }
            } else {
                // DEPRECATED: Disclosed path in URL is deprecated, use routes instead
                // This will be REMOVED in 3.4
                $file = Params::getParam('file');
            }

            // valid file?
            if( strpos($file, '../') !== false || strpos($file, '..\\') !==false || stripos($file, '/admin/') !== false ) { //If the file is inside an "admin" folder, it should NOT be opened in frontend
                $this->do404();
                return;
            }

            // check if the file exists
            if( !file_exists(osc_plugins_path() . $file) ) {
                $this->do404();
                return;
            }

            osc_run_hook('custom_controller');

            $this->_exportVariableToView('file', $file);
            if($user_menu) {
                if(osc_is_web_user_logged_in()) {
                    Params::setParam('in_user_menu', true);
                    $this->doView('user-custom.php');
                } else {
                    $this->redirectTo(osc_user_login_url());
                }
            } else {
                $this->doView('custom.php');
            }
        }
function pop_redirect_404($header_text = '')
{
    if ($header_text != '') {
        View::newInstance()->_exportVariableToView('pop_404_header_text', $header_text);
    }
    Rewrite::newInstance()->set_location('error');
    header('HTTP/1.1 404 Not Found');
    osc_current_web_theme_path('404.php');
    exit;
}
<?php

define('WWW_ROOT', __DIR__);
require __DIR__ . '/../log/Log.class.php';
require __DIR__ . '/Rewrite.class.php';
Log::getLogger(array('level' => Log::ALL));
class Render implements RewriteHandle
{
    public function process($file)
    {
        echo file_get_contents($file);
    }
}
$rewrite = new Rewrite(__DIR__ . '/test');
$rewrite->addConfigFile('home.conf');
$rewrite->addConfigFile('common.conf');
$rewrite->addRewriteHandle('tpl', new Render());
$rewrite->dispatch('/home/test');
Beispiel #14
0
 *       This program is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License
 *     as published by the Free Software Foundation, either version 3 of
 *            the License, or (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful, but
 *         WITHOUT ANY WARRANTY; without even the implied warranty of
 *        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *             GNU Affero General Public License for more details.
 *
 *      You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
require_once 'oc-load.php';
//create object
$rewrite = Rewrite::newInstance();
$rewrite->clearRules();
/*****************************
 ********* Add rules *********
 *****************************/
// Contact rules
$rewrite->addRule('^contact/?$', 'index.php?page=contact');
// Feed rules
$rewrite->addRule('^feed$', 'index.php?page=search&sFeed=rss');
$rewrite->addRule('^feed/(.+)$', 'index.php?page=search&sFeed=$1');
// Language rules
$rewrite->addRule('^language/(.*?)/?$', 'index.php?page=language&locale=$1');
// Search rules
$rewrite->addRule('^search/(.*)$', 'index.php?page=search&sPattern=$1');
$rewrite->addRule('^s/(.*)$', 'index.php?page=search&sPattern=$1');
// Item rules
Beispiel #15
0
 function do404()
 {
     Rewrite::newInstance()->set_location('error');
     header('HTTP/1.1 404 Not Found');
     osc_current_web_theme_path('404.php');
 }
function allSeo_title_filter($text)
{
    $location = Rewrite::newInstance()->get_location();
    $section = Rewrite::newInstance()->get_section();
    switch ($location) {
        // Listing page and page related to listings
        case 'item':
            switch ($section) {
                case 'item_add':
                    $text = __('Publish a listing', 'all_in_one');
                    break;
                case 'item_edit':
                    $text = __('Edit your listing', 'all_in_one');
                    break;
                case 'send_friend':
                    $text = __('Send to a friend', 'all_in_one') . Delimiter() . osc_item_title();
                    break;
                case 'contact':
                    $text = __('Contact seller', 'all_in_one') . Delimiter() . osc_item_title();
                    break;
                default:
                    $text = SeoGenerateTitleListing();
                    break;
            }
            break;
            // Static page
        // Static page
        case 'page':
            if (GetPageTitle() == '') {
                $text = osc_static_page_title();
            } else {
                $text = GetPageTitle();
            }
            break;
            // Error page
        // Error page
        case 'error':
            $text = __('Page not found', 'all_in_one');
            break;
            // Search & Category page
        // Search & Category page
        case 'search':
            $region = osc_search_region();
            $city = osc_search_city();
            $pattern = osc_search_pattern();
            $category = osc_search_category_id();
            $s_page = '';
            $i_page = Params::getParam('iPage');
            if ($i_page != '' && $i_page > 1) {
                $s_page = Delimiter() . __('page', 'all_in_one') . ' ' . $i_page;
            }
            $result = SeoGenerateTitleCategory();
            if ($result == '') {
                $result = __('Search result', 'all_in_one');
            }
            $text = $result . $s_page;
            break;
            // Login page
        // Login page
        case 'login':
            switch ($section) {
                case 'recover':
                    $text = __('Recover your password', 'all_in_one');
                default:
                    $text = __('Login into your account', 'all_in_one');
            }
            break;
            // Registration page
        // Registration page
        case 'register':
            $text = __('Create a new account', 'all_in_one');
            break;
            // User page and pages related to user
        // User page and pages related to user
        case 'user':
            switch ($section) {
                case 'dashboard':
                    $text = __('Dashboard', 'all_in_one');
                    break;
                case 'items':
                    $text = __('Manage my listings', 'all_in_one');
                    break;
                case 'alerts':
                    $text = __('Manage my alerts', 'all_in_one');
                    break;
                case 'profile':
                    $text = __('Update my profile', 'all_in_one');
                    break;
                case 'pub_profile':
                    $text = __('Public profile of', 'all_in_one') . ' ' . ucfirst(osc_user_name());
                    break;
                case 'change_email':
                    $text = __('Change my email', 'all_in_one');
                    break;
                case 'change_password':
                    $text = __('Change my password', 'all_in_one');
                    break;
                case 'forgot':
                    $text = __('Recover my password', 'all_in_one');
                    break;
            }
            break;
            // Contact page
        // Contact page
        case 'contact':
            $text = __('Contact', 'all_in_one');
            break;
        default:
            $text = osc_page_title();
            break;
    }
    // Now add page title to first or last position for other pages
    if (!osc_is_home_page() and !osc_is_ad_page() and !osc_is_search_page()) {
        $title = osc_get_preference('allSeo_other_page_title', 'plugin-all_in_one') != '' ? osc_get_preference('allSeo_other_page_title', 'plugin-all_in_one') : osc_page_title();
        if (osc_get_preference('allSeo_title_first', 'plugin-all_in_one') == 1) {
            $text = $title . Delimiter() . $text;
        } else {
            $text .= Delimiter() . $title;
        }
    }
    return $text;
}
Beispiel #17
0
function meta_title()
{
    $location = Rewrite::newInstance()->get_location();
    $section = Rewrite::newInstance()->get_section();
    $text = '';
    switch ($location) {
        case 'item':
            switch ($section) {
                case 'item_add':
                    $text = __('Publish a listing');
                    break;
                case 'item_edit':
                    $text = __('Edit your listing');
                    break;
                case 'send_friend':
                    $text = __('Send to a friend') . ' - ' . osc_item_title();
                    break;
                case 'contact':
                    $text = __('Contact seller') . ' - ' . osc_item_title();
                    break;
                default:
                    $text = osc_item_title() . ' ' . osc_item_city();
                    break;
            }
            break;
        case 'page':
            $text = osc_static_page_title();
            break;
        case 'error':
            $text = __('Error');
            break;
        case 'search':
            $region = osc_search_region();
            $city = osc_search_city();
            $pattern = osc_search_pattern();
            $category = osc_search_category_id();
            $s_page = '';
            $i_page = Params::getParam('iPage');
            if ($i_page != '' && $i_page > 1) {
                $s_page = ' - ' . __('page') . ' ' . $i_page;
            }
            $b_show_all = $region == '' && $city == '' && $pattern == '' && empty($category);
            $b_category = !empty($category);
            $b_pattern = $pattern != '';
            $b_city = $city != '';
            $b_region = $region != '';
            if ($b_show_all) {
                $text = __('Show all listings') . ' - ' . $s_page . osc_page_title();
            }
            $result = '';
            if ($b_pattern) {
                $result .= $pattern . ' &raquo; ';
            }
            if ($b_category && is_array($category) && count($category) > 0) {
                $cat = Category::newInstance()->findByPrimaryKey($category[0]);
                if ($cat) {
                    $result .= $cat['s_name'] . ' ';
                }
            }
            if ($b_city) {
                $result .= $city . ' &raquo; ';
            } else {
                if ($b_region) {
                    $result .= $region . ' &raquo; ';
                }
            }
            $result = preg_replace('|\\s?&raquo;\\s$|', '', $result);
            if ($result == '') {
                $result = __('Search results');
            }
            $text = '';
            if (osc_get_preference('seo_title_keyword') != '') {
                $text .= osc_get_preference('seo_title_keyword') . ' ';
            }
            $text .= $result . $s_page;
            break;
        case 'login':
            switch ($section) {
                case 'recover':
                    $text = __('Recover your password');
                default:
                    $text = __('Login');
            }
            break;
        case 'register':
            $text = __('Create a new account');
            break;
        case 'user':
            switch ($section) {
                case 'dashboard':
                    $text = __('Dashboard');
                    break;
                case 'items':
                    $text = __('Manage my listings');
                    break;
                case 'alerts':
                    $text = __('Manage my alerts');
                    break;
                case 'profile':
                    $text = __('Update my profile');
                    break;
                case 'pub_profile':
                    $text = __('Public profile') . ' - ' . osc_user_name();
                    break;
                case 'change_email':
                    $text = __('Change my email');
                    break;
                case 'change_username':
                    $text = __('Change my username');
                    break;
                case 'change_password':
                    $text = __('Change my password');
                    break;
                case 'forgot':
                    $text = __('Recover my password');
                    break;
            }
            break;
        case 'contact':
            $text = __('Contact');
            break;
        default:
            $text = osc_page_title();
            break;
    }
    if (!osc_is_home_page()) {
        if ($text != '') {
            $text .= ' - ' . osc_page_title();
        } else {
            $text = osc_page_title();
        }
    }
    return osc_apply_filter('meta_title_filter', $text);
}
Beispiel #18
0
 /**
  * Generate a download link for an exisiting file in the cache.
  *
  * @param  string $strCachedName The name of the file in the cache
  * @param  string $strFilename File name
  * @return string The generated download link
  */
 public static function generateDownloadLinkForExisting($strCachedName, $strFilename, $strDownloadUrl = null)
 {
     // Save in session
     $_SESSION["documents"][$strCachedName] = $strFilename;
     if (is_null($strDownloadUrl)) {
         $objRewrite = Rewrite::getInstance();
         $strDownloadUrl = $objRewrite->getUrl(SECTION_DOCUMENT, CMD_DOWNLOAD, null, null, SUB_SECTION_EMPTY, array("t" => $strCachedName));
     } else {
         $strDownloadUrl .= "/t/" . Rewrite::encode($strCachedName);
     }
     $strReturn = Request::getRootURI() . $strDownloadUrl;
     return $strReturn;
 }
Beispiel #19
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->findByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->findByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             foreach ($cities as $k => $city) {
                 $cities[$k]['label'] = $city['label'] . " (" . $city['region'] . ")";
             }
             echo json_encode($cities);
             break;
         case 'location_countries':
             // This is the autocomplete AJAX
             $countries = Country::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($countries);
             break;
         case 'location_regions':
             // This is the autocomplete AJAX
             $regions = Region::newInstance()->ajax(Params::getParam("term"), Params::getParam("country"));
             echo json_encode($regions);
             break;
         case 'location_cities':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"), Params::getParam("region"));
             echo json_encode($cities);
             break;
         case 'delete_image':
             // Delete images via AJAX
             $ajax_photo = Params::getParam('ajax_photo');
             $id = Params::getParam('id');
             $item = Params::getParam('item');
             $code = Params::getParam('code');
             $secret = Params::getParam('secret');
             $json = array();
             if ($ajax_photo != '') {
                 $files = Session::newInstance()->_get('ajax_files');
                 $success = false;
                 foreach ($files as $uuid => $file) {
                     if ($file == $ajax_photo) {
                         $filename = $files[$uuid];
                         unset($files[$uuid]);
                         Session::newInstance()->_set('ajax_files', $files);
                         $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename);
                         break;
                     }
                 }
                 echo json_encode(array('success' => $success, 'msg' => $success ? _m('The selected photo has been successfully deleted') : _m("The selected photo couldn't be deleted")));
                 return false;
             }
             if (Session::newInstance()->_get('userId') != '') {
                 $userId = Session::newInstance()->_get('userId');
                 $user = User::newInstance()->findByPrimaryKey($userId);
             } else {
                 $userId = null;
                 $user = null;
             }
             // Check for required fields
             if (!(is_numeric($id) && is_numeric($item) && preg_match('/^([a-z0-9]+)$/i', $code))) {
                 $json['success'] = false;
                 $json['msg'] = _m("The selected photo couldn't be deleted, the url doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             $aItem = Item::newInstance()->findByPrimaryKey($item);
             // Check if the item exists
             if (count($aItem) == 0) {
                 $json['success'] = false;
                 $json['msg'] = _m("The listing doesn't exist");
                 echo json_encode($json);
                 return false;
             }
             if (!osc_is_admin_user_logged_in()) {
                 // Check if the item belong to the user
                 if ($userId != null && $userId != $aItem['fk_i_user_id']) {
                     $json['success'] = false;
                     $json['msg'] = _m("The listing doesn't belong to you");
                     echo json_encode($json);
                     return false;
                 }
                 // Check if the secret passphrase match with the item
                 if ($userId == null && $aItem['fk_i_user_id'] == null && $secret != $aItem['s_secret']) {
                     $json['success'] = false;
                     $json['msg'] = _m("The listing doesn't belong to you");
                     echo json_encode($json);
                     return false;
                 }
             }
             // Does id & code combination exist?
             $result = ItemResource::newInstance()->existResource($id, $code);
             if ($result > 0) {
                 $resource = ItemResource::newInstance()->findByPrimaryKey($id);
                 if ($resource['fk_i_item_id'] == $item) {
                     // Delete: file, db table entry
                     if (defined(OC_ADMIN)) {
                         osc_deleteResource($id, true);
                         Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'admin', osc_logged_admin_id());
                     } else {
                         osc_deleteResource($id, false);
                         Log::newInstance()->insertLog('ajax', 'deleteimage', $id, $id, 'user', osc_logged_user_id());
                     }
                     ItemResource::newInstance()->delete(array('pk_i_id' => $id, 'fk_i_item_id' => $item, 's_name' => $code));
                     $json['msg'] = _m('The selected photo has been successfully deleted');
                     $json['success'] = 'true';
                 } else {
                     $json['msg'] = _m("The selected photo does not belong to you");
                     $json['success'] = 'false';
                 }
             } else {
                 $json['msg'] = _m("The selected photo couldn't be deleted");
                 $json['success'] = 'false';
             }
             echo json_encode($json);
             return true;
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $encoded_alert = Params::getParam("alert");
             $alert = osc_decrypt_alert(base64_decode($encoded_alert));
             // check alert integrity / signature
             $stringToSign = osc_get_alert_public_key() . $encoded_alert;
             $signature = hex2b64(hmacsha1(osc_get_alert_private_key(), $stringToSign));
             $server_signature = Session::newInstance()->_get('alert_signature');
             if ($server_signature != $signature) {
                 echo '-2';
                 return false;
             }
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if (osc_is_web_user_logged_in()) {
                 $userid = osc_logged_user_id();
                 $user = User::newInstance()->findByPrimaryKey($userid);
                 $email = $user['s_email'];
             }
             if ($alert != '' && $email != '') {
                 if (osc_validate_email($email)) {
                     $secret = osc_genRandomPassword();
                     if ($alertID = Alerts::newInstance()->createAlert($userid, $email, $alert, $secret)) {
                         if ((int) $userid > 0) {
                             $user = User::newInstance()->findByPrimaryKey($userid);
                             if ($user['b_active'] == 1 && $user['b_enabled'] == 1) {
                                 Alerts::newInstance()->activate($alertID);
                                 echo '1';
                                 return true;
                             } else {
                                 echo '-1';
                                 return false;
                             }
                         } else {
                             $aAlert = Alerts::newInstance()->findByPrimaryKey($alertID);
                             osc_run_hook('hook_email_alert_validation', $aAlert, $email, $secret);
                         }
                         echo "1";
                     } else {
                         echo "0";
                     }
                     return true;
                 } else {
                     echo '-1';
                     return false;
                 }
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             // run hooks
             $hook = Params::getParam('hook');
             if ($hook == '') {
                 echo json_encode(array('error' => 'hook parameter not defined'));
                 break;
             }
             switch ($hook) {
                 case 'item_form':
                     osc_run_hook('item_form', Params::getParam('catId'));
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     osc_run_hook('ajax_' . $hook);
                     break;
             }
             break;
         case 'custom':
             // Execute via AJAX custom file
             if (Params::existParam('route')) {
                 $routes = Rewrite::newInstance()->getRoutes();
                 $rid = Params::getParam('route');
                 $file = '../';
                 if (isset($routes[$rid]) && isset($routes[$rid]['file'])) {
                     $file = $routes[$rid]['file'];
                 }
             } else {
                 // DEPRECATED: Disclosed path in URL is deprecated, use routes instead
                 // This will be REMOVED in 3.4
                 $file = Params::getParam('ajaxfile');
             }
             if ($file == '') {
                 echo json_encode(array('error' => 'no action defined'));
                 break;
             }
             // valid file?
             if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || stripos($file, '/admin/') !== false) {
                 //If the file is inside an "admin" folder, it should NOT be opened in frontend
                 echo json_encode(array('error' => 'no valid ajaxFile'));
                 break;
             }
             if (!file_exists(osc_plugins_path() . $file)) {
                 echo json_encode(array('error' => "ajaxFile doesn't exist"));
                 break;
             }
             require_once osc_plugins_path() . $file;
             break;
         case 'check_username_availability':
             $username = osc_sanitize_username(Params::getParam('s_username'));
             if (!osc_is_username_blacklisted($username)) {
                 $user = User::newInstance()->findByUsername($username);
                 if (isset($user['s_username'])) {
                     echo json_encode(array('exists' => 1, 's_username' => $username));
                 } else {
                     echo json_encode(array('exists' => 0, 's_username' => $username));
                 }
             } else {
                 echo json_encode(array('exists' => 1, 's_username' => $username));
             }
             break;
         case 'ajax_upload':
             // Include the uploader class
             require_once LIB_PATH . "AjaxUploader.php";
             $uploader = new AjaxUploader();
             $original = pathinfo($uploader->getOriginalName());
             $filename = uniqid("qqfile_") . "." . $original['extension'];
             $result = $uploader->handleUpload(osc_content_path() . 'uploads/temp/' . $filename);
             $result['uploadName'] = $filename;
             echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
             break;
         case 'ajax_validate':
             $id = Params::getParam('id');
             if (!is_numeric($id)) {
                 echo json_encode(array('success' => false));
                 die;
             }
             $secret = Params::getParam('secret');
             $item = Item::newInstance()->findByPrimaryKey($id);
             if ($item['s_secret'] != $secret) {
                 echo json_encode(array('success' => false));
                 die;
             }
             $nResources = ItemResource::newInstance()->countResources($id);
             $result = array('success' => $nResources < osc_max_images_per_item(), 'count' => $nResources);
             echo json_encode($result);
             break;
         case 'delete_ajax_upload':
             $files = Session::newInstance()->_get('ajax_files');
             $success = false;
             $filename = '';
             if (isset($files[Params::getParam('qquuid')]) && $files[Params::getParam('qquuid')] != '') {
                 $filename = $files[Params::getParam('qquuid')];
                 unset($files[Params::getParam('qquuid')]);
                 Session::newInstance()->_set('ajax_files', $files);
                 $success = @unlink(osc_content_path() . 'uploads/temp/' . $filename);
             }
             echo json_encode(array('success' => $success, 'uploadName' => $filename));
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Beispiel #20
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;
        }
    }
Beispiel #21
0
require_once LIB_PATH . 'osclass/frm/Category.form.class.php';
require_once LIB_PATH . 'osclass/frm/Item.form.class.php';
require_once LIB_PATH . 'osclass/frm/Contact.form.class.php';
require_once LIB_PATH . 'osclass/frm/Comment.form.class.php';
require_once LIB_PATH . 'osclass/frm/User.form.class.php';
require_once LIB_PATH . 'osclass/frm/Language.form.class.php';
require_once LIB_PATH . 'osclass/frm/SendFriend.form.class.php';
require_once LIB_PATH . 'osclass/frm/Alert.form.class.php';
require_once LIB_PATH . 'osclass/frm/Field.form.class.php';
require_once LIB_PATH . 'osclass/frm/Admin.form.class.php';
require_once LIB_PATH . 'osclass/functions.php';
define('__OSC_LOADED__', true);
Plugins::init();
// init Rewrite class only iif it's the frontend
if (!OC_ADMIN) {
    Rewrite::newInstance()->init();
}
// Moved from BaseModel, since we need some session magic on index.php ;)
Session::newInstance()->session_start();
if (osc_timezone() != '') {
    date_default_timezone_set(osc_timezone());
}
function osc_show_maintenance()
{
    if (defined('__OSC_MAINTENANCE__')) {
        ?>
        <div id="maintenance" name="maintenance">
             <?php 
        _e("The website is currently under maintenance mode");
        ?>
        </div>
Beispiel #22
0
 public function init()
 {
     if (Params::existServerParam('REQUEST_URI')) {
         if (preg_match('|[\\?&]{1}http_referer=(.*)$|', urldecode(Params::getServerParam('REQUEST_URI', false, false)), $ref_match)) {
             $this->http_referer = $ref_match[1];
             $_SERVER['REQUEST_URI'] = preg_replace('|[\\?&]{1}http_referer=(.*)$|', "", urldecode(Params::getServerParam('REQUEST_URI', false, false)));
         }
         $request_uri = preg_replace('@^' . REL_WEB_URL . '@', "", urldecode(Params::getServerParam('REQUEST_URI', false, false)));
         $this->raw_request_uri = $request_uri;
         $route_used = false;
         foreach ($this->routes as $id => $route) {
             // UNCOMMENT TO DEBUG
             //echo 'Request URI: '.$request_uri." # Match : ".$route['regexp']." # URI to go : ".$route['url']." <br />";
             if (preg_match('#^' . $route['regexp'] . '#', $request_uri, $m)) {
                 if (!preg_match_all('#\\{([^\\}]+)\\}#', $route['url'], $args)) {
                     $args[1] = array();
                 }
                 $l = count($m);
                 for ($p = 1; $p < $l; $p++) {
                     if (isset($args[1][$p - 1])) {
                         Params::setParam($args[1][$p - 1], $m[$p]);
                     } else {
                         Params::setParam('route_param_' . $p, $m[$p]);
                     }
                 }
                 Params::setParam('page', 'custom');
                 Params::setParam('route', $id);
                 $route_used = true;
                 $this->location = $route['location'];
                 $this->section = $route['section'];
                 $this->title = $route['title'];
                 break;
             }
         }
         if (!$route_used) {
             if (osc_rewrite_enabled()) {
                 $tmp_ar = explode("?", $request_uri);
                 $request_uri = $tmp_ar[0];
                 // if try to access directly to a php file
                 if (preg_match('#^(.+?)\\.php(.*)$#', $request_uri)) {
                     $file = explode("?", $request_uri);
                     if (!file_exists(ABS_PATH . $file[0])) {
                         Rewrite::newInstance()->set_location('error');
                         header('HTTP/1.1 404 Not Found');
                         osc_current_web_theme_path('404.php');
                         exit;
                     }
                 }
                 foreach ($this->rules as $match => $uri) {
                     // UNCOMMENT TO DEBUG
                     // echo 'Request URI: '.$request_uri." # Match : ".$match." # URI to go : ".$uri." <br />";
                     if (preg_match('#^' . $match . '#', $request_uri, $m)) {
                         $request_uri = preg_replace('#' . $match . '#', $uri, $request_uri);
                         break;
                     }
                 }
             }
             $this->extractParams($request_uri);
             $this->request_uri = $request_uri;
             if (Params::getParam('page') != '') {
                 $this->location = Params::getParam('page');
             }
             if (Params::getParam('action') != '') {
                 $this->section = Params::getParam('action');
             }
         }
     }
 }
Beispiel #23
0
function osclasswizards_redirect_user_dashboard()
{
    if (Rewrite::newInstance()->get_location() === 'user' && Rewrite::newInstance()->get_section() === 'dashboard') {
        header('Location: ' . osc_user_list_items_url());
        exit;
    }
}
Beispiel #24
0
function breadcrumbs($separator = '/')
{
    $text = '';
    $location = Rewrite::newInstance()->get_location();
    $section = Rewrite::newInstance()->get_section();
    $separator = ' ' . trim($separator) . ' ';
    $page_title = '<a href="' . osc_base_url() . '"><span class="bc_root">' . osc_page_title() . '</span></a>';
    switch ($location) {
        case 'item':
            switch ($section) {
                case 'item_add':
                    break;
                default:
                    $aCategories = Category::newInstance()->toRootTree((string) osc_item_category_id());
                    $category = '';
                    if (count($aCategories) == 0) {
                        break;
                    }
                    $deep = 1;
                    foreach ($aCategories as $aCategory) {
                        $list[] = '<a href="' . breadcrumbs_category_url($aCategory['pk_i_id']) . '"><span class="bc_level_' . $deep . '">' . $aCategory['s_name'] . '</span></a>';
                        $deep++;
                    }
                    $category = implode($separator, $list) . $separator;
                    $category = preg_replace('|' . trim($separator) . '\\s*$|', '', $category);
                    break;
            }
            switch ($section) {
                case 'item_add':
                    $text = $page_title . $separator . '<span class="bc_last">' . __('Publish an item', 'breadcrumbs');
                    break;
                case 'item_edit':
                    $text = $page_title . $separator . $category . $separator . '<a href="' . osc_item_url() . '"><span class="bc_item">' . osc_item_title() . '</span></a>' . $separator . '<span class="bc_last">' . __('Edit your item', 'breadcrumbs') . '</span>';
                    break;
                case 'send_friend':
                    $text = $page_title . $separator . $category . $separator . '<a href="' . osc_item_url() . '"><span class="bc_item">' . osc_item_title() . '</span></a>' . $separator . '<span class="bc_last">' . __('Send to a friend', 'breadcrumbs') . '</span>';
                    break;
                case 'contact':
                    $text = $page_title . $separator . $category . $separator . '<a href="' . osc_item_url() . '"><span class="bc_item">' . osc_item_title() . '</span></a>' . $separator . '<span class="bc_last">' . __('Contact seller', 'breadcrumbs') . '</span>';
                    break;
                default:
                    $text = $page_title . $separator . $category . $separator . '<span class="bc_last">' . osc_item_title() . '</span>';
                    break;
            }
            break;
        case 'page':
            $text = $page_title . $separator . '<span class="bc_last">' . osc_static_page_title() . '</span>';
            break;
        case 'search':
            $region = osc_search_region();
            $city = osc_search_city();
            $pattern = osc_search_pattern();
            $category = osc_search_category_id();
            $category = count($category) == 1 ? $category[0] : '';
            $b_show_all = $pattern == '' && $category == '' && $region == '' && $city == '';
            $b_category = $category != '';
            $b_pattern = $pattern != '';
            $b_region = $region != '';
            $b_city = $city != '';
            $b_location = $b_region || $b_city;
            if ($b_show_all) {
                $text = $page_title . $separator . '<span class="bc_last">' . __('Search', 'breadcrumbs') . '</span>';
                break;
            }
            // init
            $result = $page_title . $separator;
            if ($b_category) {
                $list = array();
                $aCategories = Category::newInstance()->toRootTree($category);
                if (count($aCategories) > 0) {
                    $deep = 1;
                    foreach ($aCategories as $single) {
                        $list[] = '<a href="' . breadcrumbs_category_url($single['pk_i_id']) . '"><span class="bc_level_' . $deep . '">' . $single['s_name'] . '</span></a>';
                        $deep++;
                    }
                    // remove last link
                    if (!$b_pattern && !$b_location) {
                        $list[count($list) - 1] = preg_replace('|<a href.*?>(.*?)</a>|', '$01', $list[count($list) - 1]);
                    }
                    $result .= implode($separator, $list) . $separator;
                }
            }
            if ($b_location) {
                $list = array();
                $params = array();
                if ($b_category) {
                    $params['sCategory'] = $category;
                }
                if ($b_city) {
                    $aCity = City::newInstance()->findByName($city);
                    if (count($aCity) == 0) {
                        $params['sCity'] = $city;
                        $list[] = '<a href="' . osc_search_url($params) . '"><span class="bc_city">' . $city . '</span></a>';
                    } else {
                        $aRegion = Region::newInstance()->findByPrimaryKey($aCity['fk_i_region_id']);
                        $params['sRegion'] = $aRegion['s_name'];
                        $list[] = '<a href="' . osc_search_url($params) . '"><span class="bc_region">' . $aRegion['s_name'] . '</span></a>';
                        $params['sCity'] = $aCity['s_name'];
                        $list[] = '<a href="' . osc_search_url($params) . '"><span class="bc_city">' . $aCity['s_name'] . '</span></a>';
                    }
                    if (!$b_pattern) {
                        $list[count($list) - 1] = preg_replace('|<a href.*?>(.*?)</a>|', '$01', $list[count($list) - 1]);
                    }
                    $result .= implode($separator, $list) . $separator;
                } else {
                    if ($b_region) {
                        $params['sRegion'] = $region;
                        $list[] = '<a href="' . osc_search_url($params) . '"><span class="bc_region">' . $region . '</span></a>';
                        if (!$b_pattern) {
                            $list[count($list) - 1] = preg_replace('|<a href.*?>(.*?)</a>|', '$01', $list[count($list) - 1]);
                        }
                        $result .= implode($separator, $list) . $separator;
                    }
                }
            }
            if ($b_pattern) {
                $result .= '<span class="bc_last">' . __('Search Results', 'breadcrumbs') . ': ' . $pattern . '</span>' . $separator;
            }
            // remove last separator
            $result = preg_replace('|' . trim($separator) . '\\s*$|', '', $result);
            $text = $result;
            break;
        case 'login':
            switch ($section) {
                case 'recover':
                    $text = $page_title . $separator . '<span class="bc_last">' . __('Recover your password', 'breadcrumbs') . '</span>';
                default:
                    $text = $page_title . $separator . '<span class="bc_last">' . __('Login', 'breadcrumbs') . '</span>';
            }
            break;
        case 'register':
            $text = $page_title . $separator . '<span class="bc_last">' . __('Create a new account', 'breadcrumbs') . '</span>';
            break;
        case 'user':
            $user_dashboard = '<a href="' . osc_user_dashboard_url() . '"><span class="bc_user">' . __('My account', 'breadcrumbs') . '</span></a>';
            switch ($section) {
                case 'dashboard':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Dashboard', 'breadcrumbs') . '</span>';
                    break;
                case 'items':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Manage my items', 'breadcrumbs') . '</span>';
                    break;
                case 'alerts':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Manage my alerts', 'breadcrumbs') . '</span>';
                    break;
                case 'profile':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Update my profile', 'breadcrumbs') . '</span>';
                    break;
                case 'change_email':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Change my email', 'breadcrumbs') . '</span>';
                    break;
                case 'change_password':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Change my password', 'breadcrumbs') . '</span>';
                    break;
                case 'forgot':
                    $text = $page_title . $separator . $user_dashboard . $separator . '<span class="bc_last">' . __('Recover my password', 'breadcrumbs') . '</span>';
                    break;
            }
            break;
        case 'contact':
            $text = $page_title . $separator . '<span class="bc_last">' . __('Contact', 'breadcrumbs') . '</span>';
            break;
        default:
            break;
    }
    echo $text;
    return true;
}
Beispiel #25
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add':
             $this->doView("appearance/add.php");
             break;
         case 'add_post':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             osc_csrf_check();
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_themes_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
                 @unlink($filePackage['tmp_name']);
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The theme folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     $msg = _m('The theme has been installed correctly');
                     osc_add_flash_ok_message($msg, 'admin');
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_error_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the theme');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'delete':
             if (defined('DEMO')) {
                 osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=appearance');
             }
             osc_csrf_check();
             $theme = Params::getParam('webtheme');
             if ($theme != '') {
                 if ($theme != osc_current_web_theme()) {
                     if (file_exists(osc_content_path() . "themes/" . $theme . "/functions.php")) {
                         include osc_content_path() . "themes/" . $theme . "/functions.php";
                     }
                     osc_run_hook("theme_delete_" . $theme);
                     if (osc_deleteDir(osc_content_path() . "themes/" . $theme . "/")) {
                         osc_add_flash_ok_message(_m("Theme removed successfully"), "admin");
                     } else {
                         osc_add_flash_error_message(_m("There was a problem removing the theme"), "admin");
                     }
                 } else {
                     osc_add_flash_error_message(_m("Current theme can not be deleted"), "admin");
                 }
             } else {
                 osc_add_flash_error_message(_m("No theme selected"), "admin");
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
             /* widgets */
         /* widgets */
         case 'widgets':
             $info = WebThemes::newInstance()->loadThemeInfo(osc_theme());
             $this->_exportVariableToView("info", $info);
             $this->doView('appearance/widgets.php');
             break;
         case 'add_widget':
             $this->doView('appearance/add_widget.php');
             break;
         case 'edit_widget':
             $id = Params::getParam('id');
             $widget = Widget::newInstance()->findByPrimaryKey($id);
             $this->_exportVariableToView("widget", $widget);
             $this->doView('appearance/add_widget.php');
             break;
         case 'delete_widget':
             osc_csrf_check();
             Widget::newInstance()->delete(array('pk_i_id' => Params::getParam('id')));
             osc_add_flash_ok_message(_m('Widget removed correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'edit_widget_post':
             osc_csrf_check();
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             $res = Widget::newInstance()->update(array('s_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)), array('pk_i_id' => Params::getParam('id')));
             if ($res) {
                 osc_add_flash_ok_message(_m('Widget updated correctly'), 'admin');
             } else {
                 osc_add_flash_error_message(_m('Widget cannot be updated correctly'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
         case 'add_widget_post':
             osc_csrf_check();
             if (!osc_validate_text(Params::getParam("description"))) {
                 osc_add_flash_error_message(_m('Description field is required'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             }
             Widget::newInstance()->insert(array('s_location' => Params::getParam('location'), 'e_kind' => 'html', 's_description' => Params::getParam('description'), 's_content' => Params::getParam('content', false, false)));
             osc_add_flash_ok_message(_m('Widget added correctly'), 'admin');
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance&action=widgets");
             break;
             /* /widget */
         /* /widget */
         case 'activate':
             osc_csrf_check();
             osc_set_preference('theme', Params::getParam('theme'));
             osc_add_flash_ok_message(_m('Theme activated correctly'), 'admin');
             osc_run_hook("theme_activate", Params::getParam('theme'));
             $this->redirectTo(osc_admin_base_url(true) . "?page=appearance");
             break;
         case 'render':
             if (Params::existParam('route')) {
                 $routes = Rewrite::newInstance()->getRoutes();
                 $rid = Params::getParam('route');
                 $file = '../';
                 if (isset($routes[$rid]) && isset($routes[$rid]['file'])) {
                     $file = $routes[$rid]['file'];
                 }
             } else {
                 // DEPRECATED: Disclosed path in URL is deprecated, use routes instead
                 // This will be REMOVED in 3.6
                 $file = Params::getParam('file');
                 // We pass the GET variables (in case we have somes)
                 if (preg_match('|(.+?)\\?(.*)|', $file, $match)) {
                     $file = $match[1];
                     if (preg_match_all('|&([^=]+)=([^&]*)|', urldecode('&' . $match[2] . '&'), $get_vars)) {
                         for ($var_k = 0; $var_k < count($get_vars[1]); $var_k++) {
                             Params::setParam($get_vars[1][$var_k], $get_vars[2][$var_k]);
                         }
                     }
                 } else {
                     $file = Params::getParam('file');
                 }
             }
             if (strpos($file, '../') !== false || strpos($file, '..\\') !== false || !file_exists(osc_base_path() . $file)) {
                 osc_add_flash_warning_message(__('Error loading theme custom file'), 'admin');
             }
             $this->_exportVariableToView('file', osc_base_path() . $file);
             $this->doView('appearance/view.php');
             break;
         default:
             if (Params::getParam('checkUpdated') != '') {
                 osc_admin_toolbar_update_themes(true);
             }
             $themes = WebThemes::newInstance()->getListThemes();
             //preparing variables for the view
             $this->_exportVariableToView("themes", $themes);
             $this->doView('appearance/index.php');
             break;
     }
 }
Beispiel #26
0
 function meta_description()
 {
     $location = Rewrite::newInstance()->get_location();
     $section = Rewrite::newInstance()->get_section();
     $text = '';
     switch ($location) {
         case 'item':
             switch ($section) {
                 case 'item_add':
                     $text = '';
                     break;
                 case 'item_edit':
                     $text = '';
                     break;
                 case 'send_friend':
                     $text = '';
                     break;
                 case 'contact':
                     $text = '';
                     break;
                 default:
                     $text = osc_item_category() . ', ' . osc_highlight(strip_tags(osc_item_description()), 140) . '..., ' . osc_item_category();
                     break;
             }
             break;
         case 'page':
             $text = osc_highlight(strip_tags(osc_static_page_text()), 140);
             break;
         case 'search':
             $result = '';
             if (osc_count_items() == 0) {
                 $text = '';
             }
             if (osc_has_items()) {
                 $result = osc_item_category() . ', ' . osc_highlight(strip_tags(osc_item_description()), 140) . '..., ' . osc_item_category();
             }
             osc_reset_items();
             $text = $result;
         case '':
             // home
             $result = '';
             if (osc_count_latest_items() == 0) {
                 $text = '';
             }
             if (osc_has_latest_items()) {
                 $result = osc_item_category() . ', ' . osc_highlight(strip_tags(osc_item_description()), 140) . '..., ' . osc_item_category();
             }
             osc_reset_items();
             $text = $result;
             break;
     }
     $text = str_replace('"', "'", $text);
     return $text;
 }
function twitter_breadcrumb($separator = '/')
{
    $breadcrumb = array();
    $text = '';
    $location = Rewrite::newInstance()->get_location();
    $section = Rewrite::newInstance()->get_section();
    $separator = '<span class="divider">' . trim($separator) . '</span>';
    $page_title = '<li><a href="' . osc_base_url() . '">' . osc_page_title() . '</a>' . $separator . '</li>';
    switch ($location) {
        case 'item':
            switch ($section) {
                case 'item_add':
                    break;
                default:
                    $aCategories = Category::newInstance()->toRootTree((string) osc_item_category_id());
                    $category = '';
                    if (count($aCategories) == 0) {
                        break;
                    }
                    foreach ($aCategories as $aCategory) {
                        $list[] = '<li><a href="' . osc_item_category_url($aCategory['pk_i_id']) . '">' . $aCategory['s_name'] . '</a>' . $separator . '</li>';
                    }
                    $category = implode('', $list);
                    break;
            }
            switch ($section) {
                case 'item_add':
                    $text = $page_title . '<li>' . __('Publish an item', 'twitter') . '</li>';
                    break;
                case 'item_edit':
                    $text = $page_title . '<li><a href="' . osc_item_url() . '">' . osc_item_title() . '</a>' . $separator . '</li><li>' . __('Edit your item', 'twitter') . '</li>';
                    break;
                case 'send_friend':
                    $text = $page_title . $category . '<li><a href="' . osc_item_url() . '">' . osc_item_title() . '</a>' . $separator . '</li><li>' . __('Send to a friend', 'twitter') . '</li>';
                    break;
                case 'contact':
                    $text = $page_title . $category . '<li><a href="' . osc_item_url() . '">' . osc_item_title() . '</a>' . $separator . '<li><li>' . __('Contact seller', 'twitter') . '</li>';
                    break;
                default:
                    $text = $page_title . $category . '<li>' . osc_item_title() . '</li>';
                    break;
            }
            break;
        case 'page':
            $text = $page_title . '<li>' . osc_static_page_title() . '</li>';
            break;
        case 'search':
            $region = Params::getParam('sRegion');
            $city = Params::getParam('sCity');
            $pattern = Params::getParam('sPattern');
            $category = osc_search_category_id();
            $category = count($category) == 1 ? $category[0] : '';
            $b_show_all = $pattern == '' && $category == '' && $region == '' && $city == '';
            $b_category = $category != '';
            $b_pattern = $pattern != '';
            $b_region = $region != '';
            $b_city = $city != '';
            $b_location = $b_region || $b_city;
            if ($b_show_all) {
                $text = $page_title . '<li>' . __('Search', 'twitter') . '</li>';
                break;
            }
            // init
            $result = $page_title;
            if ($b_category) {
                $list = array();
                $aCategories = Category::newInstance()->toRootTree($category);
                if (count($aCategories) > 0) {
                    $deep = 1;
                    foreach ($aCategories as $single) {
                        $list[] = '<li><a href="' . osc_item_category_url($single['pk_i_id']) . '">' . $single['s_name'] . '</a>' . $separator . '</li>';
                        $deep++;
                    }
                    // remove last link
                    if (!$b_pattern && !$b_location) {
                        $list[count($list) - 1] = preg_replace('|<li><a href.*?>(.*?)</a>.*?</li>|', '$01', $list[count($list) - 1]);
                    }
                    $result .= implode('', $list);
                }
            }
            if ($b_location) {
                $list = array();
                $params = array();
                if ($b_category) {
                    $params['sCategory'] = $category;
                }
                if ($b_city) {
                    $aCity = City::newInstance()->findByName($city);
                    if (count($aCity) == 0) {
                        $params['sCity'] = $city;
                        $list[] = '<li><a href="' . osc_search_url($params) . '">' . $city . '</a>' . $separator . '</li>';
                    } else {
                        $aRegion = Region::newInstance()->findByPrimaryKey($aCity['fk_i_region_id']);
                        $params['sRegion'] = $aRegion['s_name'];
                        $list[] = '<li><a href="' . osc_search_url($params) . '">' . $aRegion['s_name'] . '</a>' . $separator . '</li>';
                        $params['sCity'] = $aCity['s_name'];
                        $list[] = '<li><a href="' . osc_search_url($params) . '">' . $aCity['s_name'] . '</a>' . $separator . '</li>';
                    }
                    if (!$b_pattern) {
                        $list[count($list) - 1] = preg_replace('|<li><a href.*?>(.*?)</a>.*?</li>|', '$01', $list[count($list) - 1]);
                    }
                    $result .= implode('', $list);
                } else {
                    if ($b_region) {
                        $params['sRegion'] = $region;
                        $list[] = '<li><a href="' . osc_search_url($params) . '">' . $region . '</a>' . $separator . '</li>';
                        if (!$b_pattern) {
                            $list[count($list) - 1] = preg_replace('|<li><a href.*?>(.*?)</a>.*?</li>|', '$01', $list[count($list) - 1]);
                        }
                        $result .= implode('', $list);
                    }
                }
            }
            if ($b_pattern) {
                $result .= '<li>' . __('Search Results', 'twitter') . ': ' . $pattern . '</li>';
            }
            // remove last separator
            $result = preg_replace('|' . trim($separator) . '\\s*$|', '', $result);
            $text = $result;
            break;
        case 'login':
            switch ($section) {
                case 'recover':
                    $text = $page_title . '<li>' . __('Recover your password', 'twitter') . '</li>';
                    break;
                default:
                    $text = $page_title . '<li>' . __('Login', 'twitter') . '</li>';
            }
            break;
        case 'register':
            $text = $page_title . '<li>' . __('Create a new account', 'twitter') . '</li>';
            break;
        case 'contact':
            $text = $page_title . '<li>' . __('Contact', 'twitter') . '</li>';
            break;
        default:
            break;
    }
    return '<ul class="breadcrumb">' . $text . '</ul>';
}
Beispiel #28
0
 function doModel()
 {
     switch ($this->action) {
         case 'login_post':
             //post execution for the login
             if (!osc_users_enabled()) {
                 osc_add_flash_error_message(_m('Users are not enabled'));
                 $this->redirectTo(osc_base_url());
             }
             require_once LIB_PATH . 'osclass/UserActions.php';
             $user = User::newInstance()->findByEmail(Params::getParam('email'));
             $url_redirect = osc_user_dashboard_url();
             $page_redirect = '';
             if (osc_rewrite_enabled()) {
                 if (isset($_SERVER['HTTP_REFERER'])) {
                     $request_uri = urldecode(preg_replace('@^' . osc_base_url() . '@', "", $_SERVER['HTTP_REFERER']));
                     $tmp_ar = explode("?", $request_uri);
                     $request_uri = $tmp_ar[0];
                     $rules = Rewrite::newInstance()->listRules();
                     foreach ($rules as $match => $uri) {
                         if (preg_match('#' . $match . '#', $request_uri, $m)) {
                             $request_uri = preg_replace('#' . $match . '#', $uri, $request_uri);
                             if (preg_match('|([&?]{1})page=([^&]*)|', '&' . $request_uri . '&', $match)) {
                                 $page_redirect = $match[2];
                             }
                             break;
                         }
                     }
                 }
             } else {
                 if (preg_match('|[\\?&]page=([^&]+)|', $_SERVER['HTTP_REFERER'] . '&', $match)) {
                     $page_redirect = $match[1];
                 }
             }
             if (Params::getParam('http_referer') != '') {
                 Session::newInstance()->_setReferer(Params::getParam('http_referer'));
                 $url_redirect = Params::getParam('http_referer');
             } else {
                 if (Session::newInstance()->_getReferer() != '') {
                     Session::newInstance()->_setReferer(Session::newInstance()->_getReferer());
                     $url_redirect = Session::newInstance()->_getReferer();
                 } else {
                     if ($page_redirect != '' && $page_redirect != 'login') {
                         Session::newInstance()->_setReferer($_SERVER['HTTP_REFERER']);
                         $url_redirect = $_SERVER['HTTP_REFERER'];
                     }
                 }
             }
             if (!$user) {
                 osc_add_flash_error_message(_m('The username doesn\'t exist'));
                 $this->redirectTo(osc_user_login_url());
             }
             if ($user["s_password"] != sha1(Params::getParam('password'))) {
                 osc_add_flash_error_message(_m('The password is incorrect'));
                 $this->redirectTo(osc_user_login_url());
             }
             $uActions = new UserActions(false);
             $logged = $uActions->bootstrap_login($user['pk_i_id']);
             if ($logged == 0) {
                 osc_add_flash_error_message(_m('The username doesn\'t exist'));
             } else {
                 if ($logged == 1) {
                     osc_add_flash_error_message(_m('The user has not been validated yet'));
                 } else {
                     if ($logged == 2) {
                         osc_add_flash_error_message(_m('The user has been suspended'));
                     } else {
                         if ($logged == 3) {
                             if (Params::getParam('remember') == 1) {
                                 //this include contains de osc_genRandomPassword function
                                 require_once osc_lib_path() . 'osclass/helpers/hSecurity.php';
                                 $secret = osc_genRandomPassword();
                                 User::newInstance()->update(array('s_secret' => $secret), array('pk_i_id' => $user['pk_i_id']));
                                 Cookie::newInstance()->set_expires(osc_time_cookie());
                                 Cookie::newInstance()->push('oc_userId', $user['pk_i_id']);
                                 Cookie::newInstance()->push('oc_userSecret', $secret);
                                 Cookie::newInstance()->set();
                             }
                             $this->redirectTo($url_redirect);
                         } else {
                             osc_add_flash_error_message(_m('This should never happens'));
                         }
                     }
                 }
             }
             if (!$user['b_enabled']) {
                 $this->redirectTo(osc_user_login_url());
             }
             $this->redirectTo(osc_user_login_url());
             break;
         case 'recover':
             //form to recover the password (in this case we have the form in /gui/)
             $this->doView('user-recover.php');
             break;
         case 'recover_post':
             //post execution to recover the password
             require_once LIB_PATH . 'osclass/UserActions.php';
             // e-mail is incorrect
             if (!preg_match('|^[a-z0-9\\.\\_\\+\\-]+@[a-z0-9\\.\\-]+\\.[a-z]{2,3}$|i', Params::getParam('s_email'))) {
                 osc_add_flash_error_message(_m('Invalid email address'));
                 $this->redirectTo(osc_recover_user_password_url());
             }
             $userActions = new UserActions(false);
             $success = $userActions->recover_password();
             switch ($success) {
                 case 0:
                     // recover ok
                     osc_add_flash_ok_message(_m('We have sent you an email with the instructions to reset your password'));
                     $this->redirectTo(osc_base_url());
                     break;
                 case 1:
                     // e-mail does not exist
                     osc_add_flash_error_message(_m('We were not able to identify you given the information provided'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
                 case 2:
                     // recaptcha wrong
                     osc_add_flash_error_message(_m('The recaptcha code is wrong'));
                     $this->redirectTo(osc_recover_user_password_url());
                     break;
             }
             break;
         case 'forgot':
             //form to recover the password (in this case we have the form in /gui/)
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user) {
                 $this->doView('user-forgot_password.php');
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
                 $this->redirectTo(osc_base_url());
             }
             break;
         case 'forgot_post':
             if (Params::getParam('new_password') == '' || Params::getParam('new_password2') == '') {
                 osc_add_flash_warning_message(_m('Password cannot be blank'));
                 $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
             }
             $user = User::newInstance()->findByIdPasswordSecret(Params::getParam('userId'), Params::getParam('code'));
             if ($user['b_enabled'] == 1) {
                 if (Params::getParam('new_password') == Params::getParam('new_password2')) {
                     User::newInstance()->update(array('s_pass_code' => osc_genRandomPassword(50), 's_pass_date' => date('Y-m-d H:i:s', 0), 's_pass_ip' => $_SERVER['REMOTE_ADDR'], 's_password' => sha1(Params::getParam('new_password'))), array('pk_i_id' => $user['pk_i_id']));
                     osc_add_flash_ok_message(_m('The password has been changed'));
                     $this->redirectTo(osc_user_login_url());
                 } else {
                     osc_add_flash_error_message(_m('Error, the password don\'t match'));
                     $this->redirectTo(osc_forgot_user_password_confirm_url(Params::getParam('userId'), Params::getParam('code')));
                 }
             } else {
                 osc_add_flash_error_message(_m('Sorry, the link is not valid'));
             }
             $this->redirectTo(osc_base_url());
             break;
         default:
             //login
             if (osc_logged_user_id() != '') {
                 $this->redirectTo(osc_user_dashboard_url());
             }
             $this->doView('user-login.php');
     }
 }
Beispiel #29
0
function osc_add_route($id, $regexp, $url, $file, $user_menu = false, $location = "custom", $section = "custom", $title = "Custom")
{
    Rewrite::newInstance()->addRoute($id, $regexp, $url, $file, $user_menu, $location, $section, $title);
}
Beispiel #30
-1
/**
 * 
 */
function osc_get_http_referer()
{
    $ref = Rewrite::newInstance()->get_http_referer();
    if ($ref != '') {
        return $ref;
    } else {
        if (Session::newInstance()->_getReferer() != '') {
            return Session::newInstance()->_getReferer();
        } else {
            if (isset($_SERVER['HTTP_REFERER'])) {
                return $_SERVER['HTTP_REFERER'];
            }
        }
    }
    return '';
}