Example #1
0
    public function votePoll($poll, $answer){

        if(!$poll['answers']){ return false; }

        $inUser = cmsUser::getInstance();

        //Прибавляем голос к переданному нам варианту ответа
        foreach($poll['answers'] as $key=>$value){
            if ($key == stripslashes($answer)){
                $poll['answers'][$key] += 1;
            }
        }

        $answers = $this->inDB->escape_string(cmsCore::arrayToYaml($poll['answers']));

        //Сохраняем результаты опроса
        $sql = "UPDATE cms_polls SET answers = '{$answers}' WHERE id = '{$poll['id']}'";
        $this->inDB->query($sql);

        // помечаем кто за что проголосовал
        $sql = "INSERT cms_polls_log (poll_id, answer, user_id, ip)
                VALUES ('{$poll['id']}', '$answer', '{$inUser->id}', '{$inUser->ip}')";
        $this->inDB->query($sql);

        return true;

    }
Example #2
0
 function setupAnswers($answers_title) {
     $answers = array();
     
     foreach ($answers_title as $answer) {
         if ($answer) { $answers[$answer] = 0; }
     }
     
     return cmsCore::arrayToYaml($answers);
 }
Example #3
0
    $cat['pagetitle']      = cmsCore::request('pagetitle', 'str', '');
    $cat['meta_desc']      = cmsCore::request('meta_desc', 'str', '');
    $cat['meta_keys']      = cmsCore::request('meta_keys', 'str', '');
    if (!is_numeric($cat['cost'])) { $cat['cost'] = ''; }

    if (cmsCore::request('copy_parent_struct')) {
        $fstruct = cmsCore::c('db')->get_field('cms_uc_cats', "id='{$cat['parent_id']}'", 'fieldsstruct');
    } else {
        $fstruct = cmsCore::request('fstruct', 'array', array());
        foreach ($fstruct as $key=>$value) {
            if ($value=='') { unset($fstruct[$key]); continue; }
            if ($_REQUEST['fformat'][$key]=='html') { $fstruct[$key] .= '/~h~/'; }
            if ($_REQUEST['fformat'][$key]=='link') { $fstruct[$key] .= '/~l~/'; }
            if ($_REQUEST['flink'][$key]) { $fstruct[$key] .= '/~m~/'; }
        }
        $fstruct = cmsCore::arrayToYaml($fstruct);
    }
    $cat['fieldsstruct'] = cmsCore::c('db')->escape_string($fstruct);

    if ($opt == 'submit_cat') {
        $cat_id = cmsCore::c('db')->addNsCategory('cms_uc_cats', cmsCore::callEvent('ADD_CATALOG_CAT', $cat));
    } else {
        $cat_id = cmsCore::request('item_id', 'int', 0);
        $model->updateCategory($cat_id, $cat);
    }

    if ($cat['is_public']) {
        $showfor = cmsCore::request('showfor', 'array_int', array());
        if ($showfor) {
            $model->setCategoryAccess($cat_id, $showfor);
        }
Example #4
0
function board() {
    $inCore = cmsCore::getInstance();

    global $_LANG;

    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { cmsCore::loadClass('billing'); }

    $do = $inCore->do;

    $pagetitle = $inCore->getComponentTitle();
    $pagekeys = $pagedesc  = '';
    
    cmsCore::c('page')->setTitle($pagetitle);
    cmsCore::c('page')->addPathway($pagetitle, '/board');

/////////////////////////////// VIEW CATEGORY //////////////////////////////////
if ($do == 'view') {
    //Получаем текущую категорию
    $category = cmsCore::m('board')->getCategory(cmsCore::m('board')->category_id);
    if (!$category || (!$category['published'] && !cmsCore::c('user')->is_admin)) {
        cmsCore::error404();
    }

    if ($category['id'] != cmsCore::m('board')->root_cat['id']) {
        $pagetitle = $category['pagetitle'] ? $category['pagetitle'] : $category['title'];
        $pagekeys  = $category['meta_keys'];
        $pagedesc  = $category['meta_desc'];

        $category_path  = cmsCore::c('db')->getNsCategoryPath('cms_board_cats', $category['NSLeft'], $category['NSRight']);
        if ($category_path) {
            foreach($category_path as $pcat) {
                cmsCore::c('page')->addPathway($pcat['title'], '/board/'. $pcat['id']);
            }
        }
    } else {
        $category['title'] = $pagetitle = $inCore->menuTitle();
        $category['description'] = cmsCore::m('board')->config['root_description'];
        $pagekeys = cmsCore::m('board')->config['meta_keys'];
        $pagedesc = cmsCore::m('board')->config['meta_desc'];
    }

    // rss в адресной строке
    $rss_cat_id = $category['id'] == cmsCore::m('board')->root_cat['id'] ? 'all' : $category['id'];
    cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'. $_LANG['BOARD'] .'" href="'. HOST .'/rss/board/'. $rss_cat_id .'/feed.rss">');

    //Формируем категории
    $cats = cmsCore::m('board')->getSubCats($category['id']);

    // Формируем список объявлений
    // Устанавливаем категорию
    if ($category['id'] != cmsCore::m('board')->root_cat['id']) {
        cmsCore::m('board')->whereThisAndNestedCats($category['NSLeft'], $category['NSRight']);
    }

    //Город
    if (cmsCore::m('board')->city) {
        cmsCore::m('board')->whereCityIs(cmsCore::m('board')->city);
        $pagetitle .= ' :: '. cmsCore::m('board')->city;
    }

    // Типы объявлений
    if (cmsCore::m('board')->obtype && mb_stristr(icms_ucfirst($category['obtypes']), cmsCore::m('board')->obtype)) {
        cmsCore::m('board')->whereTypeIs(cmsCore::m('board')->obtype);
        $pagetitle .= ' :: '. cmsCore::m('board')->obtype;
    }

    // модератор или админ
    $is_moder = cmsCore::c('user')->is_admin || cmsCore::m('board')->is_moderator_by_group;

    // Общее количество объявлений по заданным выше условиям
    $total = cmsCore::m('board')->getAdvertsCount($is_moder, true);

    //устанавливаем сортировку
    $orderby = cmsCore::m('board')->getOrder('orderby', $category['orderby']);
    $orderto = cmsCore::m('board')->getOrder('orderto', $category['orderto']);
    cmsCore::c('db')->orderBy('is_vip DESC, '. $orderby, $orderto);

    //устанавливаем номер текущей страницы и кол-во объявлений на странице
    cmsCore::c('db')->limitPage(cmsCore::m('board')->page, $category['perpage']);

    // Получаем объявления
    $items = cmsCore::m('board')->getAdverts($is_moder, true, false, true);
    // Если объявлений на странице большей чем 1 нет, 404
    if (!$items && cmsCore::m('board')->page > 1) { cmsCore::error404(); }

    // если не указаны ключевые слова, формируем их из названий рубрик и типов 
    if (!$pagekeys && $cats) { 
        foreach($cats as $c) { 
            $keys[] = $c['title']; 
            foreach (explode("\n", $c['obtypes']) as $obtype) {
                $keys[] = trim($obtype);
            }
        }

        $pagekeys = implode(',', $keys);
    } else if(!$cats) {
        $pagekeys = $category['title'];
    }

    // если не указано описание, формируем из текущих объявлений
    if (!$pagedesc && $items) {
        foreach ($items as $i) {
            $desc[] = $i['title'];
        }

        $pagedesc = implode('. ', $desc);
    } else if(!$items && $category['description']) {
        $pagedesc = crop($category['description']);
    }

    // Проставляем заголовки страницы и описание согласно выборки
    cmsCore::c('page')->setDescription(crop($pagedesc));
    cmsCore::c('page')->setKeywords($pagekeys);
    cmsCore::c('page')->setTitle($pagetitle);

    // Отдаем в шаблон категории
    cmsPage::initTemplate('components', 'com_board_cats')->
        assign('cats', $cats)->
        assign('category', $category)->
        assign('root_id', cmsCore::m('board')->root_cat['id'])->
        assign('is_user', cmsCore::c('user')->id)->
        assign('maxcols', cmsCore::m('board')->config['maxcols'])->
        display();

    $pagebar = cmsPage::getPagebar($total, cmsCore::m('board')->page, $category['perpage'], '/board/%catid%-%page%', array('catid'=>$category['id']));
    $order_form = $category['orderform'] ? cmsCore::m('board')->orderForm($orderby, $orderto, $category) : '';

    // Отдаем в шаблон объявления
    cmsPage::initTemplate('components', 'com_board_items')->
        assign('order_form', $order_form)->
        assign('cfg', cmsCore::m('board')->config)->
        assign('root_id', cmsCore::m('board')->root_cat['id'])->
        assign('items', $items)->
        assign('cat', $category)->
        assign('maxcols', $category['maxcols'])->
        assign('colwidth', round(100/$category['maxcols']))->
        assign('pagebar', $pagebar)->
        display();
}

/////////////////////////////// VIEW USER ADV //////////////////////////////////
if ($do == 'by_user') {
    // логин пользователя
    $login = cmsCore::request('login', 'str', cmsCore::c('user')->login);

    // получаем данные пользователя
    $user = cmsUser::getShortUserData($login);
    if (!$user) { cmsCore::error404(); }

    $myprofile = cmsCore::m('board')->checkAccess($user['id']);

    cmsCore::c('page')->addPathway($user['nickname']);
    cmsCore::c('page')->setTitle($_LANG['BOARD'] .' - '. $user['nickname']);
    cmsCore::c('page')->setDescription($_LANG['BOARD'] .' - '. $user['nickname']);

    // Формируем список объявлений
    cmsCore::m('board')->whereUserIs($user['id']);

    // Общее количество объявлений по заданным выше условиям
    $total = cmsCore::m('board')->getAdvertsCount($myprofile);

    //устанавливаем сортировку
    cmsCore::c('db')->orderBy('pubdate', 'DESC');

    //устанавливаем номер текущей страницы и кол-во объявлений на странице
    cmsCore::c('db')->limitPage(cmsCore::m('board')->page, 15);

    // Получаем объявления
    $items = cmsCore::m('board')->getAdverts($myprofile, true, false, true);
    // Если объявлений на странице большей чем 1 нет, 404
    if(!$items && cmsCore::m('board')->page > 1){ cmsCore::error404(); }

    // Пагинация
    $pagebar = cmsPage::getPagebar($total, cmsCore::m('board')->page, 15, '/board/by_user_'.$login.'/page-%page%');

    // Показываем даты
    $category['showdate'] = 1;

    cmsPage::initTemplate('components', 'com_board_items')->
        assign('cfg', cmsCore::m('board')->config)->
        assign('page_title', $_LANG['BOARD'].' - '.$user['nickname'])->
        assign('root_id', cmsCore::m('board')->root_cat['id'])->
        assign('items', $items)->
        assign('cat', $category)->
        assign('maxcols', 1)->
        assign('colwidth', 100)->
        assign('pagebar', $pagebar)->
        display();
}

/////////////////////////////// VIEW ITEM //////////////////////////////////////
if ($do == 'read') {
    // получаем объявление
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    if (!$item) { cmsCore::error404(); }

    // неопубликованные показываем админам, модераторам и автору
    if (!$item['published'] && !$item['moderator']) { cmsCore::error404(); }

    // для неопубликованного показываем инфо: просрочено/на модерации
    if (!$item['published']) {
        $info_text = $item['is_overdue'] ? $_LANG['ADV_IS_EXTEND'] : $_LANG['ADV_IS_MODER'];
        cmsCore::addSessionMessage($info_text, 'info');
    } else {
        // увеличиваем кол-во просмотров
        cmsCore::c('db')->setFlag('cms_board_items', cmsCore::m('board')->item_id, 'hits', $item['hits']+1);
    }

    // формируем заголовок и тело сообщения
    $item['title']   = $item['obtype'].' '.$item['title'];
    $item['content'] = nl2br($item['content']);
    $item['content'] = cmsCore::m('board')->config['auto_link'] ? $inCore->parseSmiles($item['content']) : $item['content'];

    $category_path = cmsCore::c('db')->getNsCategoryPath('cms_board_cats', $item['NSLeft'], $item['NSRight']);
    if ($category_path) {
        foreach ($category_path as $pcat) {
            cmsCore::c('page')->addPathway($pcat['title'], '/board/'.$pcat['id']);
        }
    }
    cmsCore::c('page')->addPathway($item['title']);

    $pagetitle = $item['pagetitle'] ? $item['pagetitle'] : $item['title'];
    $pagekeys  = $item['meta_keys'] ? $item['meta_keys'] : $item['title'];
    $pagedesc  = $item['meta_desc'] ? $item['meta_desc'] : $item['content'];

    cmsCore::c('page')->setTitle($pagetitle);
    cmsCore::c('page')->setDescription(crop($pagedesc));
    cmsCore::c('page')->setKeywords($pagekeys);

    cmsPage::initTemplate('components', 'com_board_item')->
        assign('item', $item)->
        assign('cfg', cmsCore::m('board')->config)->
        assign('user_id', cmsCore::c('user')->id)->
        assign('is_admin', cmsCore::c('user')->is_admin)->
        assign('formsdata', cmsForm::getFieldsValues($item['form_id'], $item['form_array']))->
        assign('is_moder', cmsCore::m('board')->is_moderator_by_group)->
        display();
}

/////////////////////////////// NEW BOARD ITEM /////////////////////////////////
if ($do == 'additem') {
    // Получаем категории, в которые может загружать пользователь
    $catslist = cmsCore::m('board')->getPublicCats(cmsCore::m('board')->category_id);
    if (!$catslist) {
        cmsCore::addSessionMessage($_LANG['YOU_CANT_ADD_ADV_ANY'], 'error');
        $inCore->redirect('/board');
    }

    $cat['is_photos'] = 1;
    $formsdata = array();
    if (cmsCore::m('board')->category_id && cmsCore::m('board')->category_id != cmsCore::m('board')->root_cat['id']) {
        $cat = cmsCore::m('board')->getCategory(cmsCore::m('board')->category_id);
        $formsdata = cmsForm::getFieldsHtml($cat['form_id']);
    }

    cmsCore::c('page')->addPathway($_LANG['ADD_ADV']);

    if ( !cmsCore::inRequest('submit') ) {
        if (IS_BILLING) { cmsBilling::checkBalance('board', 'add_item'); }
        cmsCore::c('page')->setTitle($_LANG['ADD_ADV']);

        $item = cmsUser::sessionGet('item');
        if ($item) { cmsUser::sessionDel('item'); }

        $item['city'] = !empty($item['city']) ? $item['city'] : cmsCore::c('user')->city;

        cmsPage::initTemplate('components', 'com_board_edit')->
            assign('action', "/board/add.html")->
            assign('form_do', 'add')->
            assign('cfg', cmsCore::m('board')->config)->
            assign('cat', $cat)->
            assign('item', $item)->
            assign('pagetitle', $_LANG['ADD_ADV'])->
            assign('formsdata', $formsdata)->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('is_user', cmsCore::c('user')->id)->
            assign('catslist', $catslist)->
            assign('is_billing', IS_BILLING)->assign('balance', cmsCore::c('user')->balance)->
            display();

        cmsUser::sessionClearAll();

        return;
    }

    if ( cmsCore::inRequest('submit') ) {
        // проверяем на заполненость скрытое поле
        $title_fake = cmsCore::request('title_fake', 'str', '');
        // если оно заполнено, считаем что это бот, 404
        if ($title_fake) { cmsCore::error404(); }

        $errors = false;

        // проверяем наличие категории
        if (!$cat['id']) {
            cmsCore::addSessionMessage($_LANG['NEED_CAT_ADV'], 'error');
            $errors = true;
        }

        // Проверяем количество добавленных за сутки
        if (!cmsCore::m('board')->checkLoadedByUser24h($cat)){
            cmsCore::addSessionMessage($_LANG['MAX_VALUE_OF_ADD_ADV'], 'error');
            $errors = true;
        }
        // Можем ли добавлять в эту рубрику
        if (!cmsCore::m('board')->checkAdd($cat)){
            cmsCore::addSessionMessage($_LANG['YOU_CANT_ADD_ADV'], 'error');
            $errors = true;
        }

        // входные данные
        $obtype     = icms_ucfirst(cmsCore::request('obtype', 'str', ''));
        $title      = trim(str_ireplace($obtype, '', cmsCore::request('title', 'str', '')));
        $content    = cmsCore::request('content', 'str', '');
        $city       = cmsCore::request('city', 'str', '');

        if ((cmsCore::m('board')->config['seo_user_access'] && cmsCore::c('user')->id) || cmsCore::c('user')->is_admin) {
            $pagetitle = cmsCore::request('pagetitle', 'str', '');
            $meta_keys = cmsCore::request('meta_keys', 'str', '');
            $meta_desc = cmsCore::request('meta_desc', 'str', '');
        } else {
            $pagetitle = $meta_keys = $meta_desc = '';
        }

        $form_input = cmsForm::getFieldsInputValues($cat['form_id']);
        $formsdata  = cmsCore::c('db')->escape_string(cmsCore::arrayToYaml($form_input['values']));

        $vipdays    = cmsCore::request('vipdays', 'int', 0);

        $published  = cmsCore::m('board')->checkPublished($cat);

        if (cmsCore::m('board')->config['srok']){  $pubdays = (cmsCore::request('pubdays', 'int') <= 50) ? cmsCore::request('pubdays', 'int') : 50; }
        if (!cmsCore::m('board')->config['srok']){ $pubdays = isset(cmsCore::m('board')->config['pubdays']) ? cmsCore::m('board')->config['pubdays'] : 14; }

        // Проверяем значения
        if (!$title) {
            cmsCore::addSessionMessage($_LANG['NEED_TITLE'], 'error');
            $errors = true;
        }
        if (!$content) {
            cmsCore::addSessionMessage($_LANG['NEED_TEXT_ADV'], 'error');
            $errors = true;
        }
        if (!$city) {
            cmsCore::addSessionMessage($_LANG['NEED_CITY'], 'error');
            $errors = true;
        }
        if (!cmsCore::c('user')->id && !cmsCore::checkCaptchaCode()) {
            cmsCore::addSessionMessage($_LANG['ERR_CAPTCHA'], 'error');
            $errors = true;
        }

        // Проверяем значения формы
        foreach ($form_input['errors'] as $field_error) {
            if ($field_error) {
                cmsCore::addSessionMessage($field_error, 'error');
                $errors = true;
            }
        }

        if ($errors) {
            $item['content'] = htmlspecialchars(stripslashes($_REQUEST['content']));
            $item['city']    = stripslashes($city);
            $item['title']   = stripslashes($title);
            $item['obtype']  = $obtype;
            cmsUser::sessionPut('item', $item);
            cmsCore::redirect('/board/'. cmsCore::m('board')->category_id .'/add.html');
        }

        if ($cat['is_photos']) {
            // Загружаем фото
            $file = cmsCore::m('board')->uploadPhoto('', $cat);
        } else {
            $file['filename'] = '';
            cmsCore::addSessionMessage($_LANG['INFO_CAT_NO_PHOTO'], 'info');
        }
        
        
        $add = array(
            'category_id' => cmsCore::m('board')->category_id,
            'user_id'     => cmsCore::c('user')->id,
            'obtype'      => $obtype,
            'title'       => $title,
            'content'     => $content,
            'formsdata'   => $formsdata,
            'city'        => $city,
            'pubdays'     => $pubdays,
            'published'   => $published,
            'pagetitle'   => $pagetitle,
            'meta_keys'   => $meta_keys,
            'meta_desc'   => $meta_desc,
            'file'        => $file['filename']
        );
        $add['id'] = cmsCore::m('board')->addRecord($add);

        if (cmsCore::c('user')->is_admin && $vipdays) {
            cmsCore::m('board')->setVip($add['id'], $vipdays);
        }

        if (IS_BILLING) {
            cmsBilling::process('board', 'add_item');
            if (cmsCore::m('board')->config['vip_enabled'] && $vipdays && cmsCore::m('board')->config['vip_day_cost']) {
                if ($vipdays > cmsCore::m('board')->config['vip_max_days']) {
                    $vipdays = cmsCore::m('board')->config['vip_max_days'];
                }

                $summ = $vipdays * cmsCore::m('board')->config['vip_day_cost'];

                if (cmsCore::c('user')->balance >= $summ) {
                    cmsBilling::pay(cmsCore::c('user')->id, $summ, $_LANG['VIP_ITEM']);
                    cmsCore::m('board')->setVip($add['id'], $vipdays);
                }
            }
        }

        cmsUser::sessionClearAll();

        if ($published) {
            //регистрируем событие
            cmsActions::log('add_board', array(
                'object'      => $obtype .' '. $title,
                'object_url'  => '/board/read'. $add['id'] .'.html',
                'object_id'   => $add['id'],
                'target'      => $cat['title'],
                'target_url'  => '/board/'. $cat['id'],
                'target_id'   => $cat['id'],
                'description' => ''
            ));
            cmsCore::addSessionMessage($_LANG['ADV_IS_ADDED'], 'success');
            cmsCore::callEvent('ADD_BOARD_DONE', $add);
            cmsCore::redirect('/board/read'. $add['id'] .'.html');
        }

        if (!$published) {
            $link = '<a href="/board/read'. $add['id'] .'.html">'. $obtype .' '. $title .'</a>';
            if (cmsCore::c('user')->id) {
                $user = '******'. cmsUser::getProfileURL(cmsCore::c('user')->login) .'">'. cmsCore::c('user')->nickname .'</a>';
            } else {
                $user = $_LANG['BOARD_GUEST'] .', ip: '. cmsCore::c('user')->ip;
            }
            $message = str_replace('%user%', $user, $_LANG['MSG_ADV_SUBMIT']);
            $message = str_replace('%link%', $link, $message);
            cmsUser::sendMessage(USER_UPDATER, 1, $message);

            cmsCore::addSessionMessage($_LANG['ADV_IS_ADDED'] .'<br>'. $_LANG['ADV_PREMODER_TEXT'], 'success');
            cmsCore::redirect('/board/'.cmsCore::m('board')->category_id);
        }
    }
}

/////////////////////////////// EDIT BOARD ITEM ////////////////////////////////
if ($do == 'edititem') {
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    $cat  = cmsCore::m('board')->getCategory($item['category_id']);

    if (!$cat || !$item) { cmsCore::error404(); }

    cmsCore::c('page')->setTitle($_LANG['EDIT_ADV']);
    cmsCore::c('page')->addPathway($item['category'], '/board/'. $item['cat_id']);
    cmsCore::c('page')->addPathway($_LANG['EDIT_ADV']);

    if (!$item['moderator']) {
        cmsCore::addSessionMessage($_LANG['YOU_HAVENT_ACCESS'], 'error');
        cmsCore::redirect('/board/read'. $item['id'] .'.html');
    }

    $errors = false;

    if (!cmsCore::inRequest('submit')) {
        cmsPage::initTemplate('components', 'com_board_edit')->
            assign('action', "/board/edit{$item['id']}.html")->
            assign('form_do', 'edit')->
            assign('cfg', cmsCore::m('board')->config)->
            assign('cat', $cat)->
            assign('item', $item)->
            assign('pagetitle', $_LANG['EDIT_ADV'])->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('catslist', cmsCore::m('board')->getPublicCats($item['category_id'], true))->
            assign('formsdata', cmsForm::getFieldsHtml($cat['form_id'], $item['form_array']))->
            assign('is_user', cmsCore::c('user')->id)->
            assign('is_billing', IS_BILLING)->assign('balance', cmsCore::c('user')->balance)->
            display();

        cmsUser::sessionClearAll();
    }

    if (cmsCore::inRequest('submit')) {
        $new_cat_id = cmsCore::request('category_id', 'int', 0);
        if ($new_cat_id) {
            $item['category_id'] = $new_cat_id;
        }

        $form_input = cmsForm::getFieldsInputValues($cat['form_id']);
        $formsdata  = cmsCore::c('db')->escape_string(cmsCore::arrayToYaml($form_input['values']));

        if ($item['is_overdue'] && !$item['published']) {
            if (cmsCore::m('board')->config['srok']) {
                $pubdays = (cmsCore::request('pubdays', 'int') <= 50) ? cmsCore::request('pubdays', 'int') : 50;
            }
            if (!cmsCore::m('board')->config['srok']) {
                $pubdays = isset(cmsCore::m('board')->config['pubdays']) ? cmsCore::m('board')->config['pubdays'] : 14;
            }

            $pubdate = date('Y-m-d H:i:s');
        } else {
            $pubdays = $item['pubdays'];
            $pubdate = $item['fpubdate'];
        }

        $update['obtype']      = icms_ucfirst(cmsCore::request('obtype', 'str'));
        $update['title']       = trim(str_ireplace($update['obtype'], '', cmsCore::request('title', 'str', '')));
        $update['category_id'] = $item['category_id'];
        $update['content']     = cmsCore::request('content', 'str', '');
        $update['formsdata']   = $formsdata;
        $update['city']        = cmsCore::request('city', 'str', '');
        $update['pubdate']     = $pubdate;
        $update['pubdays']     = $pubdays;
        $update['published']   = cmsCore::m('board')->checkPublished($cat, true);
        if ((cmsCore::m('board')->config['seo_user_access'] && cmsCore::c('user')->id) || cmsCore::c('user')->is_admin) {
            $update['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
            $update['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
            $update['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
        }

        if (!$update['title']) {
            cmsCore::addSessionMessage($_LANG['NEED_TITLE'], 'error');
            $errors = true;
        }
        if (!$update['content']) {
            cmsCore::addSessionMessage($_LANG['NEED_TEXT_ADV'], 'error');
            $errors = true;
        }
        if (!$update['city']) {
            cmsCore::addSessionMessage($_LANG['NEED_CITY'], 'error');
            $errors = true;
        }

        // Проверяем значения формы
        foreach ($form_input['errors'] as $field_error) {
            if ($field_error) {
                cmsCore::addSessionMessage($field_error, 'error');
                $errors = true;
            }
        }

        if ($errors) {
            $inCore->redirect('/board/edit'. $item['id'] .'.html');
        }

        if ($cat['is_photos']) {
            // Загружаем фото
            $file = cmsCore::m('board')->uploadPhoto($item['file'], $cat);
        }

        $update['file'] = $file['filename'] ? $file['filename'] : $item['file'];

        // обновляем объявление
        cmsCore::m('board')->updateRecord($item['id'], $update);
        // обновляем запись в ленте активности
        cmsActions::updateLog('add_board', array('object' => $update['obtype'] .' '. $update['title']), $item['id']);
        $vipdays = cmsCore::request('vipdays', 'int', 0);

        if (cmsCore::c('user')->is_admin) {
            if ($vipdays > 0) {
                cmsCore::m('board')->setVip($item['id'], $vipdays);
            }
            if ($vipdays == -1) {
                cmsCore::m('board')->deleteVip($item['id']);
            }
        }

        if (IS_BILLING) {
            if (cmsCore::m('board')->config['vip_enabled'] && cmsCore::m('board')->config['vip_prolong'] && $vipdays && cmsCore::m('board')->config['vip_day_cost']) {
                if ($vipdays > cmsCore::m('board')->config['vip_max_days']) {
                    $vipdays = cmsCore::m('board')->config['vip_max_days'];
                }

                $summ = $vipdays * cmsCore::m('board')->config['vip_day_cost'];

                if (cmsCore::c('user')->balance >= $summ) {
                    cmsBilling::pay(cmsCore::c('user')->id, $summ, $_LANG['VIP_ITEM']);
                    cmsCore::m('board')->setVip($item['id'], $vipdays);
                }
            }
        }

        cmsUser::sessionClearAll();

        if (!$update['published']) {
            $link = '<a href="/board/read'. $item['id'] .'.html">'. $update['obtype'] .' '. $update['title'] .'</a>';
            $user = '******'. cmsUser::getProfileURL(cmsCore::c('user')->login) .'">'. cmsCore::c('user')->nickname .'</a>';

            $message = str_replace(array('%link%','%user%'), array($link,$user), $_LANG['MSG_ADV_EDITED']);
            cmsUser::sendMessage(USER_UPDATER, 1, $message);

            cmsCore::addSessionMessage($_LANG['ADV_EDIT_PREMODER_TEXT'], 'info');
        }

        cmsCore::addSessionMessage($_LANG['ADV_MODIFIED'], 'success');
        cmsCore::redirect('/board/read'. $item['id'] .'.html');
    }
}

///////////////////////// PUBLISH BOARD ITEM ///////////////////////////////////
if ($do == 'publish') {
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    if (!$item) { cmsCore::error404(); }

    // если уже опубликовано, 404
    if ($item['published']) { cmsCore::error404(); }

    // публиковать могут админы и модераторы доски
    if (!cmsCore::c('user')->is_admin && !cmsCore::m('board')->is_moderator_by_group) {
        cmsCore::error404();
    }

    // публикуем
    cmsCore::c('db')->setFlag('cms_board_items', cmsCore::m('board')->item_id, 'published', 1);

    cmsCore::callEvent('ADD_BOARD_DONE', $item);

    if ($item['user_id']) {
        //регистрируем событие
        cmsActions::log('add_board', array(
            'object'      => $item['obtype'] .' '. $item['title'],
            'user_id'     => $item['user_id'],
            'object_url'  => '/board/read'. $item['id'] .'.html',
            'object_id'   => $item['id'],
            'target'      => $item['category'],
            'target_url'  => '/board/'. $item['cat_id'],
            'target_id'   => $item['cat_id'],
            'description' => ''
        ));

        $link = '<a href="/board/read'. $item['id'] .'.html">'. $item['obtype'] .' '. $item['title'] .'</a>';
        $message = str_replace('%link%', $link, $_LANG['MSG_ADV_ACCEPTED']);
        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);
    }

    cmsCore::addSessionMessage($_LANG['ADV_IS_ACCEPTED'], 'success');

    cmsCore::redirect('/board/read'. $item['id'] .'.html');
}

/////////////////////////////// DELETE BOARD ITEM //////////////////////////////
if ($do == 'delete') {
    $item = cmsCore::m('board')->getRecord(cmsCore::m('board')->item_id);
    if (!$item) { cmsCore::error404(); }

    if (!$item['moderator']) {
        cmsCore::addSessionMessage($_LANG['YOU_HAVENT_ACCESS'], 'error');
        cmsCore::redirect('/board/'. $item['cat_id']);
    }

    if (!cmsCore::inRequest('godelete')) {
        cmsCore::c('page')->setTitle($_LANG['DELETE_ADV']);
        cmsCore::c('page')->addPathway($item['category'], '/board/'. $item['cat_id']);
        cmsCore::c('page')->addPathway($_LANG['DELETE_ADV']);

        $confirm['title']               = $_LANG['DELETING_ADV'];
        $confirm['text']                = $_LANG['YOU_SURE_DELETE_ADV'] .' "'. $item['title'] .'"?';
        $confirm['action']              = $_SERVER['REQUEST_URI'];
        $confirm['yes_button']['name']  = 'godelete';

        cmsPage::initTemplate('components', 'action_confirm')->
            assign('confirm', $confirm)->
            display();
    }

    if (cmsCore::inRequest('godelete')) {
        cmsCore::m('board')->deleteRecord(cmsCore::m('board')->item_id);
        cmsCore::addSessionMessage($_LANG['ADV_IS_DELETED'], 'success');
        cmsCore::redirect('/board/'. $item['cat_id']);
    }
}
}
Example #5
0
function applet_modules() {
    $inCore = cmsCore::getInstance();

    global $_LANG;

    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) { cpAccessDenied(); }

    cmsCore::c('page')->setTitle($_LANG['AD_MODULES']);
    cpAddPathway($_LANG['AD_MODULES'], 'index.php?view=modules');
    cmsCore::c('page')->addHeadJS('admin/js/modules.js');

    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    $co = cmsCore::request('co', 'int', -1);

    if ($do == 'config') {
        $module_name  = cpModuleById($id);
        $module_title = cpModuleTitleById($id);

        if (!$module_name) { cmsCore::redirect('index.php?view=modules&do=edit&id='. $id); }

        $xml_file = PATH .'/admin/modules/'. $module_name .'/backend.xml';
        $php_file = 'modules/'. $module_name .'/backend.php';
        
        if (file_exists($php_file)) {
            include $php_file;
            return;
        }
        
        $cfg = $inCore->loadModuleConfig($id);
        
        cpAddPathway($module_title, '?view=modules&do=edit&id='. $id);
        cpAddPathway($_LANG['AD_SETTINGS']);

        echo '<h3>'. $module_title .'</h3>';
        
        $toolmenu = array(
            array( 'icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:submitModuleConfig();' ),
            array( 'icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'index.php?view=modules' ),
            array( 'icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_MODULE_VIEW'], 'link' => '?view=modules&do=edit&id='. $id )
        );

        cpToolMenu($toolmenu);
?>
        <form action="index.php?view=modules&do=save_auto_config&id=<?php echo $id; ?>" method="post" name="optform" target="_self" id="optform">
            <div class="panel panel-default" style="width:650px;">
                <div class="panel-body">
<?php
        if (file_exists($xml_file)) {
            cmsCore::loadClass('formgen');
            $formGen = new cmsFormGen($xml_file, $cfg);
            echo $formGen->getHTML();
        } else {
?>
                    <div class="form-group">
                        <label class="col-sm-5 control-label"><?php echo $_LANG['AD_MODULE_TEMPLATE']; ?></label>
                        <div class="col-sm-7">
                            <input type="text" class="form-control" value="<?php echo $cfg['tpl']; ?>" />
                        </div>
                    </div>
<?php
        }
?>
                </div>
                <div class="panel-footer">
                    <input type="submit" name="save" class="btn btn-primary" value="<?php echo $_LANG['SAVE']; ?>" />
                </div>
            </div>
        <script type="text/javascript">
            function submitModuleConfig(){
                $('#optform').submit();
            }
        </script>
        </form>
<?php

        return;
    }

    if ($do == 'save_auto_config') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }
        
        $module_name = cpModuleById($id);

        $is_ajax = cmsCore::inRequest('ajax');

        if ($is_ajax) {
            $title      = cmsCore::request('title', 'str', '');
            $published  = cmsCore::request('published', 'int', 0);
            cmsCore::c('db')->query("UPDATE cms_modules SET title='". $title ."', published='". $published ."' WHERE id=". $id);
            if (cmsCore::inRequest('content')) {
                $content = cmsCore::c('db')->escape_string(cmsCore::request('content', 'html'));
                cmsCore::c('db')->query("UPDATE cms_modules SET content='". $content ."' WHERE id=". $id);
            }
        }

        if (cmsCore::inRequest('title_only')) { cmsCore::redirectBack(); }

        $xml_file = PATH .'/admin/modules/'. $module_name .'/backend.xml';
        if (file_exists($xml_file)) {
            $cfg = array();

            $backend = simplexml_load_file($xml_file);

            foreach ($backend->params->param as $param) {
                $name    = (string)$param['name'];
                $type    = (string)$param['type'];
                $default = (string)$param['default'];

                switch($param['type']) {
                    case 'number': $value = cmsCore::request($name, 'int', $default); break;
                    case 'string': $value = cmsCore::request($name, 'str', $default); break;
                    case 'html':   $value = cmsCore::badTagClear(cmsCore::request($name, 'html', $default)); break;
                    case 'flag': $value = cmsCore::request($name, 'int', 0); break;
                    case 'list': $value = (is_array($_POST[$name]) ? cmsCore::request($name, 'array_str', $default) : cmsCore::request($name, 'str', $default)); break;
                    case 'list_function': $value = cmsCore::request($name, 'str', $default); break;
                    case 'list_db': $value = (is_array($_POST[$name]) ? cmsCore::request($name, 'array_str', $default) : cmsCore::request($name, 'str', $default)); break;
                }

                $cfg[$name] = $value;
            }
        }
        
        $cfg['tpl'] = cmsCore::request('tpl', 'str', $module_name);

        $inCore->saveModuleConfig($id, $cfg);

        if (!$is_ajax) {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        }

        cmsCore::redirectBack();
    }

    if ($do == 'list') {
        $toolmenu = array(
            array( 'icon' => 'new.gif', 'title' => $_LANG['AD_MODULE_ADD'], 'link' => '?view=modules&do=add' ),
            array( 'icon' => 'install.gif', 'title' => $_LANG['AD_MODULES_SETUP'], 'link' => '?view=install&do=module' ),
            array( 'icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=edit&multiple=1');" ),
            array( 'icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=delete&multiple=1');" ),
            array( 'icon' => 'show.gif', 'title' => $_LANG['AD_ALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=show&multiple=1');" ),
            array( 'icon' => 'hide.gif', 'title' => $_LANG['AD_DISALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=hide&multiple=1');" ),
            array( 'icon' => 'autoorder.gif', 'title' => $_LANG['AD_MODULE_ORDER'], 'link' => '?view=modules&do=autoorder' ),
            array( 'icon' => 'reorder.gif', 'title' => $_LANG['AD_SAVE_ORDER'], 'link' => "javascript:checkSel('?view=modules&do=saveorder');" ),
            array( 'icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=modules' )
        );

        cpToolMenu($toolmenu);
        
        $fields = array(
            array( 'title' => 'id', 'field' => 'id', 'width' => '40' ),
            array(
                'title' => $_LANG['AD_TITLE'],
                'field' => array('title','titles'), 'width'=>'',
                'link'  => '?view=modules&do=edit&id=%id%',
                'prc'   => function ($i) {
                    $i['titles'] = cmsCore::yamlToArray($i['titles']);
                    // переопределяем название пункта меню в зависимости от языка
                    if (!empty($i['titles'][cmsConfig::getConfig('lang')])) {
                        $i['title'] = $i['titles'][cmsConfig::getConfig('lang')];
                    }
                    
                    return $i['title'];
                }
            ),
            array( 'title' => $_LANG['TITLE'], 'field' => 'name', 'width' => '220', 'filter' => '15' ),
            array( 'title' => $_LANG['AD_VERSION'], 'field' => 'version', 'width' => '70' ),
            array( 'title' => $_LANG['AD_AUTHOR'], 'field' => 'author', 'width' => '110' ),
            array( 'title' => $_LANG['SHOW'], 'field' => 'published', 'width' => '80' ),
            array( 'title' => $_LANG['AD_ORDER'], 'field' => 'ordering', 'width' => '100' ),
            array( 'title' => $_LANG['AD_POSITION'], 'field' => 'position', 'width' => '80', 'filter' => '10', 'filterlist' => cpGetList('positions') )
        );
        
        $actions = array(
            array( 'title' => $_LANG['AD_CONFIG'], 'icon' => 'config.gif', 'link' => '?view=modules&do=config&id=%id%', 'condition' => 'cpModuleHasConfig' ),
            array( 'title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=modules&do=edit&id=%id%' ),
            array( 'title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_MODULE_DELETE'], 'link' => '?view=modules&do=delete&id=%id%' )
        );
        
        cpListTable('cms_modules', $fields, $actions, '', 'published DESC, position, ordering ASC');
    }

    if ($do == 'autoorder'){
        $rs = cmsCore::c('db')->query("SELECT id, position FROM cms_modules ORDER BY position") ;

        if (cmsCore::c('db')->num_rows($rs)) {
            $ord = 1;
            while ($item = cmsCore::c('db')->fetch_assoc($rs)) {
                if (isset($latest_pos)) {
                    if ($latest_pos != $item['position']) {
                        $ord = 1;
                    }
                }
                cmsCore::c('db')->query("UPDATE cms_modules SET ordering = ". $ord ." WHERE id=". $item['id']) ;
                $ord += 1;
                $latest_pos = $item['position'];
            }
        }

        cmsCore::redirect('index.php?view=modules');
    }

    if ($do == 'move_up') {
        if ($id >= 0) { dbMoveUp('cms_modules', $id, $co); }
        cmsCore::redirectBack();
    }

    if ($do == 'move_down') {
        if ($id >= 0) { dbMoveDown('cms_modules', $id, $co); }
        cmsCore::redirectBack();
    }

    if ($do == 'saveorder') {
        if (isset($_REQUEST['ordering'])) {
            $ord = $_REQUEST['ordering'];
            $ids = $_REQUEST['ids'];

            foreach ($ord as $id=>$ordering) {
                cmsCore::c('db')->query("UPDATE cms_modules SET ordering = ". (int)$ordering ." WHERE id = ". (int)$ids[$id]);
            }
            cmsCore::redirect('index.php?view=modules');
        }
    }

    if ($do == 'show') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) { cmsCore::c('db')->setFlag('cms_modules', $id, 'published', '1'); }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_modules', $_REQUEST['item'], 'published', '1');
            cmsCore::redirectBack();
        }

    }

    if ($do == 'hide') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) { cmsCore::c('db')->setFlag('cms_modules', $id, 'published', '0'); }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_modules', $_REQUEST['item'], 'published', '0');
            cmsCore::redirectBack();
        }
    }

    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            $inCore->removeModule($id);
        } else {
            $inCore->removeModule(cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('index.php?view=modules');
    }

    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }
        
        $id = cmsCore::request('id', 'int', 0);
        $mod = cmsCore::c('db')->get_fields('cms_modules', "id = ". $id ."", '*');
        
        $module = array(
            'name'       => cmsCore::request('name', 'str', ''),
            'title'      => cmsCore::request('title', 'str', ''),
            'titles'     => cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array())),
            'position'   => cmsCore::request('position', 'str', ''),
            'showtitle'  => cmsCore::request('showtitle', 'int', 0),
            'published'  => cmsCore::request('published', 'int', 0),
            'css_prefix' => cmsCore::request('css_prefix', 'str', ''),
            'is_strict_bind' => cmsCore::request('is_strict_bind', 'int', 0),
            'is_strict_bind_hidden' => cmsCore::request('is_strict_bind_hidden', 'int', 0),
            'template'   => cmsCore::request('template', 'str', ''),
            'cache'      => cmsCore::request('cache', 'int', 0),
            'cachetime'  => cmsCore::request('cachetime', 'int', 0),
            'cacheint'   => cmsCore::request('cacheint', 'str', ''),
            'access_list' => '',
            'hidden_menu_ids' => ''
        );
        
        if (!$mod['is_external']) {
            $module['content'] = cmsCore::c('db')->escape_string(cmsCore::request('content', 'html', ''));
        }

        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $module['access_list'] = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int', array()));
        }
        
        cmsCore::c('db')->update('cms_modules', $module, $id);
        cmsCore::c('db')->delete('cms_modules_bind', "module_id=". $id ." AND tpl='". cmsCore::c('config')->template ."'");

        if (cmsCore::request('show_all', 'int', 0)) {
            cmsCore::c('db')->insert(
                'cms_modules_bind',
                array(
                    'module_id' => $id,
                    'menu_id'   => 0,
                    'position'  => $module['position'],
                    'tpl'       => cmsCore::c('config')->template
                )
            );
            
            $hidden_menu_ids = cmsCore::request('hidden_menu_ids', 'array_int', array());
            if (!empty($hidden_menu_ids)) {
                $hidden_menu_ids = cmsCore::arrayToYaml($hidden_menu_ids);
                cmsCore::c('db')->query("UPDATE cms_modules SET hidden_menu_ids='". $hidden_menu_ids ."' WHERE id = '". $id ."' LIMIT 1");
            }
        } else {
            $showin  = cmsCore::request('showin', 'array_int', array());
            $showpos = cmsCore::request('showpos', 'array_str', array());
            if (count($showin) > 0) {
                foreach ($showin as $key => $value) {
                    cmsCore::c('db')->insert(
                        'cms_modules_bind',
                        array(
                            'module_id' => $id,
                            'menu_id'   => $value,
                            'position'  => $showpos[$value],
                            'tpl'       => cmsCore::c('config')->template
                        )
                    );
                }
            }
        }

        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');

        if (!isset($_SESSION['editlist']) || count($_SESSION['editlist']) == 0) {
            cmsCore::redirect('index.php?view=modules');
        } else {
            cmsCore::redirect('index.php?view=modules&do=edit');
        }
    }

    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }
        
        $maxorder = cmsCore::c('db')->get_field('cms_menu', '1=1 ORDER BY ordering DESC', 'ordering') + 1;

        $name           = cmsCore::request('name', 'str', '');
        $title          = cmsCore::request('title', 'str', '');
        $titles         = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $position       = cmsCore::request('position', 'str', '');
        $showtitle      = cmsCore::request('showtitle', 'int', 0);
        $content    	= cmsCore::c('db')->escape_string(cmsCore::request('content', 'html', ''));
        $published      = cmsCore::request('published', 'int', 0);
        $css_prefix     = cmsCore::request('css_prefix', 'str', '');

        $is_public      = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int', array()));
        }

        $template       = cmsCore::request('template', 'str', '');
        $cache          = cmsCore::request('cache', 'int', 0);
        $cachetime      = cmsCore::request('cachetime', 'int', 0);
        $cacheint       = cmsCore::request('cacheint', 'str', '');
        $operate        = cmsCore::request('operate', array('user', 'clone'), '');

        $is_strict_bind = cmsCore::request('is_strict_bind', 'int', 0);
        $is_strict_bind_hidden = cmsCore::request('is_strict_bind_hidden', 'int', 0);

        if ($operate == 'user') { //USER MODULE
            $sql = "INSERT INTO cms_modules (position, name, title, titles, is_external, content, ordering, showtitle, published, user, original, css_prefix, access_list, template, is_strict_bind, is_strict_bind_hidden)
                            VALUES ('". $position ."', '". $name ."', '". $title ."', '". $titles ."', 0, '". $content ."', '". $maxorder ."', '". $showtitle ."', '". $published ."', 1, 1, '". $css_prefix ."', '". $access_list ."', '". $template ."', '". $is_strict_bind ."', '". $is_strict_bind_hidden ."')";
            cmsCore::c('db')->query($sql) ;
        }

        if ($operate == 'clone') { //DUPLICATE MODULE
            $mod_id     = cmsCore::request('clone_id', 'int', 0);

            $sql         = "SELECT * FROM cms_modules WHERE id = ". $mod_id ." LIMIT 1";
            $result      = cmsCore::c('db')->query($sql) ;
            $original    = cmsCore::c('db')->escape_string(cmsCore::c('db')->fetch_assoc($result));
            $is_original = cmsCore::request('del_orig', 'int', 0) ? 1 : 0;

            $sql = "INSERT INTO cms_modules (position, name, title, titles, is_external, content, ordering, showtitle, published, original, user, config, css_prefix, template, access_list, is_strict_bind, is_strict_bind_hidden, cache, cachetime, cacheint, version)
                        VALUES (
                            '". $position ."',
                            '". $original['name'] ."',
                            '". $title ."',
                            '". $titles ."',
                            '". $original['is_external'] ."',
                            '". $original['content'] ."',
                            '". $maxorder ."',
                            '". $showtitle ."',
                            '". $published ."',
                            '". $is_original ."',
                            '". $original['user'] ."',
                            '". $original['config'] ."',
                            '". $css_prefix ."',
                            '". $template ."',
                            '". $access_list ."',
                            '". $is_strict_bind ."',
                            '". $is_strict_bind_hidden ."',
                            '". $cache ."', 
                            '". $cachetime ."',
                            '". $cacheint ."',
                            '". $original['version'] ."'
                )";
            cmsCore::c('db')->query($sql);

            if (cmsCore::request('del_orig', 'int', 0)) {
                $sql = "DELETE FROM cms_modules WHERE id = ". $mod_id;
                cmsCore::c('db')->query($sql) ;
            }
        }

        $lastid = cmsCore::c('db')->get_last_id('cms_modules');

        if (cmsCore::request('show_all', 'int', 0)) {
            $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position, tpl)
                            VALUES (". $lastid .", 0, '". $position ."', '". cmsCore::c('config')->template ."')";
            cmsCore::c('db')->query($sql) ;
            
            $hidden_menu_ids = cmsCore::request('hidden_menu_ids', 'array_int', array());
            if ($hidden_menu_ids) {
                $hidden_menu_ids = cmsCore::arrayToYaml($hidden_menu_ids);
                cmsCore::c('db')->query("UPDATE cms_modules SET hidden_menu_ids='". $hidden_menu_ids ."' WHERE id = '". $lastid ."' LIMIT 1");
            }
        } else {
            $showin = cmsCore::request('showin', 'array', array());
            $showpos = cmsCore::request('showpos', 'array', array());
            if (count($showin) > 0) {
                foreach ($showin as $key=>$value) {
                    $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position, tpl)
                                    VALUES (". $lastid .", ". $value .", '". $showpos[$value] ."', '". cmsCore::c('config')->template ."')";
                    cmsCore::c('db')->query($sql) ;
                }
            }
        }

        cmsCore::addSessionMessage($_LANG['AD_MODULE_ADD_SITE'] , 'success');
        cmsCore::redirect('index.php?view=modules');
    }

    if ($do == 'add' || $do == 'edit') {
        $langs = cmsCore::getDirsList('/languages');
        
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_MODULE_ADD']);
            echo '<h3>'. $_LANG['AD_MODULE_ADD'] .'</h3>';
            $show_all = false;
        } else {
            if (cmsCore::inRequest('multiple')) {
                if (cmsCore::inRequest('item')) {
                    $_SESSION['editlist'] = cmsCore::request('item', 'array_int', array());
                } else {
                    cmsCore::addSessionMessage($_LANG['AD_NO_SELECT_OBJECTS'], 'error');
                    cmsCore::redirectBack();
                }
            }

            $ostatok = '';

            if (isset($_SESSION['editlist'])) {
                $item_id = array_shift($_SESSION['editlist']);
                if (count($_SESSION['editlist'])==0) {
                   unset($_SESSION['editlist']);
                } else {
                    $ostatok = '('. $_LANG['AD_NEXT_IN'] . count($_SESSION['editlist']) .')';
                }
            } else {
                $item_id = cmsCore::request('id', 'int', 0);
            }

            $mod = cmsCore::c('db')->get_fields('cms_modules', "id = '". $item_id ."'", '*');
            if (!$mod) { cmsCore::error404(); }
            
            $mod['hidden_menu_ids'] = cmsCore::yamlToArray($mod['hidden_menu_ids']);
            $mod['titles'] = cmsCore::yamlToArray($mod['titles']);
            
            $show_all = false;
            
            $default_position = cmsCore::c('db')->get_field('cms_modules_bind', "module_id='". $mod['id'] ."' AND menu_id=0 AND tpl='". cmsCore::c('config')->template ."'", 'position');
            
            if (!empty($default_position)) {
                $show_all = true;
                $mod['position'] = $default_position;
            }

            echo '<h3>'. $_LANG['AD_EDIT_MODULE'] . $ostatok .'</h3>';
            cpAddPathway($mod['name']);
        }

        $toolmenu[] = array( 'icon' => 'save.gif',   'title' => $_LANG['SAVE'],   'link' => 'javascript:document.addform.submit();' );
        $toolmenu[] = array( 'icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'javascript:history.go(-1);' );

        if (cmsCore::getArrVal($mod, 'is_external')) {
            $php_file = 'modules/'. $mod['content'] .'/backend.php';
            $xml_file = 'modules/'. $mod['content'] .'/backend.xml';
            if (file_exists($php_file) || file_exists($xml_file)) {
                $toolmenu[] = array( 'icon' => 'config.gif', 'title' => $_LANG['CONFIG_MODULE'], 'link' => '?view=modules&do=config&id='. $mod['id'] );
            }
        }

        cpToolMenu($toolmenu);
?>
    <form id="addform" name="addform" method="post" action="index.php">
        <input type="hidden" name="csrf_token" value="<?php echo cmsUser::getCsrfToken(); ?>" />
        <input type="hidden" name="view" value="modules" />

        <table class="table">
            <tr><td>
                <div class="panel panel-default">
                    <div class="panel-body">
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MODULE_TITLE']; ?> (<input type="checkbox" class="uittip" title="<?php echo $_LANG['AD_VIEW_TITLE'];?>" name="showtitle" <?php if ($mod['showtitle'] || $do == 'add') { echo 'checked="checked"'; } ?> value="1" />)</label>
                            <input type="text" id="title" class="form-control" style="width:100%" name="title" value="<?php echo htmlspecialchars($mod['title']);?>" />
                            <div class="help-block"><?php echo $_LANG['AD_VIEW_IN_SITE']; ?></div>
                        </div>
                        
                        <?php if (count($langs) > 1) { ?>
                            <label><?php echo $_LANG['AD_LANG_TITLES']; ?></label>
                            <?php foreach ($langs as $lang) { ?>
                                <div>
                                    <strong><?php echo $lang; ?>:</strong>
                                    <input name="titles[<?php echo $lang; ?>]" type="text" style="width:97%" value="<?php echo htmlspecialchars($mod['titles'][$lang]); ?>" placeholder="<?php echo $_LANG['AD_HINT_DEFAULT']; ?>" />
                                </div>
                            <?php } ?>
                            <div class="help-block"><?php echo $_LANG['AD_LANG_TITLES_HINT']; ?></div>
                        <?php } ?> 
                        
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MODULE_NAME']; ?></label>
                            <?php if (!isset($mod['user']) || @$mod['user'] == 1) { ?>
                                <input type="text" id="name" class="form-control" style="width:99%" name="name" value="<?php echo htmlspecialchars($mod['name']);?>" />
                            <?php } else { ?>
                                <input type="text" id="name" class="form-control" style="width:99%" name="" value="<?php echo @$mod['name'];?>" disabled="disabled" />
                                <input type="hidden" name="name" value="<?php echo htmlspecialchars($mod['name']);?>" />
                            <?php } ?>
                            <div class="help-block"><?php echo $_LANG['AD_SHOW_ADMIN']; ?></div>
                        </div>
                        
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_PREFIX_CSS']; ?></label>
                            <input type="text" id="css_prefix" class="form-control" style="width:154px" name="css_prefix" value="<?php echo @$mod['css_prefix'];?>" />
                        </div>
                        
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_DEFOLT_VIEW']; ?></label>
                            <?php
                                $pos = cpModulePositions(cmsConfig::getConfig('template'));
                            ?>
                            
                            <select id="position" class="form-control" style="width:100%" name="position">
                                <?php
                                    if ($pos){
                                        foreach($pos as $key=>$position) {
                                            if (@$mod['position']==$position) {
                                                echo '<option value="'.$position.'" selected>'.$position.'</option>';
                                            } else {
                                                echo '<option value="'.$position.'">'.$position.'</option>';
                                            }
                                        }
                                    }
                                ?>
                            </select>
                            
                            <div class="help-block">
                                <?php echo $_LANG['AD_POSITION_MUST_BE']; ?>
                                <?php if (file_exists(PATH .'/templates/'. cmsCore::c('config')->template .'/positions.jpg')) { ?>
                                    <a href="#myModal" role="button" class="btn btn-sm btn-default" data-toggle="modal"><?php echo $_LANG['AD_SEE_VISUALLY']; ?></a>
                                    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                                    <h4 class="modal-title" id="myModalLabel"><?php echo $_LANG['AD_TPL_POS']; ?></h4>
                                                </div>
                                                <div class="modal-body">
                                                    <img src="/templates/<?php echo cmsCore::c('config')->template; ?>/positions.jpg" alt="<?php echo $_LANG['AD_TPL_POS']; ?>" style="width:100%;height:auto;" />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MODULE_TEMPLATE']; ?></label>
                            <?php
                                $tpls = cmsAdmin::getModuleTemplates();
                            ?>
                            <select id="template" class="form-control" style="width:100%" name="template">
                                <?php
                                    foreach ($tpls as $tpl) {
                                        $selected = ($mod['template'] == $tpl || (!$mod['template'] && $tpl == 'module' )) ? 'selected="selected"' : '';
                                        echo '<option value="'. $tpl .'" '. $selected .'>'. $tpl .'</option>';
                                    }
                                ?>
                            </select>
                            <div class="help-block"><?php echo $_LANG['AD_FOLDER_MODULES'];?></div>
                        </div>
                        
                        <?php if ($do == 'add') { ?>
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MODULE_TYPE']; ?></label>
                            <select id="operate" class="form-control" style="width:100%" name="operate" onchange="checkDiv()" >
                                <option value="user" selected="selected"><?php echo $_LANG['AD_MODULE_TYPE_NEW'];?></option>
                                <option value="clone"><?php echo $_LANG['AD_MODULE_TYPE_COPY'];?></option>
                            </select>
                        </div>
                        <?php } ?>
                        
                        <?php if (!isset($mod['user']) || $mod['user'] == 1 || $do == 'add') { ?>
                        <div id="user_div" class="form-group">
                            <label><?php echo $_LANG['AD_MODULE_CONTENT']; ?></label>
                            <div><?php insertPanel(); ?></div>
                            <div><?php $inCore->insertEditor('content', $mod['content'], '250', '100%'); ?></div>
                        </div>
                        <?php } ?>
                        
                        <div id="clone_div" class="form-group" style="display:none;">
                            <label><?php echo $_LANG['AD_MODULE_COPY']; ?></label>
                            <select id="clone_id" class="form-control" style="width:100%" name="clone_id">
                                <?php
                                    echo $inCore->getListItems('cms_modules');
                                ?>
                            </select>
                            <label>
                                <input type="checkbox" name="del_orig" value="1" />
                                <?php echo $_LANG['AD_ORIGINAL_MODULE_DELETE'];?>
                            </label>
                        </div>
                    </div>
                </div>
            </td>

            <!-- боковая ячейка -->
            <td width="400" valign="top">
                <div class="uitabs">
                    <ul id="tabs">
                        <li><a href="#upr_publish"><span><?php echo $_LANG['AD_TAB_PUBLISH']; ?></span></a></li>
                        
                        <?php if ((($mod['is_external'] && $do == 'edit') || $do == 'add') && cmsCore::c('config')->cache) { ?>
                        <li><a href="#upr_cache"><span><?php echo $_LANG['AD_MODULE_CACHE']; ?></span></a></li>
                        <?php } ?>
                        
                        <li><a href="#upr_access"><span><?php echo $_LANG['AD_TAB_ACCESS']; ?></span></a></li>
                    </ul>
                    
                    <div id="upr_publish">
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="published" id="published" value="1" <?php if ($mod['published'] || $do=='add') { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_MODULE_PUBLIC'];?>
                            </label>
                        </div>
                        <div class="form-group">
                            <label>
                                <input name="show_all" id="show_all" type="checkbox" value="1"  onclick="checkGroupList()" <?php if ($show_all) { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_VIEW_ALL_PAGES'];?>
                            </label>
                        </div>
                        
                        <?php
                            if ($do == 'edit') {
                                $bind_sql = "SELECT * FROM cms_modules_bind WHERE module_id = ". $mod['id'] ." AND tpl = '". cmsConfig::getConfig('template') ."'";
                                $bind_res = cmsCore::c('db')->query($bind_sql);
                                $bind     = array();
                                $bind_pos = array();
                                while ($r = cmsCore::c('db')->fetch_assoc($bind_res)) {
                                    $bind[] = $r['menu_id'];
                                    $bind_pos[$r['menu_id']] = $r['position'];
                                }
                            }

                            $menu_sql = "SELECT * FROM cms_menu ORDER BY NSLeft, ordering";
                            $menu_res = cmsCore::c('db')->query($menu_sql) ;

                            $menu_items = array();

                            if (cmsCore::c('db')->num_rows($menu_res)) {
                                while ($item = cmsCore::c('db')->fetch_assoc($menu_res)) {
                                    if ($do == 'edit') {
                                        if (in_array($item['id'], $bind)) {
                                            $item['selected'] = true;
                                            $item['position'] = $bind_pos[$item['id']];
                                        }
                                    }
                                    
                                    $item['titles'] = cmsCore::yamlToArray($item['titles']);
                                    // переопределяем название пункта меню в зависимости от языка
                                    if (!empty($item['titles'][cmsCore::c('config')->lang])) {
                                        $item['title'] = $item['titles'][cmsCore::c('config')->lang];
                                    }
                                    
                                    $item['title'] = str_replace($_LANG['AD_ROOT_PAGES'], $_LANG['AD_MAIN'], $item['title']);
                                    $menu_items[] = $item;
                                }
                            }
                        ?>
                        
                        <div id="grp" class="form-group">
                            <label>
                                <span class="show_list"><?php echo $_LANG['AD_WHERE_MODULE_VIEW'];?></span>
                                <span class="hide_list"><?php echo $_LANG['AD_WHERE_MODULE_NOT_VIEW'];?></span>
                            </label>
                            <div style="height:400px;overflow: auto;border: solid 1px #999; padding:5px 10px; background: #FFF;">
                                <table class="table">
                                    <tr>
                                        <td colspan="2" height="25"><strong><?php echo $_LANG['AD_MENU'];?></strong></td>
                                        <td class="show_list" align="center" width="50"><strong><?php echo $_LANG['AD_POSITION'];?></strong></td>
                                    </tr>
                                    <?php foreach($menu_items as $i) { ?>
                                    <tr class="show_list">
                                        <td width="20" height="25">
                                            <input type="checkbox" name="showin[]" id="mid<?php echo $i['id']; ?>" value="<?php echo $i['id']; ?>" <?php if ($i['selected']){ ?>checked="checked"<?php } ?> onclick="$('#p<?php echo $i['id']; ?>').toggle()"/>
                                        </td>
                                        <td style="padding-left:<?php echo ($i['NSLevel'])*6-6; ?>px"><label for="mid<?php echo $i['id']; ?>"><?php echo $i['title']; ?></label></td>
                                        <td align="center">
                                            <select id="p<?php echo $i['id']; ?>" name="showpos[<?php echo $i['id']; ?>]" style="<?php if (!$i['selected']) { ?>display:none<?php } ?>">
                                                <?php foreach($pos as $position){ ?>
                                                    <option value="<?php echo $position; ?>" <?php if ($i['position']==$position){ ?>selected="selected"<?php } ?>><?php echo $position; ?></option>
                                                <?php } ?>
                                            </select>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                    <?php foreach($menu_items as $it) { ?>
                                    <tr class="hide_list">
                                        <td width="20" height="25">
                                            <input type="checkbox" name="hidden_menu_ids[]" id="hmid<?php echo $it['id']; ?>" value="<?php echo $it['id']; ?>" <?php if (in_array($it['id'], $mod['hidden_menu_ids'])){ ?>checked="checked"<?php } ?> />
                                        </td>
                                        <td style="padding-left:<?php echo ($it['NSLevel'])*6-6; ?>px"><label for="hmid<?php echo $it['id']; ?>"><?php echo $it['title']; ?></label></td>
                                    </tr>
                                    <?php } ?>
                                </table>
                            </div>
                            <label class="show_list">
                                <input type="checkbox" name="is_strict_bind" id="is_strict_bind" value="1" <?php if ($mod['is_strict_bind']) { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_DONT_VIEW']; ?>
                            </label>
                            <label class="hide_list">
                                <input type="checkbox" name="is_strict_bind_hidden" id="is_strict_bind_hidden" value="1" <?php if ($mod['is_strict_bind_hidden']) { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_EXCEPT_NESTED']; ?>
                            </label>
                        </div>
                    </div>
                    
                    <?php if ((($mod['is_external'] && $do == 'edit') || $do == 'add') && cmsCore::c('config')->cache) { ?>
                    <div id="upr_cache">
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_DO_MODULE_CACHE']; ?></label>
                            <select id="cache" class="form-control" style="width:100%" name="cache">
                                <option value="0" <?php if (!cmsCore::getArrVal($mod, 'cache')) { echo 'selected="selected"'; } ?>><?php echo $_LANG['NO']; ?></option>
                                <option value="1" <?php if (cmsCore::getArrVal($mod, 'cache')) { echo 'selected="selected"'; } ?>><?php echo $_LANG['YES']; ?></option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MODULE_CACHE_PERIOD']; ?></label>
                            <table class="table">
                                <tr>
                                    <td valign="top"  width="100">
                                        <input id="int_1" class="form-control" style="width:99%" name="cachetime" type="text" value="<?php echo cmsCore::getArrVal($mod, 'cachetime', 0); ?>"/>
                                    </td>
                                    <td valign="top" style="padding-left:5px">
                                        <select id="int_2" class="form-control" style="width:100%" name="cacheint">
                                            <option value="MINUTE"  <?php if(mb_strstr(cmsCore::getArrVal($mod, 'cacheint', 'MINUTES'), 'MINUTE')) { echo 'selected="selected"'; } ?>><?php echo cmsCore::spellCount(cmsCore::getArrVal($mod, 'cachetime', 0), $_LANG['MINUTE1'], $_LANG['MINUTE2'], $_LANG['MINUTE10'], false); ?></option>
                                            <option value="HOUR"  <?php if(mb_strstr(cmsCore::getArrVal($mod, 'cacheint', 'MINUTES'), 'HOUR')) { echo 'selected="selected"'; } ?>><?php echo cmsCore::spellCount(cmsCore::getArrVal($mod, 'cachetime', 0), $_LANG['HOUR1'], $_LANG['HOUR2'], $_LANG['HOUR10'], false); ?></option>
                                            <option value="DAY" <?php if(mb_strstr(cmsCore::getArrVal($mod, 'cacheint', 'MINUTES'), 'DAY')) { echo 'selected="selected"'; } ?>><?php echo cmsCore::spellCount(cmsCore::getArrVal($mod, 'cachetime', 0), $_LANG['DAY1'], $_LANG['DAY2'], $_LANG['DAY10'], false); ?></option>
                                            <option value="MONTH" <?php if(mb_strstr(cmsCore::getArrVal($mod, 'cacheint', 'MINUTES'), 'MONTH')) { echo 'selected="selected"'; } ?>><?php echo cmsCore::spellCount(cmsCore::getArrVal($mod, 'cachetime', 0), $_LANG['MONTH1'], $_LANG['MONTH2'], $_LANG['MONTH10'], false); ?></option>
                                        </select>
                                    </td>
                                </tr>
                            </table>
                            <div style="margin-top:15px">
                                <?php
                                    if ($do == 'edit') {
                                        $cache = cmsCore::c('cache')->get('modules', $mod['id'], $mod['content'], array(cmsCore::getArrVal($mod, 'cachetime', 1), cmsCore::getArrVal($mod, 'cacheint', 'MINUTES')));
                                        
                                        if (!empty($cache)){
                                            $kb = round(mb_strlen($cache)/1024, 2);
                                            unset($cache);
                                            echo '<a href="index.php?view=cache&component=modules&target='. $mod['content'] .'&target_id='. $mod['id'] .'">'. $_LANG['AD_MODULE_CACHE_DELETE'] .'</a> ('. $kb . $_LANG['SIZE_KB'] .')';
                                        } else {
                                            echo '<span style="color:gray">'. $_LANG['AD_NO_CACHE'] .'</span>';
                                        }
                                    }
                                ?>
                            </div>
                        </div>
                    </div>
                    <?php } ?>
                    
                    <div id="upr_access">
                        <div class="form-group">
                            <?php
                                $groups = cmsUser::getGroups();
                                $style  = 'disabled="disabled"';
                                $public = 'checked="checked"';

                                if ($do == 'edit') {
                                    if ($mod['access_list']) {
                                        $public = '';
                                        $style  = '';
                                        $access_list = $inCore->yamlToArray($mod['access_list']);
                                    }
                                }
                            ?>
                            <label>
                                <input name="is_public" type="checkbox" id="is_public" onclick="checkAccesList()" value="1" <?php echo $public; ?> />
                                <?php echo $_LANG['AD_SHARE']; ?>
                            </label>
                            <div class="help-block"><?php echo $_LANG['AD_IF_CHECKED']; ?></div>
                        </div>
                        
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_GROUPS_VIEW']; ?></label>
                            <?php
                                echo '<select style="width: 99%" name="allow_group[]" id="allow_group" size="6" multiple="multiple" '.$style.'>';

                                if ($groups) {
                                    foreach($groups as $group) {
                                        echo '<option value="'.$group['id'].'"';
                                        if ($do == 'edit' && $mod['access_list']) {
                                            if (in_array($group['id'], $access_list)) {
                                                echo 'selected="selected"';
                                            }
                                        }

                                        echo '>';
                                        echo $group['title'].'</option>';
                                    }
                                }

                                echo '</select>';
                            ?>
                            <div class="help-block"><?php echo $_LANG['AD_SELECT_MULTIPLE_CTRL']; ?></div>
                        </div>
                    </div>
                </div>
            </td></tr>
        </table>
        <p>
            <input type="submit" id="add_mod" class="btn btn-primary" name="add_mod" value="<?php echo $_LANG['SAVE']; ?>" />
            <input type="button" id="back" class="btn btn-default" name="back" value="<?php echo $_LANG['CANCEL']; ?>" onclick="window.history.back();" />
            <input type="hidden" id="do" name="do" <?php if ($do == 'add') { echo 'value="submit"'; } else { echo 'value="update"'; } ?> />
            <?php
                if ($do == 'edit') {
                    echo '<input name="id" type="hidden" value="'. $mod['id'] .'" />';
                }
            ?>
        </p>
    </form>
<?php
   }
}
Example #6
0
function users()
{
    header('X-Frame-Options: DENY');
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    global $_LANG;
    $model = new cms_model_users();
    // id пользователя
    $id = cmsCore::request('id', 'int', 0);
    // логин пользователя
    $login = cmsCore::strClear(urldecode(cmsCore::request('login', 'html', '')));
    $do = $inCore->do;
    $page = cmsCore::request('page', 'int', 1);
    $pagetitle = $inCore->getComponentTitle();
    if ($model->config['sw_search'] != 2) {
        $inPage->addPathway($pagetitle, '/users');
    }
    $inPage->setTitle($pagetitle);
    $inPage->setDescription($pagetitle);
    // js только авторизованным
    if ($inUser->id) {
        $inPage->addHeadJS('components/users/js/profile.js');
        $inPage->addHeadJsLang(array('CONFIRM_CLEAN_CAT', 'CHOOSE_RECIPIENT', 'SEND_TO_USER', 'FRIENDSHIP_OFFER', 'STOP_FRIENDLY', 'REALY_STOP_FRIENDLY', 'ENTER_STATUS', 'HAVE_JUST'));
    }
    //============================================================================//
    //========================= Список пользователей  ============================//
    //============================================================================//
    if ($do == 'view') {
        // если запрещен просмотр всех пользователей, 404
        if ($model->config['sw_search'] == 2) {
            cmsCore::error404();
        }
        //очищаем поисковые запросы если пришли со другой страницы
        if (!strstr(cmsCore::getBackURL(), '/users')) {
            cmsUser::sessionClearAll();
        }
        $stext = array();
        // Возможные входные переменные
        $name = cmsCore::getSearchVar('name');
        $city = cmsCore::getSearchVar('city');
        $hobby = cmsCore::getSearchVar('hobby');
        $gender = cmsCore::getSearchVar('gender');
        $orderby = cmsCore::request('orderby', array('karma', 'rating', 'regdate'), 'regdate');
        $orderto = cmsCore::request('orderto', array('asc', 'desc'), 'desc');
        $age_to = (int) cmsCore::getSearchVar('ageto', 'all');
        $age_fr = (int) cmsCore::getSearchVar('agefrom', 'all');
        $group_id = cmsCore::request('group_id', 'int', 0);
        // Флаг о показе только онлайн пользователей
        if (cmsCore::inRequest('online')) {
            cmsUser::sessionPut('usr_online', (bool) cmsCore::request('online', 'int'));
            $page = 1;
        }
        $only_online = cmsUser::sessionGet('usr_online');
        if ($only_online) {
            $stext[] = $_LANG['SHOWING_ONLY_ONLINE'];
        }
        ///////////////////////////////////////
        //////////Условия выборки//////////////
        ///////////////////////////////////////
        // группа
        if ($group_id) {
            $model->whereUserGroupIs($group_id);
            $link['group'] = '/users/group/' . $group_id;
            $_LANG['GROUP_SEARCH_NAME'] = cmsUser::getGroupTitle($group_id);
        }
        // Добавляем в выборку имя, если оно есть
        if ($name) {
            $model->whereNameIs($name);
            $stext[] = $_LANG['NAME'] . " &mdash; " . htmlspecialchars(stripslashes($name));
        }
        // Добавляем в выборку город, если он есть
        if ($city) {
            $model->whereCityIs($city);
            $stext[] = $_LANG['CITY'] . " &mdash; " . htmlspecialchars(stripslashes($city));
        }
        // Добавляем в выборку хобби, если есть
        if ($hobby) {
            $model->whereHobbyIs($hobby);
            $stext[] = $_LANG['HOBBY'] . " &mdash; " . htmlspecialchars(stripslashes($hobby));
        }
        // Добавляем в выборку пол, если есть
        if ($gender) {
            $model->whereGenderIs($gender);
            if ($gender == 'm') {
                $stext[] = $_LANG['MALE'];
            } else {
                $stext[] = $_LANG['FEMALE'];
            }
        }
        // Добавляем в выборку возраст, более
        if ($age_fr) {
            $model->whereAgeFrom($age_fr);
            $stext[] = $_LANG['NOT_YOUNG'] . " {$age_fr} " . $_LANG['YEARS'];
        }
        // Добавляем в выборку возраст, менее
        if ($age_to) {
            $model->whereAgeTo($age_to);
            $stext[] = $_LANG['NOT_OLD'] . " {$age_fr} " . $_LANG['YEARS'];
        }
        // Считаем общее количество согласно выборки
        $total = $model->getUsersCount($only_online);
        if ($total) {
            //устанавливаем сортировку
            $inDB->orderBy($orderby, $orderto);
            //устанавливаем номер текущей страницы и кол-во пользователей на странице
            $inDB->limitPage($page, $model->config['users_perpage']);
            // Загружаем пользователей согласно выборки
            $users = $model->getUsers($only_online);
        } else {
            $inDB->resetConditions();
        }
        $link['latest'] = '/users';
        $link['positive'] = '/users/positive.html';
        $link['rating'] = '/users/rating.html';
        if ($orderby == 'regdate') {
            $link['selected'] = 'latest';
        }
        if ($orderby == 'karma') {
            $link['selected'] = 'positive';
        }
        if ($orderby == 'rating') {
            $link['selected'] = 'rating';
        }
        $pagebar_link = '/users/' . $link['selected'] . '%page%.html';
        if ($group_id) {
            $link['selected'] = 'group';
            $pagebar_link = '/users/' . $link['selected'] . '/' . $group_id . '-%page%';
        }
        cmsPage::initTemplate('components', 'com_users_view')->assign('stext', $stext)->assign('orderby', $orderby)->assign('orderto', $orderto)->assign('users', $users)->assign('total', $total)->assign('only_online', $only_online)->assign('gender', $gender)->assign('name', stripslashes($name))->assign('city', stripslashes($city))->assign('hobby', stripslashes($hobby))->assign('age_to', $age_to)->assign('age_fr', $age_fr)->assign('cfg', $model->config)->assign('link', $link)->assign('pagebar', cmsPage::getPagebar($total, $page, $model->config['users_perpage'], $pagebar_link))->display('com_users_view.tpl');
    }
    //============================================================================//
    //======================= Редактирование профиля  ============================//
    //============================================================================//
    if ($do == 'editprofile') {
        // неавторизованным, не владельцам и не админам тут делать нечего
        if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $usr = $model->getUser($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $opt = cmsCore::request('opt', 'str', 'edit');
        // главного админа может редактировать только он сам
        if ($id == 1 && $inUser->id != $id) {
            cmsCore::error404();
        }
        // показываем форму
        if ($opt == 'edit') {
            $inPage->setTitle($_LANG['CONFIG_PROFILE'] . ' - ' . $usr['nickname']);
            $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
            $inPage->addPathway($_LANG['CONFIG_PROFILE']);
            $private_forms = array();
            if (isset($model->config['privforms'])) {
                if (is_array($model->config['privforms'])) {
                    foreach ($model->config['privforms'] as $form_id) {
                        $private_forms = array_merge($private_forms, cmsForm::getFieldsHtml($form_id, $usr['formsdata']));
                    }
                }
            }
            cmsPage::initTemplate('components', 'com_users_edit_profile')->assign('opt', $opt)->assign('usr', $usr)->assign('private_forms', $private_forms)->assign('cfg_forum', $inCore->loadComponentConfig('forum'))->assign('cfg', $model->config)->display('com_users_edit_profile.tpl');
            return;
        }
        // Если сохраняем профиль
        if ($opt == 'save') {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $errors = false;
            $users['nickname'] = cmsCore::request('nickname', 'str');
            if (mb_strlen($users['nickname']) < 2) {
                cmsCore::addSessionMessage($_LANG['SHORT_NICKNAME'], 'error');
                $errors = true;
            }
            cmsCore::loadModel('registration');
            $modreg = new cms_model_registration();
            if (!$inUser->is_admin) {
                if ($modreg->getBadNickname($users['nickname'])) {
                    cmsCore::addSessionMessage($_LANG['ERR_NICK_EXISTS'], 'error');
                    $errors = true;
                }
            }
            $profiles['gender'] = cmsCore::request('gender', 'str');
            $profiles['city'] = cmsCore::request('city', 'str');
            if (mb_strlen($profiles['city']) > 50) {
                cmsCore::addSessionMessage($_LANG['LONG_CITY_NAME'], 'error');
                $errors = true;
            }
            $users['email'] = cmsCore::request('email', 'email');
            if (!$users['email']) {
                cmsCore::addSessionMessage($_LANG['REALY_ADRESS_EMAIL'], 'error');
                $errors = true;
            }
            if ($usr['email'] != $users['email']) {
                $is_set_email = $inDB->get_field('cms_users', "email='{$users['email']}'", 'id');
                if ($is_set_email) {
                    cmsCore::addSessionMessage($_LANG['ADRESS_EMAIL_IS_BUSY'], 'error');
                    $errors = true;
                } else {
                    // формируем токен
                    $token = md5($usr['email'] . uniqid() . microtime());
                    $inDB->insert('cms_users_activate', array('user_id' => $inUser->id, 'pubdate' => date("Y-m-d H:i:s"), 'code' => $token));
                    $codelink = HOST . '/users/change_email/' . $token . '/' . $users['email'];
                    // по старому адресу высылаем письмо с подтверждением
                    $letter = cmsCore::getLanguageTextFile('change_email');
                    $letter = str_replace(array('{nickname}', '{codelink}'), array($inUser->nickname, $codelink), $letter);
                    cmsCore::mailText($usr['email'], '', $letter);
                    cmsCore::addSessionMessage(sprintf($_LANG['YOU_CHANGE_EMAIL'], $usr['email']), 'info');
                    // email не меняем
                    $users['email'] = $usr['email'];
                }
            }
            $profiles['showphone'] = cmsCore::request('showphone', 'int', 0);
            $profiles['showmail'] = cmsCore::request('showmail', 'int');
            $profiles['email_newmsg'] = cmsCore::request('email_newmsg', 'int');
            $profiles['showbirth'] = cmsCore::request('showbirth', 'int');
            $profiles['description'] = cmsCore::request('description', 'str', '');
            $users['birthdate'] = (int) $_REQUEST['birthdate']['year'] . '-' . (int) $_REQUEST['birthdate']['month'] . '-' . (int) $_REQUEST['birthdate']['day'];
            $profiles['signature'] = $inDB->escape_string(cmsCore::badTagClear(cmsCore::request('signature', 'html', '')));
            $profiles['signature_html'] = $inDB->escape_string(cmsCore::parseSmiles(cmsCore::request('signature', 'html', ''), true));
            $profiles['allow_who'] = cmsCore::request('allow_who', 'str');
            if (!preg_match('/^([a-zA-Z]+)$/ui', $profiles['allow_who'])) {
                $errors = true;
            }
            $users['icq'] = cmsCore::request('icq', 'str', '');
            $profiles['showicq'] = cmsCore::request('showicq', 'int');
            $profiles['cm_subscribe'] = cmsCore::request('cm_subscribe', 'str');
            if (!preg_match('/^([a-zA-Z]+)$/ui', $profiles['cm_subscribe'])) {
                $errors = true;
            }
            $users['phone'] = cmsCore::request('phone', 'int', 0);
            // получаем данные форм
            $profiles['formsdata'] = '';
            if (isset($model->config['privforms'])) {
                if (is_array($model->config['privforms'])) {
                    foreach ($model->config['privforms'] as $form_id) {
                        $form_input = cmsForm::getFieldsInputValues($form_id);
                        $profiles['formsdata'] .= $inDB->escape_string(cmsCore::arrayToYaml($form_input['values']));
                        // Проверяем значения формы
                        foreach ($form_input['errors'] as $field_error) {
                            if ($field_error) {
                                cmsCore::addSessionMessage($field_error, 'error');
                                $errors = true;
                            }
                        }
                    }
                }
            }
            if ($errors) {
                cmsCore::redirectBack();
            }
            $inDB->update('cms_user_profiles', cmsCore::callEvent('UPDATE_USER_PROFILES', array_merge(array('id' => $usr['pid'], 'user_id' => $usr['id']), $profiles)), $usr['pid']);
            $inDB->update('cms_users', cmsCore::callEvent('UPDATE_USER_USERS', array_merge(array('id' => $usr['id']), $users)), $usr['id']);
            cmsCore::addSessionMessage($_LANG['PROFILE_SAVED'], 'info');
            cmsCore::redirect(cmsUser::getProfileURL($usr['login']));
        }
        if ($opt == 'changepass') {
            $errors = false;
            $oldpass = cmsCore::request('oldpass', 'str');
            $newpass = cmsCore::request('newpass', 'str');
            $newpass2 = cmsCore::request('newpass2', 'str');
            if ($inUser->password != md5($oldpass)) {
                cmsCore::addSessionMessage($_LANG['OLD_PASS_WRONG'], 'error');
                $errors = true;
            }
            if ($newpass != $newpass2) {
                cmsCore::addSessionMessage($_LANG['WRONG_PASS'], 'error');
                $errors = true;
            }
            if ($oldpass && $newpass && $newpass2 && mb_strlen($newpass) < 6) {
                cmsCore::addSessionMessage($_LANG['PASS_SHORT'], 'error');
                $errors = true;
            }
            if ($errors) {
                cmsCore::redirectBack();
            }
            cmsCore::callEvent('UPDATE_USER_PASSWORD', array('user_id' => $usr['id'], 'oldpass' => $oldpass, 'newpass' => $newpass));
            $sql = "UPDATE cms_users SET password='******' WHERE id = '{$id}' AND password='******'";
            $inDB->query($sql);
            cmsCore::addSessionMessage($_LANG['PASS_CHANGED'], 'info');
            cmsCore::redirect(cmsUser::getProfileURL($inUser->login));
        }
    }
    //============================================================================//
    //============================= Просмотр профиля  ============================//
    //============================================================================//
    if ($do == 'profile') {
        $inPage->addHeadJsLang(array('NEW_POST_ON_WALL', 'CONFIRM_DEL_POST_ON_WALL'));
        // если просмотр профиля гостям запрещен
        if (!$inUser->id && !$model->config['sw_guest']) {
            cmsUser::goToLogin();
        }
        if (is_numeric($login)) {
            cmsCore::error404();
        }
        $usr = $model->getUser($login);
        if (!$usr) {
            cmsCore::error404();
        }
        $myprofile = $inUser->id == $usr['id'];
        $inPage->setTitle($usr['nickname']);
        $inPage->addPathway($usr['nickname']);
        // просмотр профиля запрещен
        if (!cmsUser::checkUserContentAccess($usr['allow_who'], $usr['id'])) {
            cmsPage::initTemplate('components', 'com_users_not_allow')->assign('is_auth', $inUser->id)->assign('usr', $usr)->display('com_users_not_allow.tpl');
            return;
        }
        // Профиль удален
        if ($usr['is_deleted']) {
            cmsPage::initTemplate('components', 'com_users_deleted.tpl')->assign('usr', $usr)->assign('is_admin', $inUser->is_admin)->assign('others_active', $inDB->rows_count('cms_users', "login='******'login']}' AND is_deleted=0", 1))->display('com_users_deleted.tpl');
            return;
        }
        // Данные о друзьях
        $usr['friends_total'] = cmsUser::getFriendsCount($usr['id']);
        $usr['friends'] = cmsUser::getFriends($usr['id']);
        // очищать сессию друзей если в своем профиле и количество друзей из базы не совпадает с количеством друзей в сессии
        if ($myprofile && sizeof($usr['friends']) != $usr['friends_total']) {
            cmsUser::clearSessionFriends();
        }
        // обрезаем список
        $usr['friends'] = array_slice($usr['friends'], 0, 6);
        // выясняем друзья ли мы с текущим пользователем
        $usr['isfriend'] = !$myprofile ? cmsUser::isFriend($usr['id']) : false;
        // награды пользователя
        $usr['awards'] = $model->config['sw_awards'] ? $model->getUserAwards($usr['id']) : false;
        // стена
        if ($model->config['sw_wall']) {
            $inDB->limitPage(1, $model->config['wall_perpage']);
            $usr['wall_html'] = cmsUser::getUserWall($usr['id'], 'users', $myprofile, $inUser->is_admin);
        }
        // можно ли пользователю изменять карму
        $usr['can_change_karma'] = $model->isUserCanChangeKarma($usr['id']) && $inUser->id;
        // Фотоальбомы пользователя
        if ($model->config['sw_photo']) {
            $usr['albums'] = $model->getPhotoAlbums($usr['id'], $usr['isfriend'], !$inCore->isComponentEnable('photos'));
            $usr['albums_total'] = sizeof($usr['albums']);
            $usr['albums_show'] = 6;
            if ($usr['albums_total'] > $usr['albums_show']) {
                array_splice($usr['albums'], $usr['albums_show']);
            }
        }
        $usr['board_count'] = $model->config['sw_board'] ? $inDB->rows_count('cms_board_items', "user_id='{$usr['id']}' AND published=1") : 0;
        $usr['comments_count'] = $model->config['sw_comm'] ? $inDB->rows_count('cms_comments', "user_id='{$usr['id']}' AND published=1") : 0;
        $usr['forum_count'] = $model->config['sw_forum'] ? $inDB->rows_count('cms_forum_posts', "user_id = '{$usr['id']}'") : 0;
        $usr['files_count'] = $model->config['sw_files'] ? $inDB->rows_count('cms_user_files', "user_id = '{$usr['id']}'") : 0;
        $cfg_reg = $inCore->loadComponentConfig('registration');
        $usr['invites_count'] = $inUser->id && $myprofile && $cfg_reg['reg_type'] == 'invite' ? $model->getUserInvitesCount($inUser->id) : 0;
        $usr['blog'] = $model->config['sw_blogs'] ? $inDB->get_fields('cms_blogs', "user_id = '{$usr['id']}' AND owner = 'user'", 'title, seolink') : false;
        $usr['form_fields'] = array();
        if (is_array($model->config['privforms'])) {
            foreach ($model->config['privforms'] as $form_id) {
                $usr['form_fields'] = array_merge($usr['form_fields'], cmsForm::getFieldsValues($form_id, $usr['formsdata']));
            }
        }
        if ($usr['city']) {
            cmsCore::loadModel('geo');
            $geo = new cms_model_geo();
            $city_parents = $geo->getCityParents($usr['city']);
            if ($city_parents) {
                $usr['country'] = $city_parents['country_name'];
            }
        }
        $plugins = $model->getPluginsOutput($usr);
        cmsPage::initTemplate('components', 'com_users_profile.tpl')->assign('usr', $usr)->assign('plugins', $plugins)->assign('cfg', $model->config)->assign('myprofile', $myprofile)->assign('cfg_forum', $inCore->loadComponentConfig('forum'))->assign('is_admin', $inUser->is_admin)->assign('is_auth', $inUser->id)->display('com_users_profile.tpl');
    }
    //============================================================================//
    //============================= Список сообщений  ============================//
    //============================================================================//
    if ($do == 'messages') {
        if (!$model->config['sw_msg']) {
            cmsCore::error404();
        }
        if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) {
            cmsUser::goToLogin();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['MY_MESS']);
        $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
        $inPage->addPathway($_LANG['MY_MESS'], '/users/' . $id . '/messages.html');
        include 'components/users/messages.php';
    }
    //============================================================================//
    //=========================== Отправка сообщения  ============================//
    //============================================================================//
    if ($do == 'sendmessage') {
        if (!$model->config['sw_msg']) {
            cmsCore::halt();
        }
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id || $inUser->id == $id && !cmsCore::inRequest('massmail') && !cmsCore::request('send_to_group', 'int', 0)) {
            cmsCore::halt();
        }
        if (!cmsCore::inRequest('gosend')) {
            $replyid = cmsCore::request('replyid', 'int', 0);
            if ($replyid) {
                $msg = $model->getReplyMessage($replyid, $inUser->id);
                if (!$msg) {
                    cmsCore::halt();
                }
            }
            $inPage->setRequestIsAjax();
            cmsPage::initTemplate('components', 'com_users_messages_add')->assign('msg', isset($msg) ? $msg : array())->assign('is_reply_user', $replyid)->assign('id', $id)->assign('bbcodetoolbar', cmsPage::getBBCodeToolbar('message'))->assign('smilestoolbar', cmsPage::getSmilesPanel('message'))->assign('groups', $inUser->is_admin ? cmsUser::getGroups(true) : array())->assign('friends', cmsUser::getFriends($inUser->id))->assign('id_admin', $inUser->is_admin)->display('com_users_messages_add.tpl');
            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }
        if (cmsCore::inRequest('gosend')) {
            // Кому отправляем
            $usr = cmsUser::getShortUserData($id);
            if (!$usr) {
                cmsCore::halt();
            }
            $message = cmsCore::parseSmiles(cmsCore::request('message', 'html', ''), true);
            if (mb_strlen($message) < 2) {
                cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ERR_SEND_MESS']));
            }
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $output = cmsCore::callEvent('USER_SEND_MESSEDGE', array('text' => $message, 'to_id' => $id));
            $message = $output['text'];
            $id = $output['to_id'];
            $send_to_group = cmsCore::request('send_to_group', 'int', 0);
            $group_id = cmsCore::request('group_id', 'int', 0);
            //
            // Обычная отправка (1 получатель)
            //
            if (!cmsCore::inRequest('massmail') && !$send_to_group) {
                //отправляем сообщение
                $msg_id = cmsUser::sendMessage($inUser->id, $id, $message);
                // отправляем уведомление на email если нужно
                $model->sendNotificationByEmail($id, $inUser->id, $msg_id);
                cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['SEND_MESS_OK']));
            }
            //
            // далее идут массовые рассылки, доступные только админам
            //
            if (!$inUser->is_admin) {
                cmsCore::halt();
            }
            // отправить всем: получаем список всех пользователей
            if (cmsCore::inRequest('massmail')) {
                $userlist = cmsUser::getAllUsers();
                // проверяем что есть кому отправлять
                if (!$userlist) {
                    cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['ERR_SEND_MESS']));
                }
                $count = array();
                // отправляем всем по списку
                foreach ($userlist as $usr) {
                    $count[] = cmsUser::sendMessage(USER_MASSMAIL, $usr['id'], $message);
                }
                cmsCore::jsonOutput(array('error' => false, 'text' => sprintf($_LANG['SEND_MESS_ALL_OK'], sizeof($count))));
            }
            // отправить группе: получаем список членов группы
            if ($send_to_group) {
                $count = cmsUser::sendMessageToGroup(USER_MASSMAIL, $group_id, $message);
                $success_msg = sprintf($_LANG['SEND_MESS_GROUP_OK'], $count, cmsUser::getGroupTitle($group_id));
                cmsCore::jsonOutput(array('error' => false, 'text' => $success_msg));
            }
        }
    }
    //============================================================================//
    //============================= Удаление сообщения  ==========================//
    //============================================================================//
    if ($do == 'delmessage') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$model->config['sw_msg']) {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $msg = $inDB->get_fields('cms_user_msg', "id='{$id}'", '*');
        if (!$msg) {
            cmsCore::halt();
        }
        $can_delete = $inUser->id == $msg['to_id'] || $inUser->id == $msg['from_id'] ? true : false;
        if (!$can_delete && !$inUser->is_admin) {
            cmsCore::halt();
        }
        // Сообщения с from_id < 0
        if ($msg['from_id'] < 0) {
            $inDB->query("DELETE FROM cms_user_msg WHERE id = '{$id}' LIMIT 1");
            $info_text = $_LANG['MESS_NOTICE_DEL_OK'];
        }
        // мне сообщение от пользователя
        if ($msg['to_id'] == $inUser->id && $msg['from_id'] > 0) {
            $inDB->query("UPDATE cms_user_msg SET to_del=1 WHERE id='{$id}'");
            $info_text = $_LANG['MESS_DEL_OK'];
        }
        // от меня сообщение
        if ($msg['from_id'] == $inUser->id && !$msg['is_new']) {
            $inDB->query("UPDATE cms_user_msg SET from_del=1 WHERE id='{$id}'");
            $info_text = $_LANG['MESS_DEL_OK'];
        }
        // отзываем сообщение
        if ($msg['from_id'] == $inUser->id && $msg['is_new']) {
            $inDB->query("DELETE FROM cms_user_msg WHERE id = '{$id}' LIMIT 1");
            $info_text = $_LANG['MESS_BACK_OK'];
        }
        // удаляем сообщения, которые удалены с двух сторон
        $inDB->query("DELETE FROM cms_user_msg WHERE to_del=1 AND from_del=1");
        cmsCore::jsonOutput(array('error' => false, 'text' => $info_text));
    }
    //============================================================================//
    //=========================== Удаление сообщений  ============================//
    //============================================================================//
    if ($do == 'delmessages') {
        if (!$model->config['sw_msg']) {
            cmsCore::error404();
        }
        if ($inUser->id != $id && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $opt = cmsCore::request('opt', 'str', 'in');
        if ($opt == 'notices') {
            $inDB->query("DELETE FROM cms_user_msg WHERE to_id = '{$id}' AND from_id < 0");
        } else {
            $del_flag = $opt == 'in' ? 'to_del' : 'from_del';
            $id_flag = $opt == 'in' ? 'to_id' : 'from_id';
            $inDB->query("UPDATE cms_user_msg SET {$del_flag}=1 WHERE {$id_flag}='{$id}'");
            $inDB->query("DELETE FROM cms_user_msg WHERE to_del=1 AND from_del=1");
        }
        cmsCore::addSessionMessage($_LANG['MESS_ALL_DEL_OK'], 'info');
        cmsCore::redirectBack();
    }
    //============================================================================//
    //============================= Загрузка аватара  ============================//
    //============================================================================//
    if ($do == 'avatar') {
        if (!$inUser->id || $inUser->id && $inUser->id != $id) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['LOAD_AVATAR']);
        $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
        $inPage->addPathway($_LANG['LOAD_AVATAR']);
        if (cmsCore::inRequest('upload')) {
            cmsCore::loadClass('upload_photo');
            $inUploadPhoto = cmsUploadPhoto::getInstance();
            // Выставляем конфигурационные параметры
            $inUploadPhoto->upload_dir = PATH . '/images/';
            $inUploadPhoto->dir_medium = 'users/avatars/';
            $inUploadPhoto->dir_small = 'users/avatars/small/';
            $inUploadPhoto->small_size_w = $model->config['smallw'];
            $inUploadPhoto->medium_size_w = $model->config['medw'];
            $inUploadPhoto->medium_size_h = $model->config['medh'];
            $inUploadPhoto->is_watermark = false;
            $inUploadPhoto->input_name = 'picture';
            $file = $inUploadPhoto->uploadPhoto($inUser->orig_imageurl);
            if (!$file) {
                cmsCore::addSessionMessage('<strong>' . $_LANG['ERROR'] . ':</strong> ' . cmsCore::uploadError() . '!', 'error');
                cmsCore::redirect('/users/' . $id . '/avatar.html');
            }
            $sql = "UPDATE cms_user_profiles SET imageurl = '{$file['filename']}' WHERE user_id = '{$id}' LIMIT 1";
            $inDB->query($sql);
            // очищаем предыдущую запись о смене аватара
            cmsActions::removeObjectLog('add_avatar', $id);
            // выводим сообщение в ленту
            cmsActions::log('add_avatar', array('object' => '', 'object_url' => '', 'object_id' => $id, 'target' => '', 'target_url' => '', 'description' => '<a href="' . cmsUser::getProfileURL($inUser->login) . '" class="act_usr_ava">
								   <img border="0" src="/images/users/avatars/small/' . $file['filename'] . '">
								</a>'));
            cmsCore::redirect(cmsUser::getProfileURL($inUser->login));
        } else {
            cmsPage::initTemplate('components', 'com_users_avatar_upload')->assign('id', $id)->display('com_users_avatar_upload.tpl');
        }
    }
    //============================================================================//
    //============================= Библиотека аватаров  =========================//
    //============================================================================//
    if ($do == 'select_avatar') {
        if (!$inUser->id || $inUser->id && $inUser->id != $id) {
            cmsCore::error404();
        }
        $avatars_dir = PATH . "/images/users/avatars/library";
        $avatars_dir_rel = "/images/users/avatars/library";
        $avatars_dir_handle = opendir($avatars_dir);
        $avatars = array();
        while ($nextfile = readdir($avatars_dir_handle)) {
            if ($nextfile != '.' && $nextfile != '..' && (mb_strstr($nextfile, '.gif') || mb_strstr($nextfile, '.jpg') || mb_strstr($nextfile, '.jpeg') || mb_strstr($nextfile, '.png'))) {
                $avatars[] = $nextfile;
            }
        }
        closedir($avatars_dir_handle);
        if (!cmsCore::inRequest('set_avatar')) {
            $inPage->setTitle($_LANG['SELECT_AVATAR']);
            $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
            $inPage->addPathway($_LANG['SELECT_AVATAR']);
            $perpage = 20;
            $total = sizeof($avatars);
            $avatars = array_slice($avatars, ($page - 1) * $perpage, $perpage);
            cmsPage::initTemplate('components', 'com_users_avatars')->assign('userid', $id)->assign('avatars', $avatars)->assign('avatars_dir', $avatars_dir_rel)->assign('page', $page)->assign('perpage', $perpage)->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, '/users/%user_id%/select-avatar-%page%.html', array('user_id' => $id)))->display('com_users_avatars.tpl');
        } else {
            $avatar_id = cmsCore::request('avatar_id', 'int', 0);
            $file = $avatars[$avatar_id];
            if (file_exists($avatars_dir . '/' . $file)) {
                $uploaddir = PATH . '/images/users/avatars/';
                $realfile = $file;
                $filename = md5($realfile . '-' . $id . '-' . time()) . '.jpg';
                $uploadfile = $avatars_dir . '/' . $realfile;
                $uploadavatar = $uploaddir . $filename;
                $uploadthumb = $uploaddir . 'small/' . $filename;
                if ($inUser->orig_imageurl && $inUser->orig_imageurl != 'nopic.jpg') {
                    @unlink(PATH . '/images/users/avatars/' . $inUser->orig_imageurl);
                    @unlink(PATH . '/images/users/avatars/small/' . $inUser->orig_imageurl);
                }
                cmsCore::includeGraphics();
                copy($uploadfile, $uploadavatar);
                @img_resize($uploadfile, $uploadthumb, $model->config['smallw'], $model->config['smallw']);
                $sql = "UPDATE cms_user_profiles SET imageurl = '{$filename}' WHERE user_id = '{$id}' LIMIT 1";
                $inDB->query($sql);
                // очищаем предыдущую запись о смене аватара
                cmsActions::removeObjectLog('add_avatar', $id);
                // выводим сообщение в ленту
                cmsActions::log('add_avatar', array('object' => '', 'object_url' => '', 'object_id' => $id, 'target' => '', 'target_url' => '', 'description' => '<a href="' . cmsUser::getProfileURL($inUser->login) . '" class="act_usr_ava">
										<img border="0" src="/images/users/avatars/small/' . $filename . '">
									</a>'));
            }
            cmsCore::redirect(cmsUser::getProfileURL($inUser->login));
        }
    }
    //============================================================================//
    //======================== Работа с фотографиями  ============================//
    //============================================================================//
    if ($do == 'photos') {
        if (!$model->config['sw_photo']) {
            cmsCore::error404();
        }
        $pdo = cmsCore::request('pdo', 'str', '');
        include 'components/users/photos.php';
    }
    //============================================================================//
    //============================= Друзья пользователя  =========================//
    //============================================================================//
    if ($do == 'friendlist') {
        if (!$inUser->id) {
            cmsUser::goToLogin();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $perpage = 10;
        $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
        $inPage->addPathway($_LANG['FRIENDS']);
        $inPage->setTitle($_LANG['FRIENDS']);
        // все друзья
        $friends = cmsUser::getFriends($usr['id']);
        // их общее количество
        $total = count($friends);
        // получаем только нужных на странице
        $friends = array_slice($friends, ($page - 1) * $perpage, $perpage);
        cmsPage::initTemplate('components', 'com_users_friends')->assign('friends', $friends)->assign('usr', $usr)->assign('myprofile', $id == $inUser->id)->assign('total', $total)->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, 'javascript:centerLink(\'/users/' . $id . '/friendlist%page%.html\')'))->display('com_users_friends.tpl');
    }
    //============================================================================//
    //============================= Запрос на дружбу  ============================//
    //============================================================================//
    if ($do == 'addfriend') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id || $inUser->id == $id) {
            cmsCore::halt();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::halt();
        }
        cmsUser::clearSessionFriends();
        if (cmsUser::isFriend($id)) {
            cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['YOU_ARE_BE_FRIENDS']));
        }
        // проверяем был ли ранее запрос на дружбу
        // если был, то делаем accept запросу
        $is_need_accept_id = cmsUser::getFriendFieldId($id, 0, 'to_me');
        if ($is_need_accept_id) {
            $inDB->query("UPDATE cms_user_friends SET is_accepted = 1 WHERE id = '{$is_need_accept_id}'");
            //регистрируем событие
            cmsActions::log('add_friend', array('object' => $inUser->nickname, 'user_id' => $usr['id'], 'object_url' => cmsUser::getProfileURL($inUser->login), 'object_id' => $is_need_accept_id, 'target' => '', 'target_url' => '', 'target_id' => 0, 'description' => ''));
            cmsCore::callEvent('USER_ACCEPT_FRIEND', $id);
            cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['ADD_FRIEND_OK'] . $usr['nickname']));
        }
        // Если пользователь пытается добавиться в друзья к
        // пользователю, к которому уже отправил запрос
        if (cmsUser::getFriendFieldId($id, 0, 'from_me')) {
            cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['ADD_TO_FRIEND_SEND_ERR']));
        }
        // Мы вообще не друзья с пользователем, создаем запрос
        cmsUser::addFriend($id);
        cmsUser::sendMessage(USER_UPDATER, $id, sprintf($_LANG['RECEIVED_F_O'], cmsUser::getProfileLink($inUser->login, $inUser->nickname), '<a class="ajaxlink" href="javascript:void(0)" onclick="users.acceptFriend(' . $inUser->id . ', this);return false;">' . $_LANG['ACCEPT'] . '</a>', '<a class="ajaxlink" href="javascript:void(0)" onclick="users.rejectFriend(' . $inUser->id . ', this);return false;">' . $_LANG['REJECT'] . '</a>'));
        cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['ADD_TO_FRIEND_SEND']));
    }
    //============================================================================//
    //============================= Прекращение дружбы  ==========================//
    //============================================================================//
    if ($do == 'delfriend') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id || $inUser->id == $id) {
            cmsCore::halt();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        if (cmsUser::getFriendFieldId($id)) {
            $is_accepted_friend = cmsUser::isFriend($id);
            if (cmsUser::deleteFriend($id)) {
                // Если подтвержденный друг
                if ($is_accepted_friend) {
                    cmsCore::jsonOutput(array('error' => false, 'text' => $usr['nickname'] . $_LANG['DEL_FRIEND']));
                } else {
                    cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['REJECT_FRIEND'] . $usr['nickname']));
                }
            } else {
                cmsCore::halt();
            }
        } else {
            cmsCore::halt();
        }
    }
    //============================================================================//
    //============================= История кармы  ===============================//
    //============================================================================//
    if ($do == 'karma') {
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['KARMA_HISTORY']);
        $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
        $inPage->addPathway($_LANG['KARMA_HISTORY']);
        cmsPage::initTemplate('components', 'com_users_karma')->assign('karma', $model->getUserKarma($usr['id']))->assign('usr', $usr)->display('com_users_karma.tpl');
    }
    //============================================================================//
    //============================= Изменение кармы  =============================//
    //============================================================================//
    if ($do == 'votekarma') {
        if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
            cmsCore::halt();
        }
        if (!$inUser->id) {
            cmsCore::halt();
        }
        $points = cmsCore::request('sign', 'str', 'plus') == 'plus' ? 1 : -1;
        $to = cmsCore::request('to', 'int', 0);
        $user = cmsUser::getShortUserData($to);
        if (!$user) {
            cmsCore::halt();
        }
        if (!$model->isUserCanChangeKarma($to)) {
            cmsCore::halt();
        }
        cmsCore::halt(cmsUser::changeKarmaUser($to, $points));
    }
    //============================================================================//
    //======================= Наградить пользователя  ============================//
    //============================================================================//
    if ($do == 'giveaward') {
        if (!$inUser->is_admin) {
            cmsCore::error404();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['AWARD_USER']);
        $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
        $inPage->addPathway($_LANG['AWARD']);
        if (!cmsCore::inRequest('gosend')) {
            cmsPage::initTemplate('components', 'com_users_awards_give')->assign('usr', $usr)->assign('awardslist', cmsUser::getAwardsImages())->display('com_users_awards_give.tpl');
        } else {
            $award['title'] = cmsCore::request('title', 'str', $_LANG['AWRD']);
            $award['description'] = cmsCore::request('description', 'str', '');
            $award['imageurl'] = cmsCore::request('imageurl', 'str', '');
            $award['from_id'] = $inUser->id;
            $award['id'] = 0;
            cmsUser::giveAward($award, $id);
            cmsCore::redirect(cmsUser::getProfileURL($usr['login']));
        }
    }
    //============================================================================//
    //============================= Удаление награды  ============================//
    //============================================================================//
    if ($do == 'delaward') {
        $aw = $inDB->get_fields('cms_user_awards', "id = '{$id}'", '*');
        if (!$aw) {
            cmsCore::error404();
        }
        if (!$inUser->id || $inUser->id != $aw['user_id'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $inDB->delete('cms_user_awards', "id = '{$id}'", 1);
        cmsActions::removeObjectLog('add_award', $id);
        cmsCore::redirectBack();
    }
    //============================================================================//
    //============================= Награды на сайте  ============================//
    //============================================================================//
    if ($do == 'awardslist') {
        $inPage->setTitle($_LANG['SITE_AWARDS']);
        $inPage->addPathway($_LANG['SITE_AWARDS']);
        $awards = cmsUser::getAutoAwards();
        if (!$awards) {
            cmsCore::error404();
        }
        foreach ($awards as $aw) {
            //Перебираем все награды и ищем пользователей с текущей наградой
            $sql = "SELECT u.id as id, u.nickname as nickname, u.login as login, IFNULL(p.gender, 'm') as gender\r\n                 FROM cms_user_awards aw\r\n                 LEFT JOIN cms_users u ON u.id = aw.user_id\r\n                 LEFT JOIN cms_user_profiles p ON p.user_id = u.id\r\n                 WHERE aw.award_id = '{$aw['id']}'";
            $rs = $inDB->query($sql);
            $aw['uhtml'] = '';
            if ($inDB->num_rows($rs)) {
                while ($user = $inDB->fetch_assoc($rs)) {
                    $aw['uhtml'] .= cmsUser::getGenderLink($user['id'], $user['nickname'], $user['gender'], $user['login']) . ', ';
                }
                $aw['uhtml'] = rtrim($aw['uhtml'], ', ');
            } else {
                $aw['uhtml'] = $_LANG['NOT_USERS_WITH_THIS_AWARD'];
            }
            $aws[] = $aw;
        }
        cmsPage::initTemplate('components', 'com_users_awards_site')->assign('aws', $aws)->display('com_users_awards_site.tpl');
    }
    //============================================================================//
    //============================= Удаление профиля  ============================//
    //============================================================================//
    if ($do == 'delprofile') {
        // неавторизованным тут делать нечего
        if (!$inUser->id) {
            cmsCore::error404();
        }
        // есть ли удаляемый профиль
        $data = cmsUser::getShortUserData($id);
        if (!$data) {
            cmsCore::error404();
        }
        // владелец профиля или админ
        if ($inUser->is_admin) {
            // могут ли администраторы удалять профиль
            if (!cmsUser::isAdminCan('admin/users', cmsUser::getAdminAccess())) {
                cmsCore::error404();
            }
            // администратор сам себя не удалит
            if ($inUser->id == $data['id']) {
                cmsCore::error404();
            }
        } else {
            // удаляем только свой профиль
            if ($inUser->id != $data['id']) {
                cmsCore::error404();
            }
        }
        if (isset($_POST['csrf_token'])) {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $model->deleteUser($id);
            if (!$inUser->is_admin) {
                session_destroy();
                cmsCore::redirect('/logout');
            } else {
                cmsCore::addSessionMessage($_LANG['DELETING_PROFILE_OK'], 'info');
                cmsCore::redirect('/users');
            }
        } else {
            $inPage->setTitle($_LANG['DELETING_PROFILE']);
            $inPage->addPathway($data['nickname'], $inUser->getProfileURL($data['login']));
            $inPage->addPathway($_LANG['DELETING_PROFILE']);
            $confirm['title'] = $_LANG['DELETING_PROFILE'];
            $confirm['text'] = '<p>' . $_LANG['REALLY_DEL_PROFILE'] . '</p>';
            $confirm['action'] = '/users/' . $id . '/delprofile.html';
            $confirm['yes_button'] = array();
            $confirm['yes_button']['type'] = 'submit';
            cmsPage::initTemplate('components', 'action_confirm.tpl')->assign('confirm', $confirm)->display('action_confirm.tpl');
        }
    }
    //============================================================================//
    //============================ Восстановить профиль  =========================//
    //============================================================================//
    if ($do == 'restoreprofile') {
        if (!$inUser->is_admin) {
            cmsCore::error404();
        }
        $usr = cmsUser::getShortUserData($id);
        if (!$usr) {
            cmsCore::error404();
        }
        $inDB->query("UPDATE cms_users SET is_deleted = 0 WHERE id = '{$id}'");
        cmsCore::redirectBack();
    }
    //============================================================================//
    //============================= Файлы пользователей  =========================//
    //============================================================================//
    if ($do == 'files') {
        if (!$model->config['sw_files']) {
            cmsCore::error404();
        }
        $fdo = cmsCore::request('fdo', 'str', '');
        include 'components/users/files.php';
    }
    //============================================================================//
    //================================  Инвайты  =================================//
    //============================================================================//
    if ($do == 'invites') {
        $reg_cfg = $inCore->loadComponentConfig('registration');
        if ($reg_cfg['reg_type'] != 'invite') {
            cmsCore::error404();
        }
        $invites_count = $model->getUserInvitesCount($inUser->id);
        if (!$invites_count) {
            cmsCore::error404();
        }
        if (!cmsCore::inRequest('send_invite')) {
            $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
            $inPage->addPathway($_LANG['MY_INVITES']);
            cmsPage::initTemplate('components', 'com_users_invites')->assign('invites_count', $invites_count)->display('com_users_invites.tpl');
            return;
        }
        if (cmsCore::inRequest('send_invite')) {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $invite_email = cmsCore::request('invite_email', 'email', '');
            if (!$invite_email) {
                cmsCore::redirectBack();
            }
            if ($model->sendInvite($inUser->id, $invite_email)) {
                cmsCore::addSessionMessage(sprintf($_LANG['INVITE_SENDED'], $invite_email), 'success');
            } else {
                cmsCore::addSessionMessage($_LANG['INVITE_ERROR'], 'error');
            }
            cmsCore::redirect(cmsUser::getProfileURL($inUser->login));
        }
    }
    if ($do == 'change_email') {
        if (!$inUser->id) {
            cmsUser::goToLogin();
        }
        $email = cmsCore::request('email', 'email', '');
        $token = cmsCore::request('token', 'str', '');
        // не занят ли email
        $is_email = $inDB->get_field('cms_users', "email='{$email}'", 'id');
        if ($is_email || !$email || !$token) {
            cmsCore::error404();
        }
        // проверяем токен
        $valid_id = $inDB->get_field('cms_users_activate', "code='{$token}' AND user_id = '{$inUser->id}'", 'id');
        if (!$valid_id) {
            cmsCore::error404();
        }
        $inDB->delete('cms_users_activate', "id = '{$valid_id}'");
        // Сохраняем новый email
        $inDB->update('cms_users', array('email' => $email), $inUser->id);
        cmsCore::addSessionMessage($_LANG['NEW_EMAIL_SAVED'], 'success');
        cmsCore::redirect(cmsUser::getProfileURL($inUser->login));
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Example #7
0
function applet_menu()
{
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/menu', $adminAccess)) {
        cpAccessDenied();
    }
    $GLOBALS['cp_page_title'] = $_LANG['AD_MENU'];
    cpAddPathway($_LANG['AD_MENU'], 'index.php?view=menu');
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    if ($do == 'list') {
        $toolmenu[] = array('icon' => 'new.gif', 'title' => $_LANG['AD_MENU_POINT_ADD'], 'link' => '?view=menu&do=add');
        $toolmenu[] = array('icon' => 'newmenu.gif', 'title' => $_LANG['AD_MENU_ADD'], 'link' => '?view=menu&do=addmenu');
        $toolmenu[] = array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=edit&multiple=1');");
        $toolmenu[] = array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=delete&multiple=1');");
        $toolmenu[] = array('icon' => 'show.gif', 'title' => $_LANG['AD_ALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=show&multiple=1');");
        $toolmenu[] = array('icon' => 'hide.gif', 'title' => $_LANG['AD_DISALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=hide&multiple=1');");
        $toolmenu[] = array('icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=menu');
        cpToolMenu($toolmenu);
        $fields[] = array('title' => 'Lt', 'field' => 'NSLeft', 'width' => '30');
        $fields[] = array('title' => $_LANG['TITLE'], 'field' => 'title', 'width' => '', 'link' => '?view=menu&do=edit&id=%id%');
        $fields[] = array('title' => $_LANG['SHOW'], 'field' => 'published', 'width' => '60');
        $fields[] = array('title' => $_LANG['AD_ORDER'], 'field' => 'ordering', 'width' => '100');
        $fields[] = array('title' => $_LANG['AD_LINK'], 'field' => array('linktype', 'linkid', 'link'), 'width' => '240', 'prc' => 'cpMenutypeById');
        $fields[] = array('title' => $_LANG['AD_MENU'], 'field' => 'menu', 'width' => '70', 'filter' => '10', 'filterlist' => cpGetList('menu'), 'prc' => 'list_menu');
        $fields[] = array('title' => $_LANG['TEMPLATE'], 'field' => 'template', 'width' => '70', 'prc' => 'cpTemplateById');
        $actions[] = array('title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=menu&do=edit&id=%id%');
        $actions[] = array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_MENU_POINT_CONFIRM'], 'link' => '?view=menu&do=delete&id=%id%');
        cpListTable('cms_menu', $fields, $actions, 'parent_id>0', 'NSLeft, ordering');
    } else {
        $toolmenu[] = array('icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:document.addform.submit();');
        $toolmenu[] = array('icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'index.php?view=menu');
        cpToolMenu($toolmenu);
    }
    if ($do == 'move_up') {
        $inDB->moveNsCategory('cms_menu', $id, 'up');
        cmsCore::redirectBack();
    }
    if ($do == 'move_down') {
        $inDB->moveNsCategory('cms_menu', $id, 'down');
        cmsCore::redirectBack();
    }
    if ($do == 'show') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbShow('cms_menu', $id);
            }
            echo '1';
            exit;
        } else {
            dbShowList('cms_menu', $_REQUEST['item']);
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'hide') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbHide('cms_menu', $id);
            }
            echo '1';
            exit;
        } else {
            dbHideList('cms_menu', cmsCore::request('item', 'array_int', array()));
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'delete') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                $inDB->deleteNS('cms_menu', (int) $id);
            }
        } else {
            $items = cmsCore::request('item', 'array_int', array());
            foreach ($items as $item_id) {
                $inDB->deleteNS('cms_menu', $item_id);
            }
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirectBack();
    }
    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $id = cmsCore::request('id', 'int', 0);
        if (!$id) {
            cmsCore::redirectBack();
        }
        $title = cmsCore::request('title', 'str', '');
        $menu = cmsCore::arrayToYaml(cmsCore::request('menu', 'array_str', ''));
        $linktype = cmsCore::request('mode', 'str', '');
        $linkid = cmsCore::request($linktype, 'str', '');
        $link = $inCore->getMenuLink($linktype, $linkid);
        $target = cmsCore::request('target', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $template = cmsCore::request('template', 'str', '');
        $iconurl = cmsCore::request('iconurl', 'str', '');
        $parent_id = cmsCore::request('parent_id', 'int', 0);
        $oldparent = cmsCore::request('oldparent', 'int', 0);
        $is_lax = cmsCore::request('is_lax', 'int', 0);
        $css_class = cmsCore::request('css_class', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }
        $ns = $inCore->nestedSetsInit('cms_menu');
        if ($oldparent != $parent_id) {
            $ns->MoveNode($id, $parent_id);
        }
        $sql = "UPDATE cms_menu\n                SET title='{$title}',\n                    css_class='{$css_class}',\n                    menu='{$menu}',\n                    link='{$link}',\n                    linktype='{$linktype}',\n                    linkid='{$linkid}',\n                    target='{$target}',\n                    published='{$published}',\n                    template='{$template}',\n                    access_list='{$access_list}',\n                    is_lax='{$is_lax}',\n                    iconurl='{$iconurl}'\n                WHERE id = '{$id}'\n                LIMIT 1";
        $inDB->query($sql);
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        if (!isset($_SESSION['editlist']) || @sizeof($_SESSION['editlist']) == 0) {
            cmsCore::redirect('?view=menu');
        } else {
            cmsCore::redirect('?view=menu&do=edit');
        }
    }
    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $title = cmsCore::request('title', 'str', '');
        $menu = cmsCore::arrayToYaml(cmsCore::request('menu', 'array_str', ''));
        $linktype = cmsCore::request('mode', 'str', '');
        $linkid = cmsCore::request($linktype, 'str', '');
        $link = $inCore->getMenuLink($linktype, $linkid);
        $target = cmsCore::request('target', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $template = cmsCore::request('template', 'str', '');
        $iconurl = cmsCore::request('iconurl', 'str', '');
        $parent_id = cmsCore::request('parent_id', 'int', 0);
        $css_class = cmsCore::request('css_class', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        $is_lax = cmsCore::request('is_lax', 'int', 0);
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }
        $ns = $inCore->nestedSetsInit('cms_menu');
        $myid = $ns->AddNode($parent_id);
        $sql = "UPDATE cms_menu\n\t\t\t\tSET menu='{$menu}',\n\t\t\t\t\ttitle='{$title}',\n                    css_class='{$css_class}',\n\t\t\t\t\tlink='{$link}',\n\t\t\t\t\tlinktype='{$linktype}',\n\t\t\t\t\tlinkid='{$linkid}',\n\t\t\t\t\ttarget='{$target}',\n\t\t\t\t\tpublished='{$published}',\n\t\t\t\t\ttemplate='{$template}',\n\t\t\t\t\taccess_list='{$access_list}',\n\t\t\t\t\tis_lax='{$is_lax}',\n\t\t\t\t\ticonurl='{$iconurl}'\n\t\t\t\tWHERE id = '{$myid}'";
        $inDB->query($sql);
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('?view=menu');
    }
    if ($do == 'submitmenu') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $sql = "SELECT ordering as max_o FROM cms_modules ORDER BY ordering DESC LIMIT 1";
        $result = $inDB->query($sql);
        $row = $inDB->fetch_assoc($result);
        $maxorder = $row['max_o'] + 1;
        $menu = cmsCore::request('menu', 'str', '');
        $title = cmsCore::request('title', 'str', '');
        $position = cmsCore::request('position', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $css_prefix = cmsCore::request('css_prefix', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = $inCore->arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }
        $cfg['menu'] = $menu;
        $cfg_str = cmsCore::arrayToYaml($cfg);
        $sql = "INSERT INTO cms_modules (position, name, title, is_external, content, ordering, showtitle, published, user, config, css_prefix, access_list)\n                VALUES ('{$position}', '{$_LANG['AD_MENU']}', '{$title}', 1, 'mod_menu', {$maxorder}, 1, {$published}, 0, '{$cfg_str}', '{$css_prefix}', '{$access_list}')";
        $inDB->query($sql);
        $newid = $inDB->get_last_id('cms_modules');
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('?view=modules&do=edit&id=' . $newid);
    }
    if ($do == 'addmenu' || $do == 'add' || $do == 'edit') {
        $GLOBALS['cp_page_head'][] = '<script language="JavaScript" type="text/javascript" src="js/menu.js"></script>';
        echo '<script>';
        echo cmsPage::getLangJS('AD_SPECIFY_LINK_MENU');
        echo '</script>';
    }
    if ($do == 'addmenu') {
        $GLOBALS['cp_page_title'] = $_LANG['AD_MENU_ADD'];
        cpAddPathway($_LANG['AD_MENU_ADD']);
        $menu_list = cpGetList('menu');
        ?>
         <form id="addform" name="addform" action="index.php?view=menu&do=submitmenu" method="post">
             <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
             <table class="proptable" width="650" cellspacing="10" cellpadding="10">
                 <tr>
                     <td width="300" valign="top">
                         <strong><?php 
        echo $_LANG['AD_MODULE_MENU_TITLE'];
        ?>
</strong>
                     </td>
                     <td valign="top">
                         <input name="title" type="text" id="title2" style="width:99%" value=""/>
                     </td>
                 </tr>
                 <tr>
                     <td valign="top">
                         <strong><?php 
        echo $_LANG['AD_MENU_TO_VIEW'];
        ?>
</strong><br/>
                         <span class="hinttext"><?php 
        echo $_LANG['AD_TO_CREATE_NEW_POINT'];
        ?>
</span>
                     </td>
                     <td valign="top">
                         <select name="menu" id="menu" style="width:99%">
                             <?php 
        foreach ($menu_list as $menu) {
            ?>
                                 <option value="<?php 
            echo $menu['id'];
            ?>
">
                                     <?php 
            echo $menu['title'];
            ?>
                                 </option>
                             <?php 
        }
        ?>
                         </select>
                     </td>
                 </tr>
                 <tr>
                     <td valign="top">
                         <strong><?php 
        echo $_LANG['AD_POSITION_TO_VIEW'];
        ?>
</strong><br />
                         <span class="hinttext"><?php 
        echo $_LANG['AD_POSITION_MUST_BE'];
        ?>
</span>
                     </td>
                     <td valign="top">
                         <?php 
        $pos = cpModulePositions(cmsConfig::getConfig('template'));
        ?>
                         <select name="position" id="position" style="width:99%">
                             <?php 
        if ($pos) {
            foreach ($pos as $key => $position) {
                if (@$mod['position'] == $position) {
                    echo '<option value="' . $position . '" selected>' . $position . '</option>';
                } else {
                    echo '<option value="' . $position . '">' . $position . '</option>';
                }
            }
        }
        ?>
                         </select>
                         <input name="is_external" type="hidden" id="is_external" value="0" />
                     </td>
                 </tr>
                 <tr>
                     <td valign="top"><strong><?php 
        echo $_LANG['AD_MENU_PUBLIC'];
        ?>
</strong></td>
                     <td valign="top">
                         <label><input name="published" type="radio" value="1" checked="checked" <?php 
        if (@$mod['published']) {
            echo 'checked="checked"';
        }
        ?>
 /> <?php 
        echo $_LANG['YES'];
        ?>
</label>
                         <label><input name="published" type="radio" value="0"  <?php 
        if (@(!$mod['published'])) {
            echo 'checked="checked"';
        }
        ?>
 /> <?php 
        echo $_LANG['NO'];
        ?>
</label>
                     </td>
                 </tr>
                 <tr>
                     <td valign="top"><strong><?php 
        echo $_LANG['AD_PREFIX_CSS'];
        ?>
</strong></td>
                     <td valign="top">
                         <input name="css_prefix" type="text" id="css_prefix" value="<?php 
        echo @$mod['css_prefix'];
        ?>
" style="width:99%" />
                     </td>
                 </tr>
                 <tr>
                     <td valign="top">
                         <strong><?php 
        echo $_LANG['AD_TAB_ACCESS'];
        ?>
:</strong><br />
                         <span class="hinttext"><?php 
        echo $_LANG['AD_GROUP_ACCESS'];
        ?>
</span>
                     </td>
                     <td valign="top">
                     <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist" style="margin-top:5px">
                         <tr>
                             <td width="20">
                                 <?php 
        $groups = cmsUser::getGroups();
        $style = 'disabled="disabled"';
        $public = 'checked="checked"';
        if ($do == 'edit') {
            if ($mod['access_list']) {
                $public = '';
                $style = '';
                $access_list = $inCore->yamlToArray($mod['access_list']);
            }
        }
        ?>
                                 <input name="is_public" type="checkbox" id="is_public" onclick="checkAccesList()" value="1" <?php 
        echo $public;
        ?>
 />
                             </td>
                             <td><label for="is_public"><strong><?php 
        echo $_LANG['AD_SHARE'];
        ?>
</strong></label></td>
                         </tr>
                     </table>
                     <div style="padding:5px">
                         <span class="hinttext">
                             <?php 
        echo $_LANG['AD_VIEW_IF_CHECK'];
        ?>
                         </span>
                     </div>

                     <div style="margin-top:10px;padding:5px;padding-right:0px;" id="grp">
                         <div>
                             <strong><?php 
        echo $_LANG['AD_GROUPS_VIEW'];
        ?>
</strong><br />
                             <span class="hinttext">
                                  <?php 
        echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];
        ?>
                             </span>
                         </div>
                         <div>
                             <?php 
        echo '<select style="width: 99%" name="allow_group[]" id="allow_group" size="6" multiple="multiple" ' . $style . '>';
        if ($groups) {
            foreach ($groups as $group) {
                echo '<option value="' . $group['id'] . '"';
                if ($do == 'edit') {
                    if (inArray($access_list, $group['id'])) {
                        echo 'selected="selected"';
                    }
                }
                echo '>';
                echo $group['title'] . '</option>';
            }
        }
        echo '</select>';
        ?>
                         </div>
                     </div>
                     </td>
                 </tr>
                 <tr>
                     <td colspan="2" valign="top">
                         <div style="padding:10px;margin:4px;background-color:#EBEBEB;border:solid 1px gray">
                             <?php 
        echo $_LANG['AD_NEW_MENU_NEW_MODULE'];
        ?>
                         </div>
                     </td>
                 </tr>
             </table>
             <div style="margin-top:5px">
                 <input name="save" type="submit" id="save" value="<?php 
        echo $_LANG['AD_MENU_ADD'];
        ?>
" />
                 <input name="back" type="button" id="back" value="<?php 
        echo $_LANG['CANCEL'];
        ?>
" onclick="window.location.href='index.php?view=menu';" />
             </div>
         </form>
         <?php 
    }
    if ($do == 'add' || $do == 'edit') {
        require '../includes/jwtabs.php';
        $GLOBALS['cp_page_head'][] = jwHeader();
        $menu_list = cpGetList('menu');
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_MENU_POINT_ADD']);
            $mod['menu'] = array('mainmenu');
        } else {
            if (isset($_REQUEST['multiple'])) {
                if (isset($_REQUEST['item'])) {
                    $_SESSION['editlist'] = cmsCore::request('item', 'array_int', array());
                } else {
                    cmsCore::addSessionMessage($_LANG['AD_NO_SELECT_OBJECTS'], 'error');
                    cmsCore::redirectBack();
                }
            }
            $ostatok = '';
            if (isset($_SESSION['editlist'])) {
                $item_id = array_shift($_SESSION['editlist']);
                if (sizeof($_SESSION['editlist']) == 0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '(' . $_LANG['AD_NEXT_IN'] . sizeof($_SESSION['editlist']) . ')';
                }
            } else {
                $item_id = cmsCore::request('id', 'int', 0);
            }
            $mod = $inDB->get_fields('cms_menu', "id = '{$item_id}'", '*');
            if (!$mod) {
                cmsCore::error404();
            }
            $mod['menu'] = cmsCore::yamlToArray($mod['menu']);
            cpAddPathway($_LANG['AD_MENU_POINT_EDIT'] . $ostatok . ' "' . $mod['title'] . '"');
        }
        ?>
    <form id="addform" name="addform" method="post" action="index.php">
        <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
        <input type="hidden" name="view" value="menu" />

        <table class="proptable" width="100%" cellpadding="15" cellspacing="2">
            <tr>

                <td valign="top">

                    <div><strong><?php 
        echo $_LANG['AD_MENU_POINT_TITLE'];
        ?>
</strong> <span class="hinttext">&mdash; <?php 
        echo $_LANG['AD_VIEW_IN_SITE'];
        ?>
</span></div>
                    <div><input name="title" type="text" id="title" style="width:100%" value="<?php 
        echo htmlspecialchars($mod['title']);
        ?>
" /></div>
                    <div><strong><?php 
        echo $_LANG['AD_PARENT_POINT'];
        ?>
</strong></div>
                    <div>
                        <?php 
        $rootid = $inDB->get_field('cms_menu', 'parent_id=0', 'id');
        ?>
                        <select name="parent_id" size="10" id="parent_id" style="width:100%">
                            <option value="<?php 
        echo $rootid;
        ?>
" <?php 
        if (@$mod['parent_id'] == $rootid || !isset($mod['parent_id'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_MENU_ROOT'];
        ?>
</option>
                            <?php 
        if (isset($mod['parent_id'])) {
            echo $inCore->getListItemsNS('cms_menu', $mod['parent_id']);
        } else {
            echo $inCore->getListItemsNS('cms_menu');
        }
        ?>
                        </select>
                        <input type="hidden" name="oldparent" value="<?php 
        echo @$mod['parent_id'];
        ?>
" />
                    </div>

                    <div><strong><?php 
        echo $_LANG['AD_MENU_POINT_ACTION'];
        ?>
</strong></div>
                    <div>
                        <select name="mode" id="linktype" style="width:100%" onchange="showMenuTarget()">
                            <option value="link" <?php 
        if (@$mod['linktype'] == 'link' || !isset($mod['mode'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_LINK'];
        ?>
</option>
                            <option value="content" <?php 
        if (@$mod['linktype'] == 'content') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_ARTICLE'];
        ?>
</option>
                            <option value="category" <?php 
        if (@$mod['linktype'] == 'category') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_PARTITION'];
        ?>
</option>
                            <?php 
        if ($inCore->isComponentInstalled('video')) {
            ?>
                            <option value="video_cat" <?php 
            if (@$mod['linktype'] == 'video_cat') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo $_LANG['AD_OPEN_VIDEO_PARTITION'];
            ?>
</option>
                            <?php 
        }
        ?>
                            <option value="component" <?php 
        if (@$mod['linktype'] == 'component') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_COMPONENT'];
        ?>
</option>
                            <option value="blog" <?php 
        if (@$mod['linktype'] == 'blog') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_BLOG'];
        ?>
</option>
                            <option value="uccat" <?php 
        if (@$mod['linktype'] == 'uccat') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_CATEGORY'];
        ?>
</option>
                            <option value="photoalbum" <?php 
        if (@$mod['linktype'] == 'photoalbum') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_OPEN_ALBUM'];
        ?>
</option>
                        </select>
                    </div>

                    <div id="t_link" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'link' || $mod['linktype'] == 'ext' || !$mod['linktype']) {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_LINK'];
        ?>
</strong> <span class="hinttext">&mdash; <?php 
        echo $_LANG['AD_LINK_HINT'];
        ?>
 <b>http://</b></span>
                        </div>
                        <div>
                            <input name="link" type="text" id="link" size="50" style="width:100%" <?php 
        if (@$mod['linktype'] == 'link' || @$mod['linktype'] == 'ext') {
            echo 'value="' . $mod['link'] . '"';
        }
        ?>
/>
                        </div>
                    </div>

                    <div id="t_content" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'content') {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_CHECK_ARTICLE'];
        ?>
</strong>
                        </div>
                        <div>
                            <select name="content" id="content" style="width:100%">
                                <?php 
        if (@$mod['linktype'] == 'content') {
            echo $inCore->getListItems('cms_content', $mod['linkid']);
        } else {
            echo $inCore->getListItems('cms_content');
        }
        ?>
                            </select>
                        </div>
                    </div>

                    <?php 
        if ($inCore->isComponentInstalled('video')) {
            ?>
                    <div id="t_video_cat" class="menu_target" style="display:<?php 
            if ($mod['linktype'] == 'video_cat') {
                echo 'block';
            } else {
                echo 'none';
            }
            ?>
">
                        <div>
                            <strong><?php 
            echo $_LANG['AD_CHECK_PARTITION'];
            ?>
</strong>
                        </div>
                        <div>
                            <select name="video_cat" id="video_cat" style="width:100%">
                                    <?php 
            if (@$mod['linktype'] == 'video_cat') {
                echo $inCore->getListItemsNS('cms_video_category', $mod['linkid']);
            } else {
                echo $inCore->getListItemsNS('cms_video_category');
            }
            ?>
                            </select>
                        </div>
                    </div>
                    <?php 
        }
        ?>

                    <div id="t_category" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'category') {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_CHECK_PARTITION'];
        ?>
</strong>
                        </div>
                        <div>
                            <select name="category" id="category" style="width:100%">
                                    <?php 
        if (@$mod['linktype'] == 'category') {
            echo $inCore->getListItemsNS('cms_category', $mod['linkid']);
        } else {
            echo $inCore->getListItemsNS('cms_category');
        }
        ?>
                            </select>
                        </div>
                    </div>

                    <div id="t_component" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'component') {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_CHECK_COMPONENT'];
        ?>
</strong>
                        </div>
                        <div>
                           <select name="component" id="component" style="width:100%">
                                <?php 
        if (@$mod['linktype'] == 'component') {
            echo $inCore->getListItems('cms_components', $mod['linkid'], 'title', 'asc', 'internal=0', 'link');
        } else {
            echo $inCore->getListItems('cms_components', 0, 'title', 'asc', 'internal=0', 'link');
        }
        ?>
                            </select>
                        </div>
                    </div>

                    <div id="t_blog" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'blog') {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_CHECK_BLOG'];
        ?>
</strong>
                        </div>
                        <div>
                           <select name="blog" id="blog" style="width:100%">
                                <?php 
        if (@$mod['linktype'] == 'blog') {
            echo $inCore->getListItems('cms_blogs', $mod['linkid'], 'title', 'asc', "owner='user'");
        } else {
            echo $inCore->getListItems('cms_blogs', 0, 'title', 'asc', "owner='user'");
        }
        ?>
                            </select>
                        </div>
                    </div>

                    <div id="t_uccat" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'uccat') {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_CHECK_CATEGORY'];
        ?>
</strong>
                        </div>
                        <div>
                           <select name="uccat" id="uccat" style="width:100%">
                                <?php 
        if (@$mod['linktype'] == 'uccat') {
            echo $inCore->getListItems('cms_uc_cats', $mod['linkid']);
        } else {
            echo $inCore->getListItems('cms_uc_cats');
        }
        ?>
                            </select>
                        </div>
                    </div>

                    <div id="t_photoalbum" class="menu_target" style="display:<?php 
        if ($mod['linktype'] == 'photoalbum') {
            echo 'block';
        } else {
            echo 'none';
        }
        ?>
">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_CHECK_ALBUM'];
        ?>
</strong>
                        </div>
                        <div>
                           <select name="photoalbum" id="photoalbum" style="width:100%">
                                <?php 
        if (@$mod['linktype'] == 'photoalbum') {
            echo $inCore->getListItems('cms_photo_albums', $mod['linkid'], 'id', 'ASC', 'NSDiffer = ""');
        } else {
            echo $inCore->getListItems('cms_photo_albums', 0, 'id', 'ASC', 'NSDiffer = ""');
        }
        ?>
                            </select>
                        </div>
                    </div>

                </td>

                <td width="300" valign="top" style="background:#ECECEC;">

                    <?php 
        ob_start();
        ?>

                    {tab=<?php 
        echo $_LANG['AD_TAB_PUBLISH'];
        ?>
}

                        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                            <tr>
                                <td width="20"><input type="checkbox" name="published" id="published" value="1" <?php 
        if ($mod['published'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                                <td><label for="published"><strong><?php 
        echo $_LANG['AD_MENU_POINT_PUBLIC'];
        ?>
</strong></label></td>
                            </tr>
                        </table>

                        <div style="margin-top:15px">
                            <strong><?php 
        echo $_LANG['AD_OPEN_POINT'];
        ?>
</strong>
                        </div>
                        <div>
                            <select name="target" id="target" style="width:100%">
                                <option value="_self" <?php 
        if (@$mod['target'] == '_self') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_SELF'];
        ?>
</option>
                                <option value="_parent"><?php 
        echo $_LANG['AD_PARENT'];
        ?>
</option>
                                <option value="_blank" <?php 
        if (@$mod['target'] == '_blank') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_BLANK'];
        ?>
</option>
                                <option value="_top" <?php 
        if (@$mod['target'] == '_top') {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_TOP'];
        ?>
</option>
                            </select>
                        </div>

                        <div style="margin-top:15px">
                            <strong><?php 
        echo $_LANG['TEMPLATE'];
        ?>
</strong><br/>
                            <span class="hinttext"><?php 
        echo $_LANG['AD_DESIGN_CHANGE'];
        ?>
</span>
                        </div>
                        <div>
                            <select name="template" id="template" style="width:100%">
                                <option value="0" <?php 
        if (@$mod['template'] == 0 || !$mod['template']) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_BY_DEFAULT'];
        ?>
</option>
                                <?php 
        $templates = cmsCore::getDirsList('/templates');
        foreach ($templates as $template) {
            echo '<option value="' . $template . '" ' . (@$mod['template'] == $template ? 'selected="selected"' : '') . '>' . $template . '</option>';
        }
        ?>
                            </select>
                        </div>

                        <div style="margin-top:15px">
                            <strong><?php 
        echo $_LANG['AD_ICON_PICTURE'];
        ?>
</strong><br/>
                            <span class="hinttext"><?php 
        echo $_LANG['AD_ICON_FILENAME'];
        ?>
</span>
                        </div>
                        <div>
                            <input name="iconurl" type="text" id="iconurl" size="30" value="<?php 
        echo @$mod['iconurl'];
        ?>
" style="width:100%"/>
                            <div>
                                <a id="iconlink" style="display:block;" href="javascript:showIcons()"><?php 
        echo $_LANG['AD_CHECK_ICON'];
        ?>
</a>
                                <div id="icondiv" style="display:none; padding:6px;border:solid 1px gray;background:#FFF">
                                    <div><?php 
        iconList();
        ?>
</div>
                                </div>
                            </div>
                        </div>
                        <div style="margin-top:15px">
                            <strong><?php 
        echo $_LANG['AD_CSS_CLASS'];
        ?>
</strong>
                        </div>
                        <div>
                            <input name="css_class" type="text" size="30" value="<?php 
        echo @$mod['css_class'];
        ?>
" style="width:100%"/>
                        </div>

                    {tab=<?php 
        echo $_LANG['AD_TAB_ACCESS'];
        ?>
}
                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist" style="margin-top:5px">
                        <tr>
                            <td width="20">
                                <?php 
        $groups = cmsUser::getGroups();
        $style = 'disabled="disabled"';
        $public = 'checked="checked"';
        if ($do == 'edit') {
            if ($mod['access_list']) {
                $public = '';
                $style = '';
                $access_list = $inCore->yamlToArray($mod['access_list']);
            }
        }
        ?>
                                <input name="is_public" type="checkbox" id="is_public" onclick="checkAccesList()" value="1" <?php 
        echo $public;
        ?>
 />
                            </td>
                            <td><label for="is_public"><strong><?php 
        echo $_LANG['AD_SHARE'];
        ?>
</strong></label></td>
                        </tr>
                    </table>
                    <div style="padding:5px">
                        <span class="hinttext">
                            <?php 
        echo $_LANG['AD_VIEW_IF_CHECK'];
        ?>
                        </span>
                    </div>

                    <div style="margin-top:10px;padding:5px;padding-right:0px;" id="grp">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_GROUPS_VIEW'];
        ?>
</strong><br />
                            <span class="hinttext">
                                <?php 
        echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];
        ?>
                            </span>
                        </div>
                        <div>
                            <?php 
        echo '<select style="width: 99%" name="allow_group[]" id="allow_group" size="6" multiple="multiple" ' . $style . '>';
        if ($groups) {
            foreach ($groups as $group) {
                echo '<option value="' . $group['id'] . '"';
                if ($do == 'edit' && $mod['access_list']) {
                    if (inArray($access_list, $group['id'])) {
                        echo 'selected="selected"';
                    }
                }
                echo '>';
                echo $group['title'] . '</option>';
            }
        }
        echo '</select>';
        ?>
                        </div>
                    </div>
                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist" style="margin-top:5px">
                        <tr>
                            <td width="20">
                                <input name="is_lax" type="checkbox" id="is_lax" value="1" <?php 
        if (@$mod['is_lax']) {
            ?>
checked="checked"<?php 
        }
        ?>
 />
                            </td>
                            <td><label for="is_lax"><strong><?php 
        echo $_LANG['AD_ONLY_CHILD_ITEM'];
        ?>
</strong></label></td>
                        </tr>
                    </table>
                    {tab=<?php 
        echo $_LANG['AD_MENU'];
        ?>
}
                    <div style="padding:5px;padding-right:0px;">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_MENU_TO_VIEW'];
        ?>
</strong><br />
                            <span class="hinttext">
                                <?php 
        echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];
        ?>
                            </span>
                        </div>
                        <div>
                        <select style="width: 99%" name="menu[]" size="9" multiple="multiple">
                            <?php 
        foreach ($menu_list as $menu) {
            ?>
                                <option value="<?php 
            echo $menu['id'];
            ?>
" <?php 
            if (@in_array($menu['id'], @$mod['menu'])) {
                echo 'selected="selected"';
            }
            ?>
>
                                    <?php 
            echo $menu['title'];
            ?>
                                </option>
                            <?php 
        }
        ?>
                        </select>
                        </div>
                    </div>
                    {/tabs}

                    <?php 
        echo jwTabs(ob_get_clean());
        ?>

                </td>

            </tr>
        </table>

        <p>
            <input name="add_mod" type="button" onclick="submitItem()" id="add_mod" value="<?php 
        echo $_LANG['SAVE'];
        ?>
 " />
            <input name="back" type="button" id="back" value="<?php 
        echo $_LANG['CANCEL'];
        ?>
" onclick="window.location.href='index.php?view=menu';" />
            <input name="do" type="hidden" id="do" <?php 
        if ($do == 'add') {
            echo 'value="submit"';
        } else {
            echo 'value="update"';
        }
        ?>
 />
            <?php 
        if ($do == 'edit') {
            echo '<input name="id" type="hidden" value="' . $mod['id'] . '" />';
        }
        ?>
        </p>
    </form>
    <?php 
    }
}
Example #8
0
function applet_modules()
{
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) {
        cpAccessDenied();
    }
    $GLOBALS['cp_page_title'] = $_LANG['AD_MODULES'];
    cpAddPathway($_LANG['AD_MODULES'], 'index.php?view=modules');
    $GLOBALS['cp_page_head'][] = '<script language="JavaScript" type="text/javascript" src="js/modules.js"></script>';
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    $co = cmsCore::request('co', 'int', -1);
    //============================================================================//
    //============================================================================//
    if ($do == 'config') {
        $module_name = cpModuleById($id);
        $module_title = cpModuleTitleById($id);
        if (!$module_name) {
            cmsCore::redirect('index.php?view=modules&do=edit&id=' . $id);
        }
        $xml_file = PATH . '/admin/modules/' . $module_name . '/backend.xml';
        $php_file = 'modules/' . $module_name . '/backend.php';
        if (!file_exists($xml_file)) {
            if (file_exists($php_file)) {
                include $php_file;
                return;
            }
            cmsCore::halt();
        }
        $cfg = $inCore->loadModuleConfig($id);
        cmsCore::loadClass('formgen');
        $formGen = new cmsFormGen($xml_file, $cfg);
        cpAddPathway($module_title, '?view=modules&do=edit&id=' . $id);
        cpAddPathway($_LANG['AD_SETTINGS']);
        echo '<h3>' . $module_title . '</h3>';
        $toolmenu[] = array('icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:submitModuleConfig();');
        $toolmenu[] = array('icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'index.php?view=modules');
        $toolmenu[] = array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_MODULE_VIEW'], 'link' => '?view=modules&do=edit&id=' . $id);
        cpToolMenu($toolmenu);
        echo '<form action="index.php?view=modules&do=save_auto_config&id=' . $id . '" method="post" name="optform" target="_self" id="optform">';
        echo $formGen->getHTML();
        echo '</form>';
        return;
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'save_auto_config') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $module_name = cpModuleById($id);
        $is_ajax = cmsCore::inRequest('ajax');
        if ($is_ajax) {
            $title = cmsCore::request('title', 'str', '');
            $published = cmsCore::request('published', 'int', 0);
            $inDB->query("UPDATE cms_modules SET title='{$title}', published='{$published}' WHERE id={$id}");
            if (cmsCore::inRequest('content')) {
                $content = $inDB->escape_string(cmsCore::request('content', 'html'));
                $inDB->query("UPDATE cms_modules SET content='{$content}' WHERE id={$id}");
            }
            // Добавим возможность изменять css_префикс с фронта
            if (cmsCore::inRequest('css_prefix')) {
                // На шаблонах не не отдающих параметра затирать класс не будем
                $css_prefix = cmsCore::request('css_prefix', 'str', '');
                $inDB->query("UPDATE cms_modules SET css_prefix='{$css_prefix}' WHERE id='{$id}'");
            }
        }
        if (cmsCore::inRequest('title_only')) {
            cmsCore::redirectBack();
        }
        $xml_file = PATH . '/admin/modules/' . $module_name . '/backend.xml';
        if (!file_exists($xml_file)) {
            cmsCore::halt();
        }
        $cfg = array();
        $backend = simplexml_load_file($xml_file);
        foreach ($backend->params->param as $param) {
            $name = (string) $param['name'];
            $type = (string) $param['type'];
            $default = (string) $param['default'];
            switch ($param['type']) {
                case 'number':
                    $value = cmsCore::request($name, 'int', $default);
                    break;
                case 'string':
                    $value = cmsCore::request($name, 'str', $default);
                    break;
                case 'html':
                    $value = cmsCore::badTagClear(cmsCore::request($name, 'html', $default));
                    break;
                case 'flag':
                    $value = cmsCore::request($name, 'int', 0);
                    break;
                case 'list':
                    $value = is_array($_POST[$name]) ? cmsCore::request($name, 'array_str', $default) : cmsCore::request($name, 'str', $default);
                    break;
                case 'list_function':
                    $value = cmsCore::request($name, 'str', $default);
                    break;
                case 'list_db':
                    $value = is_array($_POST[$name]) ? cmsCore::request($name, 'array_str', $default) : cmsCore::request($name, 'str', $default);
                    break;
            }
            $cfg[$name] = $value;
        }
        $inCore->saveModuleConfig($id, $cfg);
        if (!$is_ajax) {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        }
        cmsCore::redirectBack();
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'list') {
        $toolmenu[] = array('icon' => 'new.gif', 'title' => $_LANG['AD_MODULE_ADD'], 'link' => '?view=modules&do=add');
        $toolmenu[] = array('icon' => 'install.gif', 'title' => $_LANG['AD_MODULES_SETUP'], 'link' => '?view=install&do=module');
        $toolmenu[] = array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=edit&multiple=1');");
        $toolmenu[] = array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=delete&multiple=1');");
        $toolmenu[] = array('icon' => 'show.gif', 'title' => $_LANG['AD_ALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=show&multiple=1');");
        $toolmenu[] = array('icon' => 'hide.gif', 'title' => $_LANG['AD_DISALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=hide&multiple=1');");
        $toolmenu[] = array('icon' => 'autoorder.gif', 'title' => $_LANG['AD_MODULE_ORDER'], 'link' => '?view=modules&do=autoorder');
        $toolmenu[] = array('icon' => 'reorder.gif', 'title' => $_LANG['AD_SAVE_ORDER'], 'link' => "javascript:checkSel('?view=modules&do=saveorder');");
        $toolmenu[] = array('icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=modules');
        cpToolMenu($toolmenu);
        $fields[] = array('title' => 'id', 'field' => 'id', 'width' => '30');
        $fields[] = array('title' => $_LANG['AD_TITLE'], 'field' => array('title', 'titles'), 'width' => '', 'link' => '?view=modules&do=edit&id=%id%', 'prc' => function ($i) {
            $i['titles'] = cmsCore::yamlToArray($i['titles']);
            // переопределяем название пункта меню в зависимости от языка
            if (!empty($i['titles'][cmsConfig::getConfig('lang')])) {
                $i['title'] = $i['titles'][cmsConfig::getConfig('lang')];
            }
            return $i['title'];
        });
        $fields[] = array('title' => $_LANG['TITLE'], 'field' => 'name', 'width' => '220', 'filter' => '15');
        $fields[] = array('title' => $_LANG['AD_VERSION'], 'field' => 'version', 'width' => '55');
        $fields[] = array('title' => $_LANG['AD_AUTHOR'], 'field' => 'author', 'width' => '110');
        $fields[] = array('title' => $_LANG['SHOW'], 'field' => 'published', 'width' => '65');
        $fields[] = array('title' => $_LANG['AD_ORDER'], 'field' => 'ordering', 'width' => '75');
        $fields[] = array('title' => $_LANG['AD_POSITION'], 'field' => 'position', 'width' => '70', 'filter' => '10', 'filterlist' => cpGetList('positions'));
        $actions[] = array('title' => $_LANG['AD_CONFIG'], 'icon' => 'config.gif', 'link' => '?view=modules&do=config&id=%id%', 'condition' => 'cpModuleHasConfig');
        $actions[] = array('title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=modules&do=edit&id=%id%');
        $actions[] = array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_MODULE_DELETE'], 'link' => '?view=modules&do=delete&id=%id%');
        cpListTable('cms_modules', $fields, $actions, '', 'published DESC, position, ordering ASC');
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'autoorder') {
        $rs = $inDB->query("SELECT id, position FROM cms_modules ORDER BY position");
        if ($inDB->num_rows($rs)) {
            $ord = 1;
            while ($item = $inDB->fetch_assoc($rs)) {
                if (isset($latest_pos)) {
                    if ($latest_pos != $item['position']) {
                        $ord = 1;
                    }
                }
                $inDB->query("UPDATE cms_modules SET ordering = {$ord} WHERE id='{$item['id']}'");
                $ord += 1;
                $latest_pos = $item['position'];
            }
        }
        cmsCore::redirect('index.php?view=modules');
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'move_up') {
        if ($id >= 0) {
            dbMoveUp('cms_modules', $id, $co);
        }
        cmsCore::redirectBack();
    }
    if ($do == 'move_down') {
        if ($id >= 0) {
            dbMoveDown('cms_modules', $id, $co);
        }
        cmsCore::redirectBack();
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'saveorder') {
        if (isset($_REQUEST['ordering'])) {
            $ord = $_REQUEST['ordering'];
            $ids = $_REQUEST['ids'];
            foreach ($ord as $id => $ordering) {
                $inDB->query("UPDATE cms_modules SET ordering = '" . (int) $ordering . "' WHERE id = '" . (int) $ids[$id] . "'");
            }
            cmsCore::redirect('index.php?view=modules');
        }
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'show') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbShow('cms_modules', $id);
            }
            echo '1';
            exit;
        } else {
            dbShowList('cms_modules', cmsCore::request('item', 'array_int', array()));
            cmsCore::redirectBack();
        }
    }
    if ($do == 'hide') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbHide('cms_modules', $id);
            }
            echo '1';
            exit;
        } else {
            dbHideList('cms_modules', cmsCore::request('item', 'array_int', array()));
            cmsCore::redirectBack();
        }
    }
    if ($do == 'delete') {
        if (!isset($_REQUEST['item'])) {
            $inCore->removeModule($id);
        } else {
            $inCore->removeModule(cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('index.php?view=modules');
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $id = cmsCore::request('id', 'int', 0);
        $name = cmsCore::request('name', 'str', '');
        $title = cmsCore::request('title', 'str', '');
        $titles = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $position = cmsCore::request('position', 'str', '');
        $showtitle = cmsCore::request('showtitle', 'int', 0);
        $content = $inDB->escape_string(cmsCore::request('content', 'html', ''));
        $published = cmsCore::request('published', 'int', 0);
        $css_prefix = cmsCore::request('css_prefix', 'str', '');
        $is_strict_bind = cmsCore::request('is_strict_bind', 'int', 0);
        $is_strict_bind_hidden = cmsCore::request('is_strict_bind_hidden', 'int', 0);
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int', array()));
        }
        $template = cmsCore::request('template', 'str', '');
        $cache = cmsCore::request('cache', 'int', 0);
        $cachetime = cmsCore::request('cachetime', 'int', 0);
        $cacheint = cmsCore::request('cacheint', 'str', '');
        $sql = "UPDATE cms_modules\r\n                SET name='{$name}',\r\n                    title='{$title}',\r\n                    titles='{$titles}',\r\n                    position='{$position}',\r\n                    template='{$template}',\r\n                    showtitle={$showtitle},";
        if ($content) {
            $sql .= "content='{$content}',";
        }
        $sql .= "\r\n                    published={$published},\r\n                    css_prefix='{$css_prefix}',\r\n                    access_list='{$access_list}',\r\n                    hidden_menu_ids='',\r\n                    cachetime = '{$cachetime}',\r\n                    cacheint = '{$cacheint}',\r\n                    cache = '{$cache}',\r\n                    is_strict_bind = '{$is_strict_bind}',\r\n                    is_strict_bind_hidden = '{$is_strict_bind_hidden}'\r\n                WHERE id = '{$id}'\r\n                LIMIT 1";
        $inDB->query($sql);
        $sql = "DELETE FROM cms_modules_bind WHERE module_id = {$id}";
        $inDB->query($sql);
        if (cmsCore::request('show_all', 'int', 0)) {
            $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position)\r\n                    VALUES ({$id}, 0, '{$position}')";
            $inDB->query($sql);
            $hidden_menu_ids = cmsCore::request('hidden_menu_ids', 'array_int', array());
            if ($hidden_menu_ids) {
                $hidden_menu_ids = cmsCore::arrayToYaml($hidden_menu_ids);
                $inDB->query("UPDATE cms_modules SET hidden_menu_ids='{$hidden_menu_ids}' WHERE id = '{$id}' LIMIT 1");
            }
        } else {
            $showin = cmsCore::request('showin', 'array_int', array());
            $showpos = cmsCore::request('showpos', 'array_str', array());
            if ($showin) {
                foreach ($showin as $key => $value) {
                    $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position)\r\n                            VALUES ({$id}, {$value}, '{$showpos[$value]}')";
                    $inDB->query($sql);
                }
            }
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        if (!isset($_SESSION['editlist']) || @sizeof($_SESSION['editlist']) == 0) {
            cmsCore::redirect('index.php?view=modules');
        } else {
            cmsCore::redirect('index.php?view=modules&do=edit');
        }
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $sql = "SELECT ordering as max_o FROM cms_menu ORDER BY ordering DESC LIMIT 1";
        $result = $inDB->query($sql);
        $row = $inDB->fetch_assoc($result);
        $maxorder = $row['max_o'] + 1;
        $name = cmsCore::request('name', 'str', '');
        $title = cmsCore::request('title', 'str', '');
        $titles = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $position = cmsCore::request('position', 'str', '');
        $showtitle = cmsCore::request('showtitle', 'int', 0);
        $content = $inDB->escape_string(cmsCore::request('content', 'html', ''));
        $published = cmsCore::request('published', 'int', 0);
        $css_prefix = cmsCore::request('css_prefix', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int', array()));
        }
        $template = cmsCore::request('template', 'str', '');
        $cache = cmsCore::request('cache', 'int', 0);
        $cachetime = cmsCore::request('cachetime', 'int', 0);
        $cacheint = cmsCore::request('cacheint', 'str', '');
        $operate = cmsCore::request('operate', 'str', '');
        $is_strict_bind = cmsCore::request('is_strict_bind', 'int', 0);
        $is_strict_bind_hidden = cmsCore::request('is_strict_bind_hidden', 'int', 0);
        if ($operate == 'user') {
            //USER MODULE
            $sql = "INSERT INTO cms_modules (position, name, title, titles, is_external, content, ordering, showtitle, published, user, original, css_prefix, access_list, template, is_strict_bind, is_strict_bind_hidden)\r\n\t\t\t\t\tVALUES ('{$position}', '{$name}', '{$title}', '{$titles}', 0, '{$content}', '{$maxorder}', '{$showtitle}', '{$published}', 1, 1, '{$css_prefix}', '{$access_list}', '{$template}', '{$is_strict_bind}', '{$is_strict_bind_hidden}')";
            $inDB->query($sql);
        }
        if ($operate == 'clone') {
            //DUPLICATE MODULE
            $mod_id = cmsCore::request('clone_id', 'int', 0);
            $sql = "SELECT * FROM cms_modules WHERE id = {$mod_id} LIMIT 1";
            $result = $inDB->query($sql);
            $original = $inDB->escape_string($inDB->fetch_assoc($result));
            $is_original = cmsCore::request('del_orig', 'int', 0) ? 1 : 0;
            $sql = "INSERT INTO cms_modules (position, name, title, titles, is_external,\r\n                                             content, ordering, showtitle, published,\r\n                                             original, user, config, css_prefix, template,\r\n                                             access_list, is_strict_bind, is_strict_bind_hidden,\r\n                                             cache, cachetime, cacheint, version)\r\n\t\t\t\t\tVALUES (\r\n\t\t\t\t\t\t\t'{$position}',\r\n\t\t\t\t\t\t\t'{$original['name']}',\r\n\t\t\t\t\t\t\t'{$title}',\r\n\t\t\t\t\t\t\t'{$titles}',\r\n\t\t\t\t\t\t\t'{$original['is_external']}',\r\n\t\t\t\t\t\t\t'{$original['content']}',\r\n\t\t\t\t\t\t\t'{$maxorder}',\r\n\t\t\t\t\t\t\t'{$showtitle}',\r\n\t\t\t\t\t\t\t'{$published}',\r\n\t\t\t\t\t\t\t'{$is_original}',\r\n\t\t\t\t\t\t\t'{$original['user']}',\r\n\t\t\t\t\t\t\t'{$original['config']}',\r\n\t\t\t\t\t\t\t'{$css_prefix}',\r\n                            '{$template}',\r\n                            '{$access_list}',\r\n                            '{$is_strict_bind}',\r\n                            '{$is_strict_bind_hidden}',\r\n                            '{$cache}', '{$cachetime}', '{$cacheint}', '{$original['version']}'\r\n                            )";
            $inDB->query($sql);
            if ($is_original) {
                $sql = "DELETE FROM cms_modules WHERE id = {$mod_id}";
                $inDB->query($sql);
            }
        }
        $lastid = $inDB->get_last_id('cms_modules');
        if (cmsCore::request('show_all', 'int', 0)) {
            $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position)\r\n\t\t\t\t\tVALUES ({$lastid}, 0, '{$position}')";
            $inDB->query($sql);
            $hidden_menu_ids = cmsCore::request('hidden_menu_ids', 'array_int', array());
            if ($hidden_menu_ids) {
                $hidden_menu_ids = cmsCore::arrayToYaml($hidden_menu_ids);
                $inDB->query("UPDATE cms_modules SET hidden_menu_ids='{$hidden_menu_ids}' WHERE id = '{$lastid}' LIMIT 1");
            }
        } else {
            $showin = cmsCore::request('showin', 'array_int', array());
            $showpos = cmsCore::request('showpos', 'array_str', array());
            if ($showin) {
                foreach ($showin as $key => $value) {
                    $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position)\r\n\t\t\t\t\t\t\tVALUES ({$lastid}, {$value}, '{$showpos[$value]}')";
                    $inDB->query($sql);
                }
            }
        }
        cmsCore::addSessionMessage($_LANG['AD_MODULE_ADD_SITE'], 'success');
        cmsCore::redirect('index.php?view=modules');
    }
    //============================================================================//
    //============================================================================//
    if ($do == 'add' || $do == 'edit') {
        require '../includes/jwtabs.php';
        $GLOBALS['cp_page_head'][] = jwHeader();
        $langs = cmsCore::getDirsList('/languages');
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_MODULE_ADD']);
            echo '<h3>' . $_LANG['AD_MODULE_ADD'] . '</h3>';
            $show_all = false;
        } else {
            if (isset($_REQUEST['multiple'])) {
                if (isset($_REQUEST['item'])) {
                    $_SESSION['editlist'] = cmsCore::request('item', 'array_int', array());
                } else {
                    cmsCore::addSessionMessage($_LANG['AD_NO_SELECT_OBJECTS'], 'error');
                    cmsCore::redirectBack();
                }
            }
            $ostatok = '';
            if (isset($_SESSION['editlist'])) {
                $item_id = array_shift($_SESSION['editlist']);
                if (sizeof($_SESSION['editlist']) == 0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '(' . $_LANG['AD_NEXT_IN'] . sizeof($_SESSION['editlist']) . ')';
                }
            } else {
                $item_id = cmsCore::request('id', 'int', 0);
            }
            $mod = $inDB->get_fields('cms_modules', "id = '{$item_id}'", '*');
            if (!$mod) {
                cmsCore::error404();
            }
            $mod['hidden_menu_ids'] = cmsCore::yamlToArray($mod['hidden_menu_ids']);
            $mod['titles'] = cmsCore::yamlToArray($mod['titles']);
            $sql = "SELECT id FROM cms_modules_bind WHERE module_id = {$id} AND menu_id = 0 LIMIT 1";
            $result = $inDB->query($sql);
            if ($inDB->num_rows($result)) {
                $show_all = true;
            } else {
                $show_all = false;
            }
            echo '<h3>' . $_LANG['AD_EDIT_MODULE'] . $ostatok . '</h3>';
            cpAddPathway($mod['name']);
        }
        $toolmenu[] = array('icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:document.addform.submit();');
        $toolmenu[] = array('icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'javascript:history.go(-1);');
        if (@$mod['is_external']) {
            $php_file = 'modules/' . $mod['content'] . '/backend.php';
            $xml_file = 'modules/' . $mod['content'] . '/backend.xml';
            if (file_exists($php_file) || file_exists($xml_file)) {
                $toolmenu[] = array('icon' => 'config.gif', 'title' => $_LANG['CONFIG_MODULE'], 'link' => '?view=modules&do=config&id=' . $mod['id']);
            }
        }
        cpToolMenu($toolmenu);
        ?>
    <form id="addform" name="addform" method="post" action="index.php">
        <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
        <input type="hidden" name="view" value="modules" />

        <table class="proptable" width="100%" cellpadding="15" cellspacing="2">
            <tr>

                <!-- главная ячейка -->
                <td valign="top">

                    <div><strong><?php 
        echo $_LANG['AD_MODULE_TITLE'];
        ?>
</strong> <span class="hinttext">&mdash; <?php 
        echo $_LANG['AD_VIEW_IN_SITE'];
        ?>
</span></div>
                    <div>
                        <table width="100%" cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td><input name="title" type="text" id="title" style="width:100%" value="<?php 
        echo htmlspecialchars($mod['title']);
        ?>
" /></td>
                                <td style="width:15px;padding-left:10px;padding-right:0px;">
                                    <input type="checkbox" title="<?php 
        echo $_LANG['AD_VIEW_TITLE'];
        ?>
" name="showtitle" <?php 
        if ($mod['showtitle'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
 value="1">
                                </td>
                            </tr>
                        </table>
                    </div>
                    <?php 
        if (count($langs) > 1) {
            ?>
                    <div><strong><?php 
            echo $_LANG['AD_LANG_TITLES'];
            ?>
</strong> <span class="hinttext">&mdash; <?php 
            echo $_LANG['AD_LANG_TITLES_HINT'];
            ?>
</span></div>
                    <?php 
            foreach ($langs as $lang) {
                ?>

                    <div><strong><?php 
                echo $lang;
                ?>
:</strong> <input name="titles[<?php 
                echo $lang;
                ?>
]" type="text" style="width:97%" value="<?php 
                echo htmlspecialchars(@$mod['titles'][$lang]);
                ?>
" placeholder="<?php 
                echo $_LANG['AD_HINT_DEFAULT'];
                ?>
" /></div>
                    <?php 
            }
            ?>
                    <?php 
        }
        ?>
                    <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:10px;">
                        <tr>
                            <td valign="top">
                                <div>
                                    <strong><?php 
        echo $_LANG['AD_MODULE_NAME'];
        ?>
</strong> <span class="hinttext">&mdash; <?php 
        echo $_LANG['AD_SHOW_ADMIN'];
        ?>
</span>
                                </div>
                                <div>
                                    <?php 
        if (!isset($mod['user']) || @$mod['user'] == 1) {
            ?>
                                        <input name="name" type="text" id="name" style="width:99%" value="<?php 
            echo htmlspecialchars($mod['name']);
            ?>
" />
                                    <?php 
        } else {
            ?>
                                        <input name="" type="text" id="name" style="width:99%" value="<?php 
            echo @$mod['name'];
            ?>
" disabled="disabled" />
                                        <input name="name" type="hidden" value="<?php 
            echo htmlspecialchars($mod['name']);
            ?>
" />
                                    <?php 
        }
        ?>
                                </div>
                            </td>
                            <td valign="top" width="160" style="padding-left:10px;">
                                <div>
                                    <strong><?php 
        echo $_LANG['AD_PREFIX_CSS'];
        ?>
</strong>
                                </div>
                                <div>
                                    <input name="css_prefix" type="text" id="css_prefix" value="<?php 
        echo @$mod['css_prefix'];
        ?>
" style="width:154px" />
                                </div>
                            </td>
                        </tr>
                    </table>

                    <div style="margin-top:8px">
                        <strong><?php 
        echo $_LANG['AD_DEFOLT_VIEW'];
        ?>
</strong> <span class="hinttext">&mdash; <?php 
        echo $_LANG['AD_POSITION_MUST_BE'];
        ?>
</span>
                    </div>
                    <div>
                        <?php 
        $pos = cpModulePositions(cmsConfig::getConfig('template'));
        ?>
                        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:5px;">
                            <tr>
                                <td valign="top">
                                    <select name="position" id="position" style="width:100%">
                                        <?php 
        if ($pos) {
            foreach ($pos as $key => $position) {
                if (@$mod['position'] == $position) {
                    echo '<option value="' . $position . '" selected>' . $position . '</option>';
                } else {
                    echo '<option value="' . $position . '">' . $position . '</option>';
                }
            }
        }
        ?>
                                    </select>
                                </td>
                                <?php 
        if (file_exists(PATH . '/templates/' . TEMPLATE . '/positions.jpg')) {
            ?>
                                <td valign="top" width="160" style="padding-left:10px;">
                                    <script>
                                    $(function() {
                                        $('#pos').dialog({modal: true, autoOpen: false, closeText: LANG_CLOSE, width: 'auto'});
                                    });
                                    </script>
                                    <a onclick="$('#pos').dialog('open');return false;" href="#" class="ajaxlink"><?php 
            echo $_LANG['AD_SEE_VISUALLY'];
            ?>
</a>
                                    <div id="pos" title="<?php 
            echo $_LANG['AD_TPL_POS'];
            ?>
"><img src="/templates/<?php 
            echo TEMPLATE;
            ?>
/positions.jpg" alt="<?php 
            echo $_LANG['AD_TPL_POS'];
            ?>
" /></div>
                                </td>
                                <?php 
        }
        ?>
                            </tr>
                        </table>
                    </div>

                    <div style="margin-top:15px">
                        <strong><?php 
        echo $_LANG['AD_MODULE_TEMPLATE'];
        ?>
</strong> <span class="hinttext">&mdash; <?php 
        echo $_LANG['AD_FOLDER_MODULES'];
        ?>
</span>
                    </div>
                    <div>
                        <?php 
        $tpls = cmsAdmin::getModuleTemplates();
        ?>
                        <select name="template" id="template" style="width:100%">
                            <?php 
        foreach ($tpls as $tpl) {
            $selected = $mod['template'] == $tpl || !$mod['template'] && $tpl == 'module.tpl' ? 'selected="selected"' : '';
            echo '<option value="' . $tpl . '" ' . $selected . '>' . $tpl . '</option>';
        }
        ?>
                        </select>
                    </div>

                    <?php 
        if ($do == 'add') {
            ?>
                    <div style="margin-top:15px">
                        <strong><?php 
            echo $_LANG['AD_MODULE_TYPE'];
            ?>
</strong>
                    </div>
                    <div>
                        <select name="operate" id="operate" onchange="checkDiv()" style="width:100%">
                            <option value="user" selected="selected"><?php 
            echo $_LANG['AD_MODULE_TYPE_NEW'];
            ?>
</option>
                            <option value="clone"><?php 
            echo $_LANG['AD_MODULE_TYPE_COPY'];
            ?>
</option>
                        </select>
                    </div>
                    <?php 
        }
        ?>

                    <?php 
        if (!isset($mod['user']) || $mod['user'] == 1 || $do == 'add') {
            ?>
                        <div id="user_div">
                            <div style="margin-top:15px">
                                <strong><?php 
            echo $_LANG['AD_MODULE_CONTENT'];
            ?>
</strong>
                            </div>
                            <div><?php 
            insertPanel();
            ?>
</div>
                            <div>
                                <?php 
            $inCore->insertEditor('content', $mod['content'], '250', '100%');
            ?>
                            </div>
                        </div>
                    <?php 
        }
        ?>

                <div id="clone_div" style="display:none;">
                        <div style="margin-top:15px">
                            <strong><?php 
        echo $_LANG['AD_MODULE_COPY'];
        ?>
</strong>
                        </div>
                        <div>
                            <select name="clone_id" id="clone_id" style="width:100%">
                                <?php 
        echo $inCore->getListItems('cms_modules');
        ?>
                            </select>
                            <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist" style="margin-top:6px">
                                <tr>
                                    <td width="20"><input type="checkbox" name="del_orig" id="del_orig" value="1" /></td>
                                    <td><label for="del_orig"><?php 
        echo $_LANG['AD_ORIGINAL_MODULE_DELETE'];
        ?>
</label></td>
                                </tr>
                            </table>
                        </div>
                </div>

                </td>

                <!-- боковая ячейка -->
                <td width="300" valign="top" style="background:#ECECEC;">

                    <?php 
        ob_start();
        ?>

                    {tab=<?php 
        echo $_LANG['AD_TAB_PUBLISH'];
        ?>
}

                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                        <tr>
                            <td width="20"><input type="checkbox" name="published" id="published" value="1" <?php 
        if ($mod['published'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="published"><strong><?php 
        echo $_LANG['AD_MODULE_PUBLIC'];
        ?>
</strong></label></td>
                        </tr>
                        <tr>
                            <td width="20"><input name="show_all" id="show_all" type="checkbox" value="1" onclick="checkGroupList()" <?php 
        if ($show_all) {
            echo 'checked';
        }
        ?>
 /></td>
                            <td><label for="show_all"><strong><?php 
        echo $_LANG['AD_VIEW_ALL_PAGES'];
        ?>
</strong></label></td>
                        </tr>
                    </table>

                    <?php 
        if ($do == 'edit') {
            $bind_sql = "SELECT * FROM cms_modules_bind WHERE module_id = " . $mod['id'];
            $bind_res = $inDB->query($bind_sql);
            $bind = array();
            $bind_pos = array();
            while ($r = $inDB->fetch_assoc($bind_res)) {
                $bind[] = $r['menu_id'];
                $bind_pos[$r['menu_id']] = $r['position'];
            }
        }
        $menu_sql = "SELECT * FROM cms_menu ORDER BY NSLeft, ordering";
        $menu_res = $inDB->query($menu_sql);
        $menu_items = array();
        if ($inDB->num_rows($menu_res)) {
            while ($item = $inDB->fetch_assoc($menu_res)) {
                if ($do == 'edit') {
                    if (in_array($item['id'], $bind)) {
                        $item['selected'] = true;
                        $item['position'] = $bind_pos[$item['id']];
                    }
                }
                $item['titles'] = cmsCore::yamlToArray($item['titles']);
                // переопределяем название пункта меню в зависимости от языка
                if (!empty($item['titles'][cmsConfig::getConfig('lang')])) {
                    $item['title'] = $item['titles'][cmsConfig::getConfig('lang')];
                }
                $item['title'] = str_replace($_LANG['AD_ROOT_PAGES'], $_LANG['AD_MAIN'], $item['title']);
                $menu_items[] = $item;
            }
        }
        ?>

                    <div id="grp">

                        <div style="margin-top:13px">
                            <strong class="show_list"><?php 
        echo $_LANG['AD_WHERE_MODULE_VIEW'];
        ?>
</strong>
                            <strong class="hide_list"><?php 
        echo $_LANG['AD_WHERE_MODULE_NOT_VIEW'];
        ?>
</strong>
                        </div>

                        <div style="height:300px;overflow: auto;border: solid 1px #999; padding:5px 10px; background: #FFF;">
                        <table cellpadding="0" cellspacing="0" border="0" width="100%" align="center">
                            <tr>
                                <td colspan="2" height="25"><strong><?php 
        echo $_LANG['AD_MENU'];
        ?>
</strong></td>
                                <td class="show_list" align="center" width="50"><strong><?php 
        echo $_LANG['AD_POSITION'];
        ?>
</strong></td>
                            </tr>
                            <?php 
        foreach ($menu_items as $i) {
            ?>
                            <tr class="show_list">
                                <td width="20" height="25">
                                    <input type="checkbox" name="showin[]" id="mid<?php 
            echo $i['id'];
            ?>
" value="<?php 
            echo $i['id'];
            ?>
" <?php 
            if ($i['selected']) {
                ?>
checked="checked"<?php 
            }
            ?>
 onclick="$('#p<?php 
            echo $i['id'];
            ?>
').toggle()"/>
                                </td>
                                <td style="padding-left:<?php 
            echo $i['NSLevel'] * 6 - 6;
            ?>
px"><label for="mid<?php 
            echo $i['id'];
            ?>
"><?php 
            echo $i['title'];
            ?>
</label></td>
                                <td align="center">
                                    <select id="p<?php 
            echo $i['id'];
            ?>
" name="showpos[<?php 
            echo $i['id'];
            ?>
]" style="<?php 
            if (!$i['selected']) {
                ?>
display:none<?php 
            }
            ?>
">
                                        <?php 
            foreach ($pos as $position) {
                ?>
                                            <option value="<?php 
                echo $position;
                ?>
" <?php 
                if ($i['position'] == $position) {
                    ?>
selected="selected"<?php 
                }
                ?>
><?php 
                echo $position;
                ?>
</option>
                                        <?php 
            }
            ?>
                                    </select>
                                </td>
                            </tr>
                            <?php 
        }
        ?>
                            <?php 
        foreach ($menu_items as $it) {
            ?>
                            <tr class="hide_list">
                                <td width="20" height="25">
                                    <input type="checkbox" name="hidden_menu_ids[]" id="hmid<?php 
            echo $it['id'];
            ?>
" value="<?php 
            echo $it['id'];
            ?>
" <?php 
            if (in_array($it['id'], $mod['hidden_menu_ids'])) {
                ?>
checked="checked"<?php 
            }
            ?>
 />
                                </td>
                                <td style="padding-left:<?php 
            echo $it['NSLevel'] * 6 - 6;
            ?>
px"><label for="hmid<?php 
            echo $it['id'];
            ?>
"><?php 
            echo $it['title'];
            ?>
</label></td>
                            </tr>
                            <?php 
        }
        ?>
                        </table>
                        </div>

                        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist show_list">
                            <tr>
                                <td width="20"><input type="checkbox" name="is_strict_bind" id="is_strict_bind" value="1" <?php 
        if ($mod['is_strict_bind']) {
            echo 'checked="checked"';
        }
        ?>
/></td>
                                <td><label for="is_strict_bind"><strong><?php 
        echo $_LANG['AD_DONT_VIEW'];
        ?>
</strong></label></td>
                            </tr>
                        </table>
                        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist hide_list">
                            <tr>
                                <td width="20"><input type="checkbox" name="is_strict_bind_hidden" id="is_strict_bind_hidden" value="1" <?php 
        if ($mod['is_strict_bind_hidden']) {
            echo 'checked="checked"';
        }
        ?>
/></td>
                                <td><label for="is_strict_bind_hidden"><strong><?php 
        echo $_LANG['AD_EXCEPT_NESTED'];
        ?>
</strong></label></td>
                            </tr>
                        </table>

                    </div>

					<?php 
        if ($mod['is_external'] && $do == 'edit' || $do == 'add') {
            ?>

                    {tab=<?php 
            echo $_LANG['AD_MODULE_CACHE'];
            ?>
}

                        <div style="margin-top:4px">
                            <strong><?php 
            echo $_LANG['AD_DO_MODULE_CACHE'];
            ?>
</strong>
                        </div>
                        <div>
                            <select name="cache" id="cache" style="width:100%">
                                <option value="0" <?php 
            if (@(!$mod['cache'])) {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo $_LANG['NO'];
            ?>
</option>
                                <option value="1" <?php 
            if (@$mod['cache']) {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo $_LANG['YES'];
            ?>
</option>
                            </select>
                        </div>

                        <div style="margin-top:15px">
                            <strong><?php 
            echo $_LANG['AD_MODULE_CACHE_PERIOD'];
            ?>
</strong>
                        </div>
                        <div>
                            <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:5px;">
                                <tr>
                                    <td valign="top"  width="100">
                                        <input name="cachetime" type="text" id="int_1" style="width:99%" value="<?php 
            echo @(int) $mod['cachetime'];
            ?>
"/>
                                    </td>
                                    <td valign="top" style="padding-left:5px">
                                        <select name="cacheint" id="int_2" style="width:100%">
                                            <option value="MINUTE"  <?php 
            if (@mb_strstr($mod['cacheint'], 'MINUTE')) {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo cmsCore::spellCount((int) @$mod['cachetime'], $_LANG['MINUTE1'], $_LANG['MINUTE2'], $_LANG['MINUTE10'], false);
            ?>
</option>
                                            <option value="HOUR"  <?php 
            if (@mb_strstr($mod['cacheint'], 'HOUR')) {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo cmsCore::spellCount((int) @$mod['cachetime'], $_LANG['HOUR1'], $_LANG['HOUR2'], $_LANG['HOUR10'], false);
            ?>
</option>
                                            <option value="DAY" <?php 
            if (@mb_strstr($mod['cacheint'], 'DAY')) {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo cmsCore::spellCount((int) @$mod['cachetime'], $_LANG['DAY1'], $_LANG['DAY2'], $_LANG['DAY10'], false);
            ?>
</option>
                                            <option value="MONTH" <?php 
            if (@mb_strstr($mod['cacheint'], 'MONTH')) {
                echo 'selected="selected"';
            }
            ?>
><?php 
            echo cmsCore::spellCount((int) @$mod['cachetime'], $_LANG['MONTH1'], $_LANG['MONTH2'], $_LANG['MONTH10'], false);
            ?>
</option>
                                        </select>
                                    </td>
                                </tr>
                            </table>
                        </div>

                        <div style="margin-top:15px">
                            <?php 
            if ($do == 'edit') {
                if ($inCore->isCached('module', $mod['id'], $mod['cachetime'], $mod['cacheint'])) {
                    $t = 'module' . $mod['id'];
                    $cfile = PATH . '/cache/' . md5($t) . '.html';
                    if (file_exists($cfile)) {
                        $kb = round(filesize($cfile) / 1024, 2);
                        echo '<a href="index.php?view=cache&do=delcache&target=module&id=' . $mod['id'] . '">' . $_LANG['AD_MODULE_CACHE_DELETE'] . '</a> (' . $kb . $_LANG['SIZE_KB'] . ')';
                    }
                } else {
                    echo '<span style="color:gray">' . $_LANG['AD_NO_CACHE'] . '</span>';
                }
            }
            ?>
                        </div>
					<?php 
        }
        ?>

                    {tab=<?php 
        echo $_LANG['AD_TAB_ACCESS'];
        ?>
}
                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist" style="margin-top:5px">
                        <tr>
                            <td width="20">
                                <?php 
        $groups = cmsUser::getGroups();
        $style = 'disabled="disabled"';
        $public = 'checked="checked"';
        if ($do == 'edit') {
            if ($mod['access_list']) {
                $public = '';
                $style = '';
                $access_list = $inCore->yamlToArray($mod['access_list']);
            }
        }
        ?>
                                <input name="is_public" type="checkbox" id="is_public" onclick="checkAccesList()" value="1" <?php 
        echo $public;
        ?>
 />
                            </td>
                            <td><label for="is_public"><strong><?php 
        echo $_LANG['AD_SHARE'];
        ?>
</strong></label></td>
                        </tr>
                    </table>
                    <div style="padding:5px">
                        <span class="hinttext">
                            <?php 
        echo $_LANG['AD_IF_CHECKED'];
        ?>
                        </span>
                    </div>

                    <div style="margin-top:10px;padding:5px;padding-right:0px;">
                        <div>
                            <strong><?php 
        echo $_LANG['AD_GROUPS_VIEW'];
        ?>
</strong><br />
                            <span class="hinttext">
                                <?php 
        echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];
        ?>
                            </span>
                        </div>
                        <div>
                            <?php 
        echo '<select style="width: 99%" name="allow_group[]" id="allow_group" size="6" multiple="multiple" ' . $style . '>';
        if ($groups) {
            foreach ($groups as $group) {
                echo '<option value="' . $group['id'] . '"';
                if ($do == 'edit' && $mod['access_list']) {
                    if (inArray($access_list, $group['id'])) {
                        echo 'selected="selected"';
                    }
                }
                echo '>';
                echo $group['title'] . '</option>';
            }
        }
        echo '</select>';
        ?>
                        </div>
                    </div>

                    {/tabs}

                    <?php 
        echo jwTabs(ob_get_clean());
        ?>

                </td>

            </tr>
        </table>
        <p>
            <input name="add_mod" type="submit" id="add_mod" value="<?php 
        echo $_LANG['SAVE'];
        ?>
" />
            <input name="back" type="button" id="back" value="<?php 
        echo $_LANG['CANCEL'];
        ?>
" onclick="window.history.back();" />
            <input name="do" type="hidden" id="do" <?php 
        if ($do == 'add') {
            echo 'value="submit"';
        } else {
            echo 'value="update"';
        }
        ?>
 />
            <?php 
        if ($do == 'edit') {
            echo '<input name="id" type="hidden" value="' . $mod['id'] . '" />';
        }
        ?>
        </p>
    </form>
<?php 
    }
    //============================================================================//
    //============================================================================//
}
Example #9
0
 /**
  * Регистрирует поля подлежащие переводу
  * @param str $target Цель
  * @param array $fields массив подлежащих переводу полей и их типов 'поле'=>'str|html'
  */
 public static function registerFields($target, $fields)
 {
     cmsDatabase::getInstance()->insert('cms_translations_fields', array('target' => $target, 'fields' => cmsCore::arrayToYaml($fields)), true);
 }
Example #10
0
function applet_modules()
{
    $inCore = cmsCore::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) {
        cpAccessDenied();
    }
    cmsCore::c('page')->setTitle($_LANG['AD_MODULES']);
    cpAddPathway($_LANG['AD_MODULES'], 'index.php?view=modules');
    cmsCore::c('page')->addHeadJS('admin/js/modules.js');
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    $co = cmsCore::request('co', 'int', -1);
    if ($do == 'config') {
        $module_name = cpModuleById($id);
        $module_title = cpModuleTitleById($id);
        if (!$module_name) {
            cmsCore::redirect('index.php?view=modules&do=edit&id=' . $id);
        }
        $xml_file = PATH . '/admin/modules/' . $module_name . '/backend.xml';
        $php_file = 'modules/' . $module_name . '/backend.php';
        if (file_exists($php_file)) {
            include $php_file;
            return;
        }
        $cfg = $inCore->loadModuleConfig($id);
        cpAddPathway($module_title, '?view=modules&do=edit&id=' . $id);
        cpAddPathway($_LANG['AD_SETTINGS']);
        $toolmenu = array(array('icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:submitModuleConfig();'), array('icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'index.php?view=modules'), array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_MODULE_VIEW'], 'link' => '?view=modules&do=edit&id=' . $id));
        cpToolMenu($toolmenu);
        $tpl = cmsCore::c('page')->initTemplate('applets', 'modules_config')->assign('module_title', $module_title)->assign('id', $id);
        if (file_exists($xml_file)) {
            cmsCore::loadClass('formgen');
            $formGen = new cmsFormGen($xml_file, $cfg);
            $tpl->assign('formGenHtml', $formGen->getHTML());
        } else {
            $tpl->assign('cfg', $cfg);
        }
        $tpl->display();
    }
    if ($do == 'save_auto_config') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $module_name = cpModuleById($id);
        $is_ajax = cmsCore::inRequest('ajax');
        if ($is_ajax) {
            $title = cmsCore::request('title', 'str', '');
            $published = cmsCore::request('published', 'int', 0);
            cmsCore::c('db')->query("UPDATE cms_modules SET title='" . $title . "', published='" . $published . "' WHERE id=" . $id);
            if (cmsCore::inRequest('content')) {
                $content = cmsCore::c('db')->escape_string(cmsCore::request('content', 'html'));
                cmsCore::c('db')->query("UPDATE cms_modules SET content='" . $content . "' WHERE id=" . $id);
            }
        }
        if (cmsCore::inRequest('title_only')) {
            cmsCore::redirectBack();
        }
        $xml_file = PATH . '/admin/modules/' . $module_name . '/backend.xml';
        if (file_exists($xml_file)) {
            $cfg = array();
            $backend = simplexml_load_file($xml_file);
            foreach ($backend->params->param as $param) {
                $name = (string) $param['name'];
                $type = (string) $param['type'];
                $default = (string) $param['default'];
                switch ($param['type']) {
                    case 'number':
                        $value = cmsCore::request($name, 'int', $default);
                        break;
                    case 'string':
                        $value = cmsCore::request($name, 'str', $default);
                        break;
                    case 'html':
                        $value = cmsCore::badTagClear(cmsCore::request($name, 'html', $default));
                        break;
                    case 'flag':
                        $value = cmsCore::request($name, 'int', 0);
                        break;
                    case 'list':
                        $value = is_array($_POST[$name]) ? cmsCore::request($name, 'array_str', $default) : cmsCore::request($name, 'str', $default);
                        break;
                    case 'list_function':
                        $value = cmsCore::request($name, 'str', $default);
                        break;
                    case 'list_db':
                        $value = is_array($_POST[$name]) ? cmsCore::request($name, 'array_str', $default) : cmsCore::request($name, 'str', $default);
                        break;
                }
                $cfg[$name] = $value;
            }
        }
        $cfg['tpl'] = cmsCore::request('tpl', 'str', $module_name);
        $inCore->saveModuleConfig($id, $cfg);
        if (!$is_ajax) {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        }
        cmsCore::redirectBack();
    }
    if ($do == 'list') {
        $toolmenu = array(array('icon' => 'new.gif', 'title' => $_LANG['AD_MODULE_ADD'], 'link' => '?view=modules&do=add'), array('icon' => 'install.gif', 'title' => $_LANG['AD_MODULES_SETUP'], 'link' => '?view=install&do=module'), array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=edit&multiple=1');"), array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=delete&multiple=1');"), array('icon' => 'show.gif', 'title' => $_LANG['AD_ALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=show&multiple=1');"), array('icon' => 'hide.gif', 'title' => $_LANG['AD_DISALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=modules&do=hide&multiple=1');"), array('icon' => 'autoorder.gif', 'title' => $_LANG['AD_MODULE_ORDER'], 'link' => '?view=modules&do=autoorder'), array('icon' => 'reorder.gif', 'title' => $_LANG['AD_SAVE_ORDER'], 'link' => "javascript:checkSel('?view=modules&do=saveorder');"), array('icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=modules'));
        cpToolMenu($toolmenu);
        $fields = array(array('title' => 'id', 'field' => 'id', 'width' => '40'), array('title' => $_LANG['AD_TITLE'], 'field' => array('title', 'titles'), 'width' => '', 'link' => '?view=modules&do=edit&id=%id%', 'prc' => function ($i) {
            $i['titles'] = cmsCore::yamlToArray($i['titles']);
            // переопределяем название пункта меню в зависимости от языка
            if (!empty($i['titles'][cmsConfig::getConfig('lang')])) {
                $i['title'] = $i['titles'][cmsConfig::getConfig('lang')];
            }
            return $i['title'];
        }), array('title' => $_LANG['TITLE'], 'field' => 'name', 'width' => '220', 'filter' => '15'), array('title' => $_LANG['AD_VERSION'], 'field' => 'version', 'width' => '70'), array('title' => $_LANG['AD_AUTHOR'], 'field' => 'author', 'width' => '110'), array('title' => $_LANG['SHOW'], 'field' => 'published', 'width' => '80'), array('title' => $_LANG['AD_ORDER'], 'field' => 'ordering', 'width' => '100'), array('title' => $_LANG['AD_POSITION'], 'field' => 'position', 'width' => '80', 'filter' => '10', 'filterlist' => cpGetList('positions')));
        $actions = array(array('title' => $_LANG['AD_CONFIG'], 'icon' => 'config.gif', 'link' => '?view=modules&do=config&id=%id%', 'condition' => 'cpModuleHasConfig'), array('title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=modules&do=edit&id=%id%'), array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_MODULE_DELETE'], 'link' => '?view=modules&do=delete&id=%id%'));
        cpListTable('cms_modules', $fields, $actions, '', 'published DESC, position, ordering ASC');
    }
    if ($do == 'autoorder') {
        $rs = cmsCore::c('db')->query("SELECT id, position FROM cms_modules ORDER BY position");
        if (cmsCore::c('db')->num_rows($rs)) {
            $ord = 1;
            while ($item = cmsCore::c('db')->fetch_assoc($rs)) {
                if (isset($latest_pos)) {
                    if ($latest_pos != $item['position']) {
                        $ord = 1;
                    }
                }
                cmsCore::c('db')->query("UPDATE cms_modules SET ordering = " . $ord . " WHERE id=" . $item['id']);
                $ord += 1;
                $latest_pos = $item['position'];
            }
        }
        cmsCore::redirect('index.php?view=modules');
    }
    if ($do == 'move_up') {
        if ($id >= 0) {
            dbMoveUp('cms_modules', $id, $co);
        }
        cmsCore::redirectBack();
    }
    if ($do == 'move_down') {
        if ($id >= 0) {
            dbMoveDown('cms_modules', $id, $co);
        }
        cmsCore::redirectBack();
    }
    if ($do == 'saveorder') {
        if (isset($_REQUEST['ordering'])) {
            $ord = $_REQUEST['ordering'];
            $ids = $_REQUEST['ids'];
            foreach ($ord as $id => $ordering) {
                cmsCore::c('db')->query("UPDATE cms_modules SET ordering = " . (int) $ordering . " WHERE id = " . (int) $ids[$id]);
            }
            cmsCore::redirect('index.php?view=modules');
        }
    }
    if ($do == 'show') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                cmsCore::c('db')->setFlag('cms_modules', $id, 'published', '1');
            }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_modules', $_REQUEST['item'], 'published', '1');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'hide') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                cmsCore::c('db')->setFlag('cms_modules', $id, 'published', '0');
            }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_modules', $_REQUEST['item'], 'published', '0');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            $inCore->removeModule($id);
        } else {
            $inCore->removeModule(cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('index.php?view=modules');
    }
    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $id = cmsCore::request('id', 'int', 0);
        $mod = cmsCore::c('db')->get_fields('cms_modules', "id = " . $id . "", '*');
        $module = array('name' => cmsCore::request('name', 'str', ''), 'title' => cmsCore::request('title', 'str', ''), 'titles' => cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array())), 'position' => cmsCore::request('position', 'str', ''), 'showtitle' => cmsCore::request('showtitle', 'int', 0), 'published' => cmsCore::request('published', 'int', 0), 'css_prefix' => cmsCore::request('css_prefix', 'str', ''), 'is_strict_bind' => cmsCore::request('is_strict_bind', 'int', 0), 'is_strict_bind_hidden' => cmsCore::request('is_strict_bind_hidden', 'int', 0), 'template' => cmsCore::request('template', 'str', ''), 'cache' => cmsCore::request('cache', 'int', 0), 'cachetime' => cmsCore::request('cachetime', 'int', 0), 'cacheint' => cmsCore::request('cacheint', 'str', ''), 'access_list' => '', 'hidden_menu_ids' => '');
        if (!$mod['is_external']) {
            $module['content'] = cmsCore::c('db')->escape_string(cmsCore::request('content', 'html', ''));
        }
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $module['access_list'] = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int', array()));
        }
        cmsCore::c('db')->update('cms_modules', $module, $id);
        cmsCore::c('db')->delete('cms_modules_bind', "module_id=" . $id . " AND tpl='" . cmsCore::c('config')->template . "'");
        if (cmsCore::request('show_all', 'int', 0)) {
            cmsCore::c('db')->insert('cms_modules_bind', array('module_id' => $id, 'menu_id' => 0, 'position' => $module['position'], 'tpl' => cmsCore::c('config')->template));
            $hidden_menu_ids = cmsCore::request('hidden_menu_ids', 'array_int', array());
            if (!empty($hidden_menu_ids)) {
                $hidden_menu_ids = cmsCore::arrayToYaml($hidden_menu_ids);
                cmsCore::c('db')->query("UPDATE cms_modules SET hidden_menu_ids='" . $hidden_menu_ids . "' WHERE id = '" . $id . "' LIMIT 1");
            }
        } else {
            $showin = cmsCore::request('showin', 'array_int', array());
            $showpos = cmsCore::request('showpos', 'array_str', array());
            if (count($showin) > 0) {
                foreach ($showin as $key => $value) {
                    cmsCore::c('db')->insert('cms_modules_bind', array('module_id' => $id, 'menu_id' => $value, 'position' => $showpos[$value], 'tpl' => cmsCore::c('config')->template));
                }
            }
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        if (!isset($_SESSION['editlist']) || count($_SESSION['editlist']) == 0) {
            cmsCore::redirect('index.php?view=modules');
        } else {
            cmsCore::redirect('index.php?view=modules&do=edit');
        }
    }
    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $maxorder = cmsCore::c('db')->get_field('cms_menu', '1=1 ORDER BY ordering DESC', 'ordering') + 1;
        $name = cmsCore::request('name', 'str', '');
        $title = cmsCore::request('title', 'str', '');
        $titles = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $position = cmsCore::request('position', 'str', '');
        $showtitle = cmsCore::request('showtitle', 'int', 0);
        $content = cmsCore::c('db')->escape_string(cmsCore::request('content', 'html', ''));
        $published = cmsCore::request('published', 'int', 0);
        $css_prefix = cmsCore::request('css_prefix', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int', array()));
        }
        $template = cmsCore::request('template', 'str', '');
        $cache = cmsCore::request('cache', 'int', 0);
        $cachetime = cmsCore::request('cachetime', 'int', 0);
        $cacheint = cmsCore::request('cacheint', 'str', '');
        $operate = cmsCore::request('operate', array('user', 'clone'), '');
        $is_strict_bind = cmsCore::request('is_strict_bind', 'int', 0);
        $is_strict_bind_hidden = cmsCore::request('is_strict_bind_hidden', 'int', 0);
        if ($operate == 'user') {
            //USER MODULE
            $sql = "INSERT INTO cms_modules (position, name, title, titles, is_external, content, ordering, showtitle, published, user, original, css_prefix, access_list, template, is_strict_bind, is_strict_bind_hidden)\r\n                            VALUES ('" . $position . "', '" . $name . "', '" . $title . "', '" . $titles . "', 0, '" . $content . "', '" . $maxorder . "', '" . $showtitle . "', '" . $published . "', 1, 1, '" . $css_prefix . "', '" . $access_list . "', '" . $template . "', '" . $is_strict_bind . "', '" . $is_strict_bind_hidden . "')";
            cmsCore::c('db')->query($sql);
        }
        if ($operate == 'clone') {
            //DUPLICATE MODULE
            $mod_id = cmsCore::request('clone_id', 'int', 0);
            $sql = "SELECT * FROM cms_modules WHERE id = " . $mod_id . " LIMIT 1";
            $result = cmsCore::c('db')->query($sql);
            $original = cmsCore::c('db')->escape_string(cmsCore::c('db')->fetch_assoc($result));
            $is_original = cmsCore::request('del_orig', 'int', 0) ? 1 : 0;
            $sql = "INSERT INTO cms_modules (position, name, title, titles, is_external, content, ordering, showtitle, published, original, user, config, css_prefix, template, access_list, is_strict_bind, is_strict_bind_hidden, cache, cachetime, cacheint, version)\r\n                        VALUES (\r\n                            '" . $position . "',\r\n                            '" . $original['name'] . "',\r\n                            '" . $title . "',\r\n                            '" . $titles . "',\r\n                            '" . $original['is_external'] . "',\r\n                            '" . $original['content'] . "',\r\n                            '" . $maxorder . "',\r\n                            '" . $showtitle . "',\r\n                            '" . $published . "',\r\n                            '" . $is_original . "',\r\n                            '" . $original['user'] . "',\r\n                            '" . $original['config'] . "',\r\n                            '" . $css_prefix . "',\r\n                            '" . $template . "',\r\n                            '" . $access_list . "',\r\n                            '" . $is_strict_bind . "',\r\n                            '" . $is_strict_bind_hidden . "',\r\n                            '" . $cache . "', \r\n                            '" . $cachetime . "',\r\n                            '" . $cacheint . "',\r\n                            '" . $original['version'] . "'\r\n                )";
            cmsCore::c('db')->query($sql);
            if (cmsCore::request('del_orig', 'int', 0)) {
                $sql = "DELETE FROM cms_modules WHERE id = " . $mod_id;
                cmsCore::c('db')->query($sql);
            }
        }
        $lastid = cmsCore::c('db')->get_last_id('cms_modules');
        if (cmsCore::request('show_all', 'int', 0)) {
            $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position, tpl)\r\n                            VALUES (" . $lastid . ", 0, '" . $position . "', '" . cmsCore::c('config')->template . "')";
            cmsCore::c('db')->query($sql);
            $hidden_menu_ids = cmsCore::request('hidden_menu_ids', 'array_int', array());
            if ($hidden_menu_ids) {
                $hidden_menu_ids = cmsCore::arrayToYaml($hidden_menu_ids);
                cmsCore::c('db')->query("UPDATE cms_modules SET hidden_menu_ids='" . $hidden_menu_ids . "' WHERE id = '" . $lastid . "' LIMIT 1");
            }
        } else {
            $showin = cmsCore::request('showin', 'array', array());
            $showpos = cmsCore::request('showpos', 'array', array());
            if (count($showin) > 0) {
                foreach ($showin as $key => $value) {
                    $sql = "INSERT INTO cms_modules_bind (module_id, menu_id, position, tpl)\r\n                                    VALUES (" . $lastid . ", " . $value . ", '" . $showpos[$value] . "', '" . cmsCore::c('config')->template . "')";
                    cmsCore::c('db')->query($sql);
                }
            }
        }
        cmsCore::addSessionMessage($_LANG['AD_MODULE_ADD_SITE'], 'success');
        cmsCore::redirect('index.php?view=modules');
    }
    if ($do == 'add' || $do == 'edit') {
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_MODULE_ADD']);
            echo '<h3>' . $_LANG['AD_MODULE_ADD'] . '</h3>';
            $show_all = false;
        } else {
            if (cmsCore::inRequest('multiple')) {
                if (cmsCore::inRequest('item')) {
                    $_SESSION['editlist'] = cmsCore::request('item', 'array_int', array());
                } else {
                    cmsCore::addSessionMessage($_LANG['AD_NO_SELECT_OBJECTS'], 'error');
                    cmsCore::redirectBack();
                }
            }
            $ostatok = '';
            if (isset($_SESSION['editlist'])) {
                $item_id = array_shift($_SESSION['editlist']);
                if (count($_SESSION['editlist']) == 0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '(' . $_LANG['AD_NEXT_IN'] . count($_SESSION['editlist']) . ')';
                }
            } else {
                $item_id = cmsCore::request('id', 'int', 0);
            }
            $mod = cmsCore::c('db')->get_fields('cms_modules', "id = '" . $item_id . "'", '*');
            if (!$mod) {
                cmsCore::error404();
            }
            $mod['hidden_menu_ids'] = cmsCore::yamlToArray($mod['hidden_menu_ids']);
            $mod['titles'] = cmsCore::yamlToArray($mod['titles']);
            $show_all = false;
            $default_position = cmsCore::c('db')->get_field('cms_modules_bind', "module_id='" . $mod['id'] . "' AND menu_id=0 AND tpl='" . cmsCore::c('config')->template . "'", 'position');
            if (!empty($default_position)) {
                $show_all = true;
                $mod['position'] = $default_position;
            }
            echo '<h3>' . $_LANG['AD_EDIT_MODULE'] . $ostatok . '</h3>';
            cpAddPathway($mod['name']);
        }
        $toolmenu[] = array('icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:document.addform.submit();');
        $toolmenu[] = array('icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'javascript:history.go(-1);');
        if (cmsCore::getArrVal($mod, 'is_external')) {
            $php_file = 'modules/' . $mod['content'] . '/backend.php';
            $xml_file = 'modules/' . $mod['content'] . '/backend.xml';
            if (file_exists($php_file) || file_exists($xml_file)) {
                $toolmenu[] = array('icon' => 'config.gif', 'title' => $_LANG['CONFIG_MODULE'], 'link' => '?view=modules&do=config&id=' . $mod['id']);
            }
        }
        cpToolMenu($toolmenu);
        $bind = array();
        $bind_pos = array();
        $cache = 0;
        if ($do == 'edit') {
            $bind_sql = "SELECT * FROM cms_modules_bind WHERE module_id = " . $mod['id'] . " AND tpl = '" . cmsCore::c('config')->template . "'";
            $bind_res = cmsCore::c('db')->query($bind_sql);
            while ($r = cmsCore::c('db')->fetch_assoc($bind_res)) {
                $bind[] = $r['menu_id'];
                $bind_pos[$r['menu_id']] = $r['position'];
            }
            $cache = cmsCore::c('cache')->get('modules', $mod['id'], $mod['content'], array(cmsCore::getArrVal($mod, 'cachetime', 1), cmsCore::getArrVal($mod, 'cacheint', 'MINUTES')));
        }
        $menu_sql = "SELECT * FROM cms_menu ORDER BY NSLeft, ordering";
        $menu_res = cmsCore::c('db')->query($menu_sql);
        $menu_items = array();
        if (cmsCore::c('db')->num_rows($menu_res)) {
            while ($item = cmsCore::c('db')->fetch_assoc($menu_res)) {
                if ($do == 'edit') {
                    if (in_array($item['id'], $bind)) {
                        $item['selected'] = true;
                        $item['position'] = $bind_pos[$item['id']];
                    }
                }
                $item['titles'] = cmsCore::yamlToArray($item['titles']);
                // переопределяем название пункта меню в зависимости от языка
                if (!empty($item['titles'][cmsCore::c('config')->lang])) {
                    $item['title'] = $item['titles'][cmsCore::c('config')->lang];
                }
                $item['title'] = str_replace($_LANG['AD_ROOT_PAGES'], $_LANG['AD_MAIN'], $item['title']);
                $menu_items[] = $item;
            }
        }
        cmsCore::c('page')->initTemplate('applets', 'modules_add')->assign('do', $do)->assign('langs', cmsCore::getDirsList('/languages'))->assign('pos', cpModulePositions(cmsCore::c('config')->template))->assign('positions_img_exist', file_exists(PATH . '/templates/' . cmsCore::c('config')->template . '/positions.jpg'))->assign('tpls', cmsAdmin::getModuleTemplates())->assign('modules_opt', $inCore->getListItems('cms_modules'))->assign('show_all', $show_all)->assign('groups', cmsUser::getGroups())->assign('kb_cache', !empty($cache) ? round(mb_strlen($cache) / 1024, 2) : false)->assign('menu_items', $menu_items)->assign('access_list', !empty($mod['access_list']) ? $inCore->yamlToArray($mod['access_list']) : array())->assign('mod', $mod)->display();
    }
}
Example #11
0
function catalog(){

    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();

    global $_LANG;

    $model = new cms_model_catalog();

    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) { cmsCore::loadClass('billing'); }

    $pagetitle = $inCore->getComponentTitle();

	$inPage->addPathway($pagetitle, '/catalog');
	$inPage->setTitle($pagetitle);

	$inPage->setDescription($model->config['meta_desc'] ? $model->config['meta_desc'] : $pagetitle);
    $inPage->setKeywords($model->config['meta_keys'] ? $model->config['meta_keys'] : $pagetitle);

    $cfg = $inCore->loadComponentConfig('catalog');

    if (cmsCore::inRequest('cat_id')){
        $id = cmsCore::request('cat_id', 'int', 0);
    } else {
        $id = cmsCore::request('id', 'int', 0);
    }

    $do = $inCore->do;

    cmsCore::includeFile('components/catalog/includes/shopcore.php');

    //////////////////////////// RATING SUBMISSION ///////////////////////////////////////////////////////////////////
    if (cmsCore::inRequest('rating')){
        $points     = cmsCore::request('points', 'int', 0);
        $item_id    = cmsCore::request('item_id', 'int', 0);
        $ip         = $inUser->ip;
        if (!alreadyVoted($item_id)){
            $inDB->query("INSERT INTO cms_uc_ratings (item_id, points, ip) VALUES ($item_id, $points, '$ip')") ;
            $inDB->query("DELETE FROM cms_uc_ratings WHERE item_id = $item_id AND ip = '0.0.0.0'") ;
        }
    }

    //////////////////////////// SEARCH BY TAG ///////////////////////////////////////////////////////////////////////
    if ($do == 'tag') {

		$tag = $inCore->strClear(urldecode($inCore->request('tag', 'html', '')));

        $sql = "SELECT tag FROM cms_tags WHERE tag = '$tag' AND target='catalog' LIMIT 1";
        $result = $inDB->query($sql) ;
        if ($inDB->num_rows($result)==1){
            $item = $inDB->fetch_assoc($result);
            $query = $inCore->strClear($item['tag']);
            $findsql = "SELECT *
                        FROM cms_uc_items
                        WHERE category_id = '$id' AND published = 1 AND tags LIKE '%$query%'";
            $do = 'cat';
        } else { echo $_LANG['NO_MATCHING_FOUND']; }

    }
    //////////////////////////// ADVANCED SEARCH ////////////////////////////////////////////////////////////////////
    if ($do == 'search') {

        if (cmsCore::inRequest('gosearch')){

            $fdata = cmsCore::request('fdata', 'array', array());
            $query = cmsCore::strClear(implode('%', $fdata));
            $title = cmsCore::request('title', 'str', '');
            $tags  = cmsCore::request('tags', 'str', '');

            if ($query || $title || $tags){

                $findsql = "SELECT i.* , IFNULL(AVG(r.points),0) AS rating
                            FROM cms_uc_items i
                            LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                            WHERE i.published = 1 AND i.category_id = '$id' ";

                if($query){
                    $findsql .= " AND i.fieldsdata LIKE '%{$query}%' ";
                }
                if($title){
                    $findsql .= " AND i.title LIKE '%$title%' ";
                }
                if($tags){
                    $findsql .= "AND (i.tags LIKE '%".$tags."%')";
                }

                $findsql .=	" GROUP BY i.id";
                $advsearch = 1;
            }
            $do = 'cat';
        } else {
            //show search form
            $sql = "SELECT * FROM cms_uc_cats WHERE id = '$id'";
            $result = $inDB->query($sql) ;

            if ($inDB->num_rows($result)==1){
                $cat = $inDB->fetch_assoc($result);
                $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

                //heading
                $inPage->addPathway($cat['title'], '/catalog/'.$cat['id']);
                $inPage->addPathway($_LANG['SEARCH'], '/catalog/'.$cat['id'].'/search.html');
                $inPage->setTitle($_LANG['SEARCH_IN_CAT']);

                $inPage->addHeadJS('components/catalog/js/search.js');

                $fstruct_ready = array();
                foreach($fstruct as $key=>$value) {
                    if (mb_strstr($value, '/~h~/')) { $ftype = 'html'; $value=str_replace('/~h~/', '', $value); }
                    elseif (mb_strstr($value, '/~l~/')) { $ftype = 'link'; $value=str_replace('/~l~/', '', $value); } else { $ftype='text'; }
                    if (mb_strstr($value, '/~m~/')) {
                        $value = str_replace('/~m~/', '', $value);
                    }
                    $fstruct_ready[stripslashes($key)] = stripslashes($value);
                }

                //searchform
                cmsPage::initTemplate('components', 'com_catalog_search')->
                        assign('id', $id)->
                        assign('cat', $cat)->
                        assign('fstruct', $fstruct_ready)->
                        display('com_catalog_search.tpl');

            } else { cmsCore::error404(); }
        }//search form

    }
    //////////////////////////// SEARCH BY FIRST LETTER OF TITLE ///////////////////////////////////////////////////////
    if ($do == 'findfirst') {

        $id = cmsCore::request('cat_id', 'int');

		$query = mb_substr(cmsCore::strClear(urldecode(cmsCore::request('text', 'html', ''))), 0, 1);

        $findsql = "SELECT i.* , IFNULL(AVG( r.points ),0) AS rating
                    FROM cms_uc_items i
                    LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id AND UPPER(LTRIM(i.title)) LIKE UPPER('$query%')
                    GROUP BY i.id";

        $do = 'cat';
        $advsearch = 0;

        $pagemode = 'findfirst';

    }

    //////////////////////////// SEARCH BY FIELD ////////////////////////////////////////////////////////////////////
    if ($do == 'find') {

        $id = cmsCore::request('cat_id', 'int');

        $query = cmsCore::strClear(urldecode(cmsCore::request('text', 'html', '')));

        $findsql = "SELECT i.* , IFNULL(AVG(r.points),0) AS rating
                    FROM cms_uc_items i
                    LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id AND i.fieldsdata LIKE '%$query%'
                    GROUP BY i.id";

        $do = 'cat';
        $advsearch = 0;

		$query = stripslashes($query);

        $pagemode = 'find';
    }

    //////////////////////////// LIST OF CATEGORIES ////////////////////////////////////////////////////////////////////
    if ($do == 'view'){ //List of all categories

        $cats_html = subCatsList();
        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['CATALOG'].'" href="'.HOST.'/rss/catalog/all/feed.rss">');
        cmsPage::initTemplate('components', 'com_catalog_index')->
                assign('cfg', $cfg)->
                assign('title', $pagetitle)->
                assign('cats_html', $cats_html)->
                display('com_catalog_index.tpl');

    }

    //////////////////////////// VIEW CATEGORY ///////////////////////////////////////////////////////////////////////
    if ($do == 'cat'){

        //get category data
        $sql = "SELECT * FROM cms_uc_cats WHERE id = $id";
        $catres = $inDB->query($sql);
        if (!$inDB->num_rows($catres)){ cmsCore::error404(); }

        $cat     = $inDB->fetch_assoc($catres);
        $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

        $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['CATALOG'].'" href="'.HOST.'/rss/catalog/'.$cat['id'].'/feed.rss">');

        //heading
        //PATHWAY ENTRY
        $path_list = $model->getCategoryPath($cat['NSLeft'], $cat['NSRight']);
        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/catalog/'.$pcat['id']);
            }
        }
        $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']);

        //subcategories
        $subcats = subCatsList($cat['id'], $cat['NSLeft'], $cat['NSRight']);

        //alphabetic list
        if ($cat['showabc']){ $alphabet = getAlphaList($cat['id']);	} else { $alphabet = ''; }

        //Tool links
        $shopcartlink = shopCartLink();

        //get items SQL
        if (!isset($findsql)){
            $sql = "SELECT i.* , IFNULL(AVG( r.points ), 0) AS rating, i.price as price
                    FROM cms_uc_items i
                    LEFT JOIN cms_uc_ratings r ON r.item_id = i.id
                    WHERE i.published = 1 AND i.category_id = $id
                    GROUP BY i.id";
        } else {
            $sql = $findsql;
            if (!$advsearch){ $inPage->addPathway(icms_ucfirst($query)); } else
            { $inPage->addPathway($_LANG['SEARCH_RESULT']); }
        }

        // сортировка
        if(cmsCore::inRequest('orderby')){
            $orderby = cmsCore::request('orderby', array('hits','rating','pubdate','title','price'), $cat['orderby']);
            cmsUser::sessionPut('uc_orderby', $orderby);
        } elseif(cmsUser::sessionGet('uc_orderby')){
            $orderby = cmsUser::sessionGet('uc_orderby');
        } else {
            $orderby = $cat['orderby'];
        }
        if(cmsCore::inRequest('orderto')){
            $orderto = cmsCore::request('orderto', array('asc','desc'), $cat['orderto']);
            cmsUser::sessionPut('uc_orderto', $orderto);
        } elseif(cmsUser::sessionGet('uc_orderto')){
            $orderto = cmsUser::sessionGet('uc_orderto');
        } else {
            $orderto = $cat['orderto'];
        }

        $sql .=  " ORDER BY ".$orderby." ".$orderto;

        //get total items count
        $result = $inDB->query($sql);
        $itemscount = $inDB->num_rows($result);

        //can user add items here?
        $is_cat_access = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
        $is_can_add = $is_cat_access || $inUser->is_admin;

        $tpl = cmsPage::initTemplate('components', 'com_catalog_view')->
                assign('id', $id)->
                assign('cat', $cat)->
                assign('subcats', $subcats)->
                assign('alphabet', $alphabet)->
                assign('shopcartlink', $shopcartlink)->
                assign('itemscount', $itemscount)->
                assign('is_can_add', $is_can_add)->
                assign('orderform', orderForm($orderby, $orderto, ($cat['view_type']=='shop')));

        //pagination
        if (!@$advsearch) { $perpage = $cat['perpage']; } else { $perpage='100'; }
        $page = $inCore->request('page', 'int', 1);

        //request items using pagination
        $sql .= " LIMIT ".(($page-1)*$perpage).", $perpage";
        $result = $inDB->query($sql) ;

        //search details, if needed
        $search_details = '';
        if (isset($findsql)){
            if ($advsearch){
                $search_details = '<div class="uc_queryform"><strong>'.$_LANG['SEARCH_RESULT'].' - </strong> '.$_LANG['FOUNDED'].': '.$itemscount.' | <a href="/catalog/'.$cat['id'].'">'.$_LANG['CANCEL_SEARCH'].'</a></div>';
            } else {
                $search_details = '<div class="uc_queryform"><strong>'.$_LANG['SEARCH_BY_TAG'].'</strong> "'.htmlspecialchars(icms_ucfirst(stripslashes($query))).'" ('.$_LANG['MATCHES'].': '.$itemscount.') <a href="/catalog/'.$cat['id'].'">'.$_LANG['CANCEL_SEARCH'].'</a></div>';
            }
        }

        $items = array();
        while($item = $inDB->fetch_assoc($result)){
            $item['ratingdata'] = ratingData($item['id']);
            $item['fdata'] = cmsCore::yamlToArray($item['fieldsdata']);
            $item['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 2, '.', ' ');
            $item['rating'] = cms_model_catalog::buildRating($item['ratingdata']['rating']);
            $item['is_new'] = isNew($item['id'], $cat['shownew'], $cat['newint']);
            $item['tagline'] = tagLine($item['tags'], $cat['id']);

            $item['can_edit'] = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;

            $item['fields'] = array();

            if (sizeof($fstruct)>0){
                $fields_show = 0;
                foreach($fstruct as $key=>$value){
                    if ($fields_show < $cat['fields_show']){

                        if ($item['fdata'][$key]){

                            if (mb_strstr($value, '/~h~/')){ $value = str_replace('/~h~/', '', $value); $is_html = true; } else { $is_html = false; }
                            if (mb_strstr($value, '/~m~/')){
                                $value = str_replace('/~m~/', '', $value);
                                $makelink = true;
                            } else {$makelink = false; }
                            if (!$is_html){
                                if (mb_strstr($value, '/~l~/')){
                                    if (@$item['fdata'][$key]!=''){
                                        $field = '<a class="uc_fieldlink" href="/load/url=-'.base64_encode($item['fdata'][$key]).'" target="_blank">'.str_replace('/~l~/', '', $value).'</a> ('.$inCore->fileDownloadCount($item['fdata'][$key]).')';
                                    }
                                } else {
                                    if ($makelink){
                                        $field = $model->getUCSearchLink($cat['id'], $item['fdata'][$key]);
                                    } else {
                                        $field = $item['fdata'][$key];
                                    }
                                }
                            } else {
                                $field = $item['fdata'][$key];
                            }

                            if (isset($query)) { if (mb_stristr($field, $query)) { $field .= '<span class="uc_findsame"> &larr; <i>'.$_LANG['MATCHE'].'</i></span>';} }
                            $fields_show++;

                            $item['fields'][stripslashes($value)] = stripslashes($field);

                        }

                    } else { break; }
                }
            }

            $items[] = $item;
        }

        if (!@$pagemode){
            $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/catalog/'.$id.'-%page%');
        } else {

            if ($pagemode=='findfirst'){
                $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/catalog/'.$id.'-%page%/find-first/'.urlencode(urlencode($query)));
            }

            if ($pagemode=='find'){
                $pagebar = cmsPage::getPagebar($itemscount, $page, $perpage, '/catalog/'.$id.'-%page%/find/'.urlencode(urlencode($query)));
            }

        }

        // SEO
        if($cat['NSLevel'] > 0){

            // meta description
            if($cat['meta_desc']){
                $meta_desc = $cat['meta_desc'];
            } elseif(mb_strlen(strip_tags($cat['description']))>=250){
                $meta_desc = crop($cat['description']);
            } else {
                $meta_desc = $cat['title'];
            }
            $inPage->setDescription($meta_desc);
            // meta keywords
            if($cat['meta_keys']){
                $meta_keys = $cat['meta_keys'];
            } elseif($items){
                foreach($items as $c){
                    $k[] = $c['title'];
                }
                $meta_keys = implode(', ', $k);
            } else {
                $meta_keys = $cat['title'];
            }
            $inPage->setKeywords($meta_keys);

        }

        $tpl->assign('cfg', $cfg)->
              assign('page', $page)->
              assign('search_details', $search_details)->
              assign('fstruct', $fstruct)->
              assign('items', $items)->
              assign('pagebar', $pagebar)->
              display('com_catalog_view.tpl');

        return true;

    }

    //////////////////////////// VIEW ITEM DETAILS ///////////////////////////////////////////////////////////////////////
    if ($do == 'item'){

        $id  = $inCore->request('id', 'int');
        $sql = "SELECT * FROM cms_uc_items WHERE id = '$id'";
        $itemres = $inDB->query($sql) ;

        if (!$inDB->num_rows($itemres)){ cmsCore::error404(); }

        $item = $inDB->fetch_assoc($itemres);

        if ((!$item['published'] || $item['on_moderate']) && !$inUser->is_admin){
            cmsCore::error404();
        }

        $fdata = cmsCore::yamlToArray($item['fieldsdata']);

        if ($item['meta_keys']) { $inPage->setKeywords($item['meta_keys']); }
        if ($item['meta_desc']) { $inPage->setDescription($item['meta_desc']); }

        $ratingdata = ratingData($id);

        $sql = "SELECT * FROM cms_uc_cats WHERE id = '{$item['category_id']}'";
        $catres = $inDB->query($sql) ;
        $cat = $inDB->fetch_assoc($catres);
        $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

        $is_cat_access = $inUser->id ?
                            $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id) : false;
        $item['can_edit'] = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;

        //PATHWAY ENTRY
        $path_list  = $model->getCategoryPath($cat['NSLeft'], $cat['NSRight']);

        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/catalog/'.$pcat['id']);
            }
        }
        $inPage->addPathway($item['title'], '/catalog/item'.$item['id'].'.html');

        $inPage->setTitle($item['title']);


        if ($cat['view_type']=='shop'){

            $shopCartLink=shopCartLink();

        }

        //update hits
        $inDB->query("UPDATE cms_uc_items SET hits = hits + 1 WHERE id = '$id'") ;

        //print item details
        $fields = array();

        if (sizeof($fstruct)>0){
            foreach($fstruct as $key=>$value){
                if (@$fdata[$key]){
                    if (mb_strstr($value, '/~h~/')){
                        $value = str_replace('/~h~/', '', $value);
                        $htmlfield = true;
                    }
                    if (mb_strstr($value, '/~m~/')){
                        $value = str_replace('/~m~/', '', $value);
                        $makelink = true;
                    } else {$makelink = false; }
                    $field = (string)str_replace('<p>', '<p style="margin-top:0px; margin-bottom:5px">', $fdata[$key]);
                    if (mb_strstr($value, '/~l~/')){
                        $field = '<a class="uc_detaillink" href="/load/url=-'.base64_encode($field).'" target="_blank">'.str_replace('/~l~/', '', $value).'</a> ('.$inCore->fileDownloadCount($field).')';

                    } else {

                        if (isset($htmlfield)) {
                            if ($makelink) {
                                 $field = $model->getUCSearchLink($cat['id'], $field);
                            } else {
                                //PROCESS FILTERS, if neccessary
                                if ($cat['filters']){
                                    $filters = $inCore->getFilters();
                                    if ($filters){
                                        foreach($filters as $id=>$_data){
                                            require_once PATH.'/filters/'.$_data['link'].'/filter.php';
                                            $_data['link']($field);
                                        }
                                    }
                                }
                                $field =  stripslashes($field);
                            }
                        } else {
                            if ($makelink) {
                                 $field =  $model->getUCSearchLink($cat['id'], $field);
                            }
                        }

                    }
                    $fields[stripslashes($value)] = stripslashes($field);
                }
            }
        }
        if ($cat['view_type']=='shop'){
            $item['price'] = number_format(shopDiscountPrice($item['id'], $item['category_id'], $item['price']), 2, '.', ' ');
        }

        $user = $inDB->get_fields('cms_users', "id='{$item['user_id']}'", 'login, nickname');
        $getProfileLink = cmsUser::getProfileLink($user['login'], $user['nickname']);

        if ($cat['is_ratings']){
            $ratingForm = ratingForm($ratingdata, $item['id']);
        }

        cmsPage::initTemplate('components', 'com_catalog_item')->
                assign('shopCartLink', (isset($shopCartLink) ? $shopCartLink : ''))->
                assign('getProfileLink', $getProfileLink)->
                assign('tagline', tagLine($item['tags'], $cat['id']))->
                assign('item', $item)->
                assign('cat', $cat)->
                assign('fields', $fields)->
                assign('ratingForm', (isset($ratingForm) ? $ratingForm : ''))->
                display('com_catalog_item.tpl');

        if ($item['is_comments'] && $inCore->isComponentEnable('comments')) {
            cmsCore::includeComments();
            comments('catalog', $item['id'], array(), ($inUser->id == $item['user_id']));
        }

        return true;
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// S H O P /////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////// ADD TO CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'addcart'){
        shopAddToCart($id, 1);
		$inCore->redirect('/catalog/viewcart.html');
    }
    ///////////////////////// VIEW CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'viewcart'){
        shopCart();
    }
    ///////////////////////// DELETE FROM CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'cartremove'){
        shopRemoveFromCart($id);
		$inCore->redirectBack();
    }
    ///////////////////////// CLEAR CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'clearcart'){
        shopClearCart();
        $inCore->redirectBack();
    }
    ///////////////////////// CLEAR CART /////////////////////////////////////////////////////////////////////////////
    if ($do == 'savecart'){
        $itemcounts =  $inCore->request('kolvo', 'array_int');
        if (is_array($itemcounts)){
            shopUpdateCart($itemcounts);
        }
        $inCore->redirectBack();
    }
    ///////////////////////// ORDER //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'order'){
        shopOrder($cfg);
    }
    ///////////////////////// ORDER //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'finish'){
        shopFinishOrder($cfg);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'add_item' || $do == 'edit_item'){

        $cat_id  = cmsCore::request('cat_id', 'int');
        $item_id = cmsCore::request('item_id', 'int', 0);

        if ($do == 'add_item'){

            $cat = $inDB->get_fields('cms_uc_cats', "id='$cat_id'", '*');
            if (!$cat){ cmsCore::error404(); }

            $inPage->setTitle($_LANG['ADD_ITEM']);

            if (!($model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id) || $inUser->is_admin)){
                cmsCore::error404();
            }

            $item  = array();
            $fdata = array();

            if ($cat['cost']=='') { $cat['cost'] = false; }
            if (IS_BILLING){
                cmsBilling::checkBalance('catalog', 'add_catalog_item', false, $cat['cost']);
            }

            $item['is_comments'] = 1;

        }

        if ($do == 'edit_item'){

            $inPage->setTitle($_LANG['EDIT_ITEM']);

            $item = $inDB->get_fields('cms_uc_items', "id='$item_id'", '*');
            if (!$item) { cmsCore::error404(); }

            $cat = $inDB->get_fields('cms_uc_cats', "id='{$item['category_id']}'", '*');
            if (!$cat){ cmsCore::error404(); }

            $is_cat_access  = $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id);
            $is_can_edit    = ($cat['can_edit'] && $is_cat_access && ($inUser->id == $item['user_id'])) || $inUser->is_admin;
            if (!$is_can_edit) { cmsCore::error404(); }

            $fdata = cmsCore::yamlToArray($item['fieldsdata']);

        }

        $path_list  = $model->getCategoryPath($cat['NSLeft'], $cat['NSRight']);
        if ($path_list){
            foreach($path_list as $pcat){
                $inPage->addPathway($pcat['title'], '/catalog/'.$pcat['id']);
            }
        }
        if($do == 'add_item'){
            $inPage->addPathway($_LANG['ADD_ITEM']);
        } else {
            $inPage->addPathway($_LANG['EDIT_ITEM']);
        }

		$cats = $inCore->getListItems('cms_uc_cats', $cat['id'], 'id', 'ASC', 'parent_id > 0 AND published = 1');

        $fields = array();

        $fstruct = cmsCore::yamlToArray($cat['fieldsstruct']);

        foreach($fstruct as $f_id=>$value){

            if (mb_strstr($value, '/~h~/')) { $ftype = 'html'; $value=str_replace('/~h~/', '', $value); }
            elseif (mb_strstr($value, '/~l~/')) { $ftype = 'link'; $value=str_replace('/~l~/', '', $value); } else { $ftype='text'; }

            if (mb_strstr($value, '/~m~/')) { $makelink = true; $value=str_replace('/~m~/', '', $value); }
            else { $makelink = false; }

            $next['ftype']    = stripslashes($ftype);
            $next['title']    = stripslashes($value);
            $next['makelink'] = stripslashes($makelink);

            if (!empty($fdata[$f_id])){
                $next['value']  = stripslashes($fdata[$f_id]);
            } else {
                $next['value']  = '';
            }

            $fields[$f_id] = $next;

        }

        cmsPage::initTemplate('components', 'com_catalog_add')->
                assign('do', $do)->
                assign('item', $item)->
                assign('fields', $fields)->
                assign('cat', $cat)->
                assign('cats', $cats)->
                assign('cfg', $cfg)->
                assign('is_admin', $inUser->is_admin)->
                assign('cat_id', $cat['id'])->
                display('com_catalog_add.tpl');

        return;

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'submit_item'){

        $opt     = cmsCore::request('opt', 'str', 'add');
        $new_cat_id = cmsCore::request('new_cat_id', 'int', 0);
        $cat_id = $new_cat_id ? $new_cat_id : cmsCore::request('cat_id', 'int', 0);

        $item_id = cmsCore::request('item_id', 'int', 0);

        $cat = $inDB->get_fields('cms_uc_cats', "id='$cat_id'", '*');
        if(!$cat){ cmsCore::error404(); }

        if ($opt == 'add'){

            if(!$inUser->is_admin &&
                    !$model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id)){
                cmsCore::error404();
            }

        } else {

            $item = $inDB->get_fields('cms_uc_items', "id='{$item_id}'", '*');
            if(!$item){ cmsCore::error404(); }

            if(!$inUser->is_admin &&
                    !($cat['can_edit'] && ($inUser->id == $item['user_id']) &&
                        $model->checkCategoryAccess($cat['id'], $cat['is_public'], $inUser->group_id))){
                cmsCore::error404();
            }

        }

        $item['title'] = cmsCore::request('title', 'str');
        if (!$item['title']) { cmsCore::addSessionMessage($_LANG['NEED_TITLE'], 'error'); cmsCore::redirectBack(); }

        $item['category_id']    = $cat_id;
        $item['published']      = ($cfg['premod'] && !$inUser->is_admin ? 0 : 1);
        $item['on_moderate']    = ($cfg['premod'] && !$inUser->is_admin ? 1 : 0);

        $item['fdata']          = cmsCore::request('fdata', 'array', array());;
        foreach($item['fdata'] as $key=>$value) {
			$item['fdata'][$key] = cmsCore::badTagClear($value);
		}
        $item['fieldsdata']     = $inDB->escape_string(cmsCore::arrayToYaml($item['fdata']));

        $item['is_comments']    = $inUser->is_admin ? cmsCore::request('is_comments', 'int', 0) : $cfg['is_comments'];
        $item['tags']           = cmsCore::request('tags', 'str', '');
        $item['canmany']        = 1;
        $item['imageurl']       = ($opt == 'add' ? '' : $item['imageurl']);
        $item['price']          = 0;
        $item['canmany']        = 1;

        if($inUser->is_admin){
            $meta_desc = cmsCore::request('meta_desc', 'str', '');
            $meta_keys = cmsCore::request('meta_keys', 'str', '');
            $item['meta_desc']  = $meta_desc ? $meta_desc : $item['title'];
            $item['meta_keys']  = $meta_keys ? $meta_keys : $item['tags'];
        } else {
            $item['meta_desc']  = @$item['meta_desc'] ? $item['meta_desc'] : $item['title'];
            $item['meta_keys']  = @$item['meta_keys'] ? $item['meta_keys'] : $item['tags'];
        }

		if (cmsCore::inRequest('price')) {
			$price          = cmsCore::request('price', 'str', '');
			$price          = str_replace(',', '.', $price);
            $item['price']  = round($price, 2);
            $item['canmany']= cmsCore::request('canmany', 'int', 0);
		}

        if (cmsCore::request('delete_img', 'int', 0)){

            @unlink(PATH."/images/catalog/".$item['imageurl']);
            @unlink(PATH."/images/catalog/small/".$item['imageurl']);
            @unlink(PATH."/images/catalog/medium/".$item['imageurl']);

            $item['imageurl'] = '';

        }
        $file = $model->uploadPhoto($item['imageurl']);
        if($file){
            $item['imageurl'] = $file['filename'];
        }

        if ($opt=='add'){

            $item['pubdate'] = date('Y-m-d H:i');
            $item['user_id'] = $inUser->id;

            $item['id'] = $model->addItem($item);

            if (IS_BILLING){
                if ($cat['cost']=='') { $cat['cost'] = false; }
                cmsBilling::process('catalog', 'add_catalog_item', $cat['cost']);
            }

            if (!$cfg['premod'] || $inUser->is_admin) {

                cmsCore::callEvent('ADD_CATALOG_DONE', $item);

                //регистрируем событие
                cmsActions::log('add_catalog', array(
                    'object' => $item['title'],
                    'object_url' => '/catalog/item'.$item['id'].'.html',
                    'object_id' => $item['id'],
                    'target' => $cat['title'],
                    'target_url' => '/catalog/'.$cat['id'],
                    'target_id' => $cat['id'],
                    'description' => ''
                ));
            }
		}
        if ($opt=='edit'){
			$model->updateItem($item['id'], $item);
			cmsActions::updateLog('add_catalog', array('object' => $item['title']), $item['id']);
		}

        if ($inUser->id != 1 && $cfg['premod'] && $cfg['premod_msg']){

            $link = '<a href="/catalog/item'.$item['id'].'.html">'.$item['title'].'</a>';
            $user = '******'.cmsUser::getProfileURL($inUser->login).'">'.$inUser->nickname.'</a>';

            if ($opt=='add')  { $message = $_LANG['MSG_ITEM_SUBMIT']; }
            if ($opt=='edit') { $message = $_LANG['MSG_ITEM_EDITED']; }
            $message = str_replace('%user%', $user, $message);
            $message = str_replace('%link%', $link, $message);

            cmsUser::sendMessage(USER_UPDATER, 1, $message);

            cmsCore::addSessionMessage($_LANG['ITEM_PREMOD_NOTICE'], 'info');

            cmsCore::redirect('/catalog/'.$item['category_id']);

        }

        cmsCore::redirect('/catalog/item'.$item['id'].'.html');

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'accept_item'){

        $item_id = cmsCore::request('item_id', 'int');

        $item = $inDB->get_fields('cms_uc_items', "id='{$item_id}'", 'title, user_id, category_id');
        if (!$item || !$inUser->is_admin){ cmsCore::error404(); }

        $inDB->query("UPDATE cms_uc_items SET published=1, on_moderate=0 WHERE id='{$item_id}'");

		$cat = $inDB->get_fields('cms_uc_cats', 'id='.$item['category_id'], 'id, title');

        cmsCore::callEvent('ADD_CATALOG_DONE', $item);

		//регистрируем событие
		cmsActions::log('add_catalog', array(
				'object' => $item['title'],
				'user_id' => $item['user_id'],
				'object_url' => '/catalog/item'.$item_id.'.html',
				'object_id' => $item_id,
				'target' => $cat['title'],
				'target_url' => '/catalog/'.$cat['id'],
				'target_id' => $cat['id'],
				'description' => ''
		));

        $item_link  = '<a href="/catalog/item'.$item_id.'.html">'.$item['title'].'</a>';

        $message = str_replace('%link%', $item_link, $_LANG['MSG_ITEM_ACCEPTED']);

        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);

        cmsCore::redirectBack();

    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if ($do == 'delete_item'){

        $item_id = cmsCore::request('item_id', 'int');

        $item = $inDB->get_fields('cms_uc_items', "id='{$item_id}'", '*');
        if(!$item){ cmsCore::error404(); }

        if (!($item['user_id']==$inUser->id || $inUser->is_admin)){ cmsCore::error404(); }

        $model->deleteItem($item_id);

        $message = str_replace('%item%', $item['title'], $_LANG['MSG_ITEM_REJECTED']);
        cmsUser::sendMessage(USER_UPDATER, $item['user_id'], $message);

        cmsCore::redirect('/catalog/'.$item['category_id']);

    }

}
Example #12
0
     $plg_nconfig = cmsCore::arrayToYaml($plg_nconfig);
     cmsCore::c('db')->query("UPDATE cms_plugins SET config='". cmsCore::c('db')->escape_string($plg_nconfig) ."' WHERE plugin='p_content_imgs' LIMIT 1");
 }
 // ========== /p_content_imgs =========
 //======================================================================
 
 // --------------- Добавляем всем модулям настройку tpl ----------------
 $results = cmsCore::c('db')->query('SELECT id, content, config FROM cms_modules WHERE is_external = 1');
 while ($mod = cmsCore::c('db')->fetch_assoc($results)) {
     $mod['config'] = cmsCore::yamlToArray($mod['config']);
     
     if (empty($mod['config']['tpl'])) {
         $mod['config']['tpl'] = $mod['content'];
     }
     
     $mod['config'] = cmsCore::arrayToYaml($mod['config']);
     
     cmsCore::c('db')->update(
         'cms_modules',
         array(
             'config' => cmsCore::c('db')->escape_string($mod['config'])
         ),
         $mod['id']
     );
 }
 //======================================================================
 
 $last_user_menu = cmsCore::c('db')->get_fields('cms_modules', "title = 'Меню пользователя' AND content = 'mod_usermenu'", '*');
 if (!empty($last_user_menu)) {
     cmsCore::c('db')->query("UPDATE `cms_modules` SET 
             `position` = '". $last_user_menu['position'] ."',
Example #13
0
}
$type = $fields[$field];
// получаем все данные по $target_id и $target
$translation = translations::getTranslation($lang, $target, $target_id);
// получаем текущее значение поля
if ($translation && isset($translation['data'][$field])) {
    $value = $translation['data'][$field];
} else {
    $value = '';
}
if (cmsCore::inRequest('save')) {
    if (!cmsUser::checkCsrfToken()) {
        cmsCore::halt();
    }
    $field_data = cmsCore::request('field_data', $type, '');
    // если есть запись, обновляем
    if ($translation) {
        if ($field_data) {
            $translation['data'][$field] = $field_data;
        }
        if (!$field_data && isset($translation['data'][$field])) {
            unset($translation['data'][$field]);
        }
        $inDB->update('cms_translations', array('data' => $inDB->escape_string(cmsCore::arrayToYaml($translation['data']))), $translation['id']);
    } else {
        $inDB->insert('cms_translations', array('data' => $inDB->escape_string(cmsCore::arrayToYaml(array($field => $field_data))), 'lang' => $lang, 'fieldsset_id' => translations::getFieldsetId($target), 'target_id' => $target_id));
    }
    cmsCore::halt();
} else {
    cmsPage::includeTemplateFile('admin/translations.php', array('type' => $type, 'value' => $value, 'action' => $_SERVER['REQUEST_URI']));
}
Example #14
0
        case 'menu':
            $item['config']['items'] = cmsCore::request('f_menu_list', 'str', '');
            $item['config']['size'] = cmsCore::request('f_menu_size', 'int');
            break;
        case 'file':
            $exts = cmsCore::request('f_file_ext', 'str', '');
            while (mb_strpos($exts, 'htm') || mb_strpos($exts, 'php') || mb_strpos($exts, 'ht')) {
                $exts = str_replace(array('htm', 'php', 'ht'), '', mb_strtolower($exts));
            }
            $item['config']['ext'] = str_replace(' ', '', $exts);
            $item['config']['size'] = cmsCore::request('f_file_size', 'int');
            break;
    }
    $item['config'] = $inDB->escape_string(cmsCore::arrayToYaml($item['config']));
    if (!cmsCore::request('is_public', 'int', 0)) {
        $item['show_for_group'] = cmsCore::arrayToYaml(cmsCore::request('show_for_group', 'array_int'));
    } else {
        $item['show_for_group'] = '';
    }
    if ($opt == 'add_field') {
        $inDB->insert('cms_form_fields', cmsCore::callEvent('ADD_FORM_FIELD', $item));
    } else {
        $inDB->update('cms_form_fields', cmsCore::callEvent('UPDATE_FORM_FIELD', $item), cmsCore::request('field_id', 'int'));
    }
    cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS']);
    cmsCore::redirect('?view=components&do=config&id=' . $id . '&opt=edit&item_id=' . $item['form_id']);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (in_array($opt, array('submit', 'update'))) {
    if (!cmsUser::checkCsrfToken()) {
        cmsCore::error404();
Example #15
0
 /**
  * Обновляет конфигурацию модулей
  */
 public function setModCfgs() {
     if (!empty($this->cfg['mod_cfgs'])) {
         foreach ($this->cfg['mod_cfgs'] as $mod) {
             $results = cmsCore::c('db')->query("SELECT id,config FROM cms_modules WHERE content='". $mod['name'] ."'");
             
             if (!cmsCore::c('db')->num_rows($results)) { continue; }
             
             while ($module = cmsCore::c('db')->fetch_assoc($results)) {
                 if (!empty($module['config'])) {
                     $module['config'] = cmsCore::yamlToArray($module['config']);
                     
                     if (!empty($mod['unset_keys'])) {
                         foreach ($mod['unset_keys'] as $key) {
                             unset($module['config'][$key]);
                         }
                     }
                 } else {
                     $module['config'] = array();
                 }
                 
                 if (!empty($mod['merge_cfgs'])) {
                     $module['config'] = array_merge($mod['merge_cfgs'], $module['config']);
                 }
                 
                 $module['config'] = cmsCore::arrayToYaml($module['config']);
                 cmsCore::c('db')->update(
                     'cms_modules',
                     array(
                         'config' => cmsCore::c('db')->escape_string($module['config'])
                     ),
                     $module['id']
                 );
             }
         }
     }
 }
Example #16
0
            $item['config']['size'] = cmsCore::request('f_list_size', 'int');
            break;
        case 'menu':
            $item['config']['items'] = cmsCore::request('f_menu_list', 'str', '');
            $item['config']['size'] = cmsCore::request('f_menu_size', 'int');
            break;
        case 'file':
            $exts = cmsCore::request('f_file_ext', 'str', '');
            while (mb_strpos($exts, 'htm') || mb_strpos($exts, 'php') || mb_strpos($exts, 'ht')) {
                $exts = str_replace(array('htm', 'php', 'ht'), '', mb_strtolower($exts));
            }
            $item['config']['ext'] = str_replace(' ', '', $exts);
            $item['config']['size'] = cmsCore::request('f_file_size', 'int');
            break;
    }
    $item['config'] = $inDB->escape_string(cmsCore::arrayToYaml($item['config']));
    if ($opt == 'add_field') {
        $inDB->insert('cms_form_fields', cmsCore::callEvent('ADD_FORM_FIELD', $item));
    } else {
        $inDB->update('cms_form_fields', cmsCore::callEvent('UPDATE_FORM_FIELD', $item), cmsCore::request('field_id', 'int'));
    }
    cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS']);
    cmsCore::redirect('?view=components&do=config&id=' . $id . '&opt=edit&item_id=' . $item['form_id']);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (in_array($opt, array('submit', 'update'))) {
    if (!cmsUser::checkCsrfToken()) {
        cmsCore::error404();
    }
    $item['title'] = cmsCore::request('title', 'str', $_LANG['AD_FORM_UNTITLED']);
    $item['description'] = $inDB->escape_string(cmsCore::request('description', 'html', ''));
Example #17
0
function applet_menu() {
    $inCore = cmsCore::getInstance();

    global $_LANG;
    global $adminAccess;

    if (!cmsUser::isAdminCan('admin/menu', $adminAccess)) { cpAccessDenied(); }

    cmsCore::c('page')->setTitle($_LANG['AD_MENU']);
    cpAddPathway($_LANG['AD_MENU'], 'index.php?view=menu');

    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);

    if ($do == 'list') {
        $toolmenu = array(
            array( 'icon' => 'new.gif', 'title' => $_LANG['AD_MENU_POINT_ADD'], 'link' => '?view=menu&do=add' ),
            array( 'icon' => 'newmenu.gif', 'title' => $_LANG['AD_MENU_ADD'], 'link' => '?view=menu&do=addmenu' ),
            array( 'icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link'=> "javascript:checkSel('?view=menu&do=edit&multiple=1');" ),
            array( 'icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=delete&multiple=1');" ),
            array( 'icon' => 'show.gif', 'title' => $_LANG['AD_ALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=show&multiple=1');" ),
            array( 'icon' => 'hide.gif', 'title' => $_LANG['AD_DISALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=hide&multiple=1');" ),
            array( 'icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=menu' )
        );

        cpToolMenu($toolmenu);

        $fields = array(
            array( 'title' => 'Lt', 'field' => 'NSLeft', 'width' => '40' ),
            array(
                'title' => $_LANG['TITLE'],
                'field' => array('title', 'titles'), 'width'=>'',
                'link'  => '?view=menu&do=edit&id=%id%',
                'prc'   => function ($i) {
                    $i['titles'] = cmsCore::yamlToArray($i['titles']);
                    
                    // переопределяем название пункта меню в зависимости от языка
                    if (!empty($i['titles'][cmsConfig::getConfig('lang')])) {
                        $i['title'] = $i['titles'][cmsConfig::getConfig('lang')];
                    }
                    
                    return $i['title'];
                }
            ),
            array( 'title' => $_LANG['SHOW'], 'field' => 'published', 'width' => '80' ),
            array( 'title' => $_LANG['AD_ORDER'], 'field' => 'ordering', 'width' => '100' ),
            array( 'title' => $_LANG['AD_LINK'], 'field' => array('linktype', 'linkid', 'link'), 'width' => '240', 'prc' => 'cpMenutypeById' ),
            array( 'title' => $_LANG['AD_MENU'], 'field' => 'menu', 'width' => '80', 'filter' => '10', 'filterlist' => cpGetList('menu'), 'prc' => 'list_menu' ),
            array( 'title' => $_LANG['TEMPLATE'], 'field' => 'template', 'width' => '90', 'prc' => 'cpTemplateById' )
        );
        
        $actions = array(
            array( 'title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=menu&do=edit&id=%id%' ),
            array( 'title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_MENU_POINT_CONFIRM'], 'link' => '?view=menu&do=delete&id=%id%' )
        );

        cpListTable('cms_menu', $fields, $actions, 'parent_id>0', 'NSLeft, ordering');

    } else {
        $toolmenu = array(
            array( 'icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:document.addform.submit();' ),
            array( 'icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'index.php?view=menu' )
        );

        cpToolMenu($toolmenu);
    }

    if ($do == 'move_up') {
        cmsCore::c('db')->moveNsCategory('cms_menu', $id, 'up');
        cmsCore::redirectBack();
    }

    if ($do == 'move_down') {
        cmsCore::c('db')->moveNsCategory('cms_menu', $id, 'down');
        cmsCore::redirectBack();
    }

    if ($do == 'show') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) { cmsCore::c('db')->setFlag('cms_menu', $id, 'published', '1'); }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_menu', $_REQUEST['item'], 'published', '1');
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');
            cmsCore::redirectBack();
        }
    }

    if ($do == 'hide') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) { cmsCore::c('db')->setFlag('cms_menu', $id, 'published', '0'); }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_menu', cmsCore::request('item', 'array_int', array()), 'published', '0');
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');
            cmsCore::redirectBack();
        }
    }

    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) { cmsCore::c('db')->deleteNS('cms_menu', (int)$id); }
        } else {
            cmsCore::c('db')->deleteListNS('cms_menu', cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');
        cmsCore::redirectBack();
    }

    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }

        $id = cmsCore::request('id', 'int', 0);
        if(!$id){ cmsCore::redirectBack(); }

        $title     = cmsCore::request('title', 'str', '');
        $titles    = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $menu      = cmsCore::arrayToYaml(cmsCore::request('menu', 'array_str', ''));
        $linktype  = cmsCore::request('mode', 'str', '');
        $linkid    = cmsCore::request($linktype, 'str', '');
        $link      = $inCore->getMenuLink($linktype, $linkid);
        $target    = cmsCore::request('target', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $template  = cmsCore::request('template', 'str', '');
        $iconurl   = cmsCore::request('iconurl', 'str', '');
        $parent_id = cmsCore::request('parent_id', 'int', 0);
        $oldparent = cmsCore::request('oldparent', 'int', 0);
        $is_lax    = cmsCore::request('is_lax', 'int', 0);
        $css_class = cmsCore::request('css_class', 'str', '');

        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }

        $ns = $inCore->nestedSetsInit('cms_menu');

        if ($oldparent != $parent_id) {
            $ns->MoveNode($id, $parent_id);
        }

        $sql = "UPDATE cms_menu
                SET title='". $title ."',
                    titles='". $titles ."',
                    css_class='". $css_class ."',
                    menu='". $menu ."',
                    link='". $link ."',
                    linktype='". $linktype ."',
                    linkid='". $linkid ."',
                    target='". $target ."',
                    published='". $published ."',
                    template='". $template ."',
                    access_list='". $access_list ."',
                    is_lax='". $is_lax ."',
                    iconurl='". $iconurl ."'
                WHERE id = '". $id ."'
                LIMIT 1";
        cmsCore::c('db')->query($sql) ;

        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');

        if (!isset($_SESSION['editlist']) || count($_SESSION['editlist']) == 0) {
            cmsCore::redirect('?view=menu');
        } else {
            cmsCore::redirect('?view=menu&do=edit');
        }

    }

    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }

        $title     = cmsCore::request('title', 'str', '');
        $titles    = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $menu      = cmsCore::arrayToYaml(cmsCore::request('menu', 'array_str', ''));
        $linktype  = cmsCore::request('mode', 'str', '');
        $linkid    = cmsCore::request($linktype, 'str', '');
        $link      = $inCore->getMenuLink($linktype, $linkid);
        $target    = cmsCore::request('target', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $template  = cmsCore::request('template', 'str', '');
        $iconurl   = cmsCore::request('iconurl', 'str', '');
        $parent_id = cmsCore::request('parent_id', 'int', 0);
        $css_class = cmsCore::request('css_class', 'str', '');

        $is_public = cmsCore::request('is_public', 'int', '');
        $is_lax    = cmsCore::request('is_lax', 'int', 0);
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }

        $ns = $inCore->nestedSetsInit('cms_menu');
        $myid = $ns->AddNode($parent_id);

        $sql = "UPDATE cms_menu
                        SET menu='". $menu ."',
                                title='". $title ."',
                                titles='". $titles ."',
                                css_class='". $css_class ."',
                                link='". $link ."',
                                linktype='". $linktype ."',
                                linkid='". $linkid ."',
                                target='". $target ."',
                                published='". $published ."',
                                template='". $template ."',
                                access_list='". $access_list ."',
                                is_lax='". $is_lax ."',
                                iconurl='". $iconurl ."'
                        WHERE id = '". $myid ."'";

        cmsCore::c('db')->query($sql);

        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');
        cmsCore::redirect('?view=menu');
    }

    if ($do == 'submitmenu') {
        if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }

        $sql = "SELECT ordering as max_o FROM cms_modules ORDER BY ordering DESC LIMIT 1";
        $result = cmsCore::c('db')->query($sql) ;
        $row = cmsCore::c('db')->fetch_assoc($result);
        $maxorder = $row['max_o'] + 1;

        $menu       = cmsCore::request('menu', 'str', '');
        $title      = cmsCore::request('title', 'str', '');
        $position   = cmsCore::request('position', 'str', '');
        $published  = cmsCore::request('published', 'int', 0);
        $css_prefix = cmsCore::request('css_prefix', 'str', '');
        $is_public  = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = $inCore->arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }

        $cfg['menu'] = $menu;
        $cfg_str = cmsCore::arrayToYaml($cfg);

        $sql = "INSERT INTO cms_modules (position, name, title, is_external, content, ordering, showtitle, published, user, config, css_prefix, access_list)
                VALUES ('". $position ."', '". $_LANG['AD_MENU'] ."', '". $title ."', 1, 'mod_menu', ". $maxorder .", 1, ". $published .", 0, '". $cfg_str ."', '". $css_prefix ."', '". $access_list ."')";

        cmsCore::c('db')->query($sql) ;

        $newid = cmsCore::c('db')->get_last_id('cms_modules');

        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'] , 'success');

        cmsCore::redirect('?view=modules&do=edit&id='.$newid);

    }

    if ($do == 'addmenu' || $do == 'add' || $do == 'edit') {
        cmsCore::c('page')->addHeadJS('admin/js/menu.js');
        echo '<script>';
        echo cmsPage::getLangJS('AD_SPECIFY_LINK_MENU');
        echo '</script>';
    }

    if ($do == 'addmenu') {
        cmsCore::c('page')->setTitle($_LANG['AD_MENU_ADD']);
        cpAddPathway($_LANG['AD_MENU_ADD']);

        $menu_list = cpGetList('menu');

?>
<form id="addform" name="addform" action="index.php?view=menu&do=submitmenu" method="post">
    <input type="hidden" name="csrf_token" value="<?php echo cmsUser::getCsrfToken(); ?>" />
            
    <div class="panel panel-default" style="width:650px;">
        <div class="panel-body">
            <div class="form-group">
                <label><?php echo $_LANG['AD_MODULE_MENU_TITLE']; ?></label>
                <input type="text" id="title2" class="form-control" name="title" style="width:99%" value="" />
            </div>

            <div class="form-group">
                <label><?php echo $_LANG['AD_MENU_TO_VIEW']; ?></label>
                <select id="menu" class="form-control" name="menu" style="width:99%">
                    <?php foreach ($menu_list as $menu) { ?>
                        <option value="<?php echo $menu['id']; ?>">
                            <?php echo $menu['title']; ?>
                        </option>
                    <?php } ?>
                </select>
                <div class="help-block"><?php echo $_LANG['AD_TO_CREATE_NEW_POINT']; ?></div>
            </div>
                    
            <div class="form-group">
                <label><?php echo $_LANG['AD_POSITION_TO_VIEW']; ?></label>
                <?php
                    $pos = cpModulePositions(cmsConfig::getConfig('template'));
                ?>
                <select id="position" class="form-control" name="position" style="width:99%">
                    <?php
                        if ($pos){
                            foreach($pos as $key=>$position) {
                                if (cmsCore::getArrVal($mod, 'position') == $position){
                                    echo '<option value="'. $position .'" selected>'. $position .'</option>';
                                } else {
                                    echo '<option value="'. $position .'">'. $position .'</option>';
                                }
                            }
                        }
                    ?>
                </select>
                <input name="is_external" type="hidden" id="is_external" value="0" />
                <div class="help-block"><?php echo $_LANG['AD_POSITION_MUST_BE']; ?></div>
            </div>
                    
            <div class="form-group">
                <label><?php echo $_LANG['AD_MENU_PUBLIC']; ?></label>
                <label>
                    <input name="published" type="radio" value="1" checked="checked" <?php if (cmsCore::getArrVal($mod, 'published')) { echo 'checked="checked"'; } ?> /> <?php echo $_LANG['YES']; ?>
                </label>
                <label>
                    <input name="published" type="radio" value="0"  <?php if (!cmsCore::getArrVal($mod, 'published')) { echo 'checked="checked"'; } ?> /> <?php echo $_LANG['NO']; ?>
                </label>
            </div>
                    
            <div class="form-group">
                <label><?php echo $_LANG['AD_PREFIX_CSS']; ?></label>
                <input type="text" id="css_prefix" class="form-control" name="css_prefix" value="<?php echo cmsCore::getArrVal($mod, 'css_prefix'); ?>" style="width:99%" />
            </div>
                    
            <div class="form-group">
                <label><?php echo $_LANG['AD_TAB_ACCESS']; ?>:</label>
                <div class="help-block"><?php echo $_LANG['AD_GROUP_ACCESS'] ; ?></div>
                <?php
                    $groups = cmsUser::getGroups();
                    $style  = 'disabled="disabled"';
                    $public = 'checked="checked"';

                    if ($do == 'edit') {
                        if ($mod['access_list']) {
                            $public = '';
                            $style  = '';
                            $access_list = $inCore->yamlToArray($mod['access_list']);
                        }
                    }
                ?>
                <label><input name="is_public" type="checkbox" id="is_public" onclick="checkAccesList()" value="1" <?php echo $public?> /> <?php echo $_LANG['AD_SHARE']; ?></label>
                <div class="help-block"><?php echo $_LANG['AD_VIEW_IF_CHECK']; ?></div>
            </div>
                    
            <div class="form-group">
                <label><?php echo $_LANG['AD_GROUPS_VIEW']; ?></label>
                <?php
                    echo '<select class="form-control" style="width: 99%" name="allow_group[]" id="allow_group" size="6" multiple="multiple" '. $style .'>';
                    if ($groups) {
                        foreach ($groups as $group) {
                            echo '<option value="'. $group['id'] .'"';
                            if ($do == 'edit') {
                                if (in_array($group['id'], $access_list)) {
                                    echo 'selected="selected"';
                                }
                            }
                            echo '>';
                            echo $group['title'].'</option>';
                        }
                    }
                            
                    echo '</select>';
                ?>
                <div class="help-block"><?php echo $_LANG['AD_SELECT_MULTIPLE_CTRL']; ?></div>
            </div>
                    
            <div class="alert alert-info" role="alert"><?php echo $_LANG['AD_NEW_MENU_NEW_MODULE']; ?></div>
        </div>
    </div>

    <div style="margin-top:5px">
        <input class="btn btn-primary" name="save" type="submit" id="save" value="<?php echo $_LANG['AD_MENU_ADD']; ?>" />
        <input class="btn btn-default" name="back" type="button" id="back" value="<?php echo $_LANG['CANCEL']; ?>" onclick="window.location.href='index.php?view=menu';" />
    </div>
</form>
<?php
    }

    if ($do == 'add' || $do == 'edit') {
        $menu_list = cpGetList('menu');
        
        $langs = cmsCore::getDirsList('/languages');
        
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_MENU_POINT_ADD']);
            $mod['menu'] = array('mainmenu');
        } else {
            if (isset($_REQUEST['multiple'])) {
                if (isset($_REQUEST['item'])) {
                    $_SESSION['editlist'] = cmsCore::request('item', 'array_int', array());
                } else {
                    cmsCore::addSessionMessage($_LANG['AD_NO_SELECT_OBJECTS'], 'error');
                    cmsCore::redirectBack();
                }
            }

            $ostatok = '';

            if (isset($_SESSION['editlist'])) {
                $item_id = array_shift($_SESSION['editlist']);
                if (sizeof($_SESSION['editlist']) == 0) {
                   unset($_SESSION['editlist']);
                } else {
                    $ostatok = '('.$_LANG['AD_NEXT_IN'].sizeof($_SESSION['editlist']).')';
                }
            } else {
                $item_id = cmsCore::request('id', 'int', 0);
            }

            $mod = cmsCore::c('db')->get_fields('cms_menu', "id = '$item_id'", '*');
            if (!$mod) { cmsCore::error404(); }

            $mod['menu']   = cmsCore::yamlToArray($mod['menu']);
            $mod['titles'] = cmsCore::yamlToArray($mod['titles']);

            cpAddPathway($_LANG['AD_MENU_POINT_EDIT'].$ostatok.' "'.$mod['title'].'"');

        }
?>
<form id="addform" name="addform" method="post" action="index.php">
    <input type="hidden" name="csrf_token" value="<?php echo cmsUser::getCsrfToken(); ?>" />
    <input type="hidden" name="view" value="menu" />

    <table class="table">
        <tr>
            <td valign="top">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MENU_POINT_TITLE']; ?></label>
                            <input type="text" id="title" class="form-control" style="width:100%" name="title" value="<?php echo htmlspecialchars(cmsCore::getArrVal($mod, 'title', ''));?>" />
                            <div class="help-block"><?php echo $_LANG['AD_VIEW_IN_SITE']; ?></div>
                        </div>
                        
                        <?php if (count($langs) > 1) { ?>
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_LANG_TITLES']; ?></label>
                            <?php foreach ($langs as $lang) { ?>
                                <div>
                                    <strong><?php echo $lang; ?>:</strong>
                                    <input name="titles[<?php echo $lang; ?>]" type="text" style="width:97%" value="<?php echo htmlspecialchars(cmsCore::getArrVal($mod['titles'], $lang, '')); ?>" placeholder="<?php echo $_LANG['AD_HINT_DEFAULT']; ?>" />
                                </div>
                            <?php } ?>
                            <div class="help-block"><?php echo $_LANG['AD_LANG_TITLES_HINT']; ?></div>
                        </div>
                        <?php } ?>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_PARENT_POINT']; ?></label>
                            <?php
                                $rootid = cmsCore::c('db')->get_field('cms_menu', 'parent_id=0', 'id');
                            ?>
                            <select id="parent_id" class="form-control" style="width:100%" name="parent_id" size="10">
                                <option value="<?php echo $rootid; ?>" <?php if (cmsCore::getArrVal($mod, 'parent_id', $rootid) == $rootid) { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_MENU_ROOT']; ?></option>
                                <?php
                                    echo $inCore->getListItemsNS('cms_menu', cmsCore::getArrVal($mod, 'parent_id', 0));
                                ?>
                            </select>
                            <input type="hidden" name="oldparent" value="<?php echo cmsCore::getArrVal($mod, 'parent_id', '');?>" />
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MENU_POINT_ACTION']; ?></label>
                            <select id="linktype" class="form-control" style="width:100%" name="mode" onchange="showMenuTarget()">
                                <?php $link_type = cmsCore::getArrVal($mod, 'linktype', 'link') ?>
                                <option value="link" <?php if ($link_type == 'link') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_LINK']; ?></option>
                                <option value="content" <?php if ($link_type == 'content') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_ARTICLE']; ?></option>
                                <?php if($inCore->isComponentInstalled('video')){ ?> 
                                    <option value="video_cat" <?php if ($link_type == 'video_cat') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_VIDEO_PARTITION']; ?></option> 
                                <?php } ?>
                                <option value="category" <?php if ($link_type == 'category') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_PARTITION']; ?></option>
                                <option value="component" <?php if ($link_type == 'component') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_COMPONENT']; ?></option>
                                <option value="blog" <?php if ($link_type == 'blog') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_BLOG']; ?></option>
                                <option value="uccat" <?php if ($link_type == 'uccat') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_CATEGORY']; ?></option>
                                <option value="photoalbum" <?php if ($link_type == 'photoalbum') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_OPEN_ALBUM']; ?></option>
                            </select>
                        </div>
                            
                        <div id="t_link" class="form-group menu_target" style="display:<?php if ($link_type == 'link' || $link_type == 'ext') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_LINK']; ?></label>
                            <input type="text" id="link" class="form-control" style="width:100%" name="link" size="50" value="<?php if ($link_type == 'link' || $link_type == 'ext') { echo cmsCore::getArrVal($mod, 'link', ''); } ?>" />
                            <div class="help-block"><?php echo $_LANG['AD_LINK_HINT']; ?> <b>http://</b></div>
                        </div>
                            
                        <div id="t_content" class="form-group menu_target" style="display:<?php if ($link_type == 'content') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_ARTICLE'] ; ?></label>
                            <select id="content" class="form-control" style="width:100%" name="content">
                                <?php
                                    echo $inCore->getListItems('cms_content', (($link_type == 'content') ? $mod['linkid'] : 0));
                                ?>
                            </select>
                        </div>
                            
                        <?php if($inCore->isComponentInstalled('video')){ ?> 
                        <div id="t_video_cat" class="form-group menu_target" style="display:<?php if ($link_type == 'video_cat') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_PARTITION']; ?></label>
                            <select id="video_cat" class="form-control" style="width:100%" name="video_cat"> 
                                <?php
                                    echo $inCore->getListItemsNS('cms_video_category', (($link_type == 'video_cat') ? $mod['linkid'] : 0));
                                ?> 
                            </select>
                        </div>
                        <?php } ?>
                            
                        <div id="t_category" class="form-group menu_target" style="display:<?php if ($link_type == 'category') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_PARTITION']; ?></label>
                            <select id="category" class="form-control" style="width:100%" name="category"> 
                                <?php
                                    echo $inCore->getListItemsNS('cms_category', (($link_type == 'category') ? $mod['linkid'] : 0));
                                ?> 
                            </select>
                        </div>
                            
                        <div id="t_component" class="form-group menu_target" style="display:<?php if ($link_type == 'component') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_COMPONENT']; ?></label>
                            <select id="component" class="form-control" style="width:100%" name="component"> 
                                <?php
                                    echo $inCore->getListItems('cms_components', (($link_type == 'component') ? $mod['linkid'] : 0), 'title', 'asc', 'internal=0', 'link');
                                ?> 
                            </select>
                        </div>
                            
                        <div id="t_blog" class="form-group menu_target" style="display:<?php if ($link_type == 'blog') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_BLOG']; ?></label>
                            <select id="blog" class="form-control" style="width:100%" name="blog"> 
                                <?php
                                    echo $inCore->getListItems('cms_blogs', (($link_type == 'blog') ? $mod['linkid'] : 0), 'title', 'asc', "owner='user'");
                                ?> 
                            </select>
                        </div>
                            
                        <div id="t_uccat" class="form-group menu_target" style="display:<?php if ($link_type == 'uccat') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_CATEGORY']; ?></label>
                            <select id="blog" class="form-control" style="width:100%" name="blog"> 
                                <?php
                                    echo $inCore->getListItems('cms_uc_cats', (($link_type == 'uccat') ? $mod['linkid'] : 0));
                                ?> 
                            </select>
                        </div>
                            
                        <div id="t_photoalbum" class="form-group menu_target" style="display:<?php if ($link_type == 'photoalbum') { echo 'block'; } else { echo 'none'; } ?>">
                            <label><?php echo $_LANG['AD_CHECK_ALBUM']; ?></label>
                            <select id="blog" class="form-control" style="width:100%" name="blog"> 
                                <?php
                                    echo $inCore->getListItems('cms_photo_albums', (($link_type == 'photoalbum') ? $mod['linkid'] : 0), 'id', 'ASC', 'NSDiffer = ""');
                                ?> 
                            </select>
                        </div>
                    </div>
                </div>
            </td>

            <td width="400" valign="top">
                <div class="uitabs">
                    <ul id="tabs">
                        <li><a href="#upr_publish"><span><?php echo $_LANG['AD_TAB_PUBLISH']; ?></span></a></li>
                        <li><a href="#upr_access"><span><?php echo $_LANG['AD_TAB_ACCESS']; ?></span></a></li>
                        <li><a href="#upr_menu"><span><?php echo $_LANG['AD_MENU']; ?></span></a></li>
                    </ul>
                        
                    <div id="upr_publish">
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="published" value="1" <?php if (cmsCore::getArrVal($mod, 'published') || $do == 'add') { echo 'checked="checked"'; } ?> />
                                <?php echo $_LANG['AD_MENU_POINT_PUBLIC']; ?>
                            </label>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_OPEN_POINT']; ?></label>
                            <select id="target" class="form-control" style="width:100%" name="target">
                                <option value="_self" <?php if (@$mod['target']=='_self') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_SELF']; ?></option>
                                <option value="_parent"><?php echo $_LANG['AD_PARENT'];?></option>
                                <option value="_blank" <?php if (@$mod['target']=='_blank') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_BLANK']; ?></option>
                                <option value="_top" <?php if (@$mod['target']=='_top') { echo 'selected="selected"'; }?>><?php echo $_LANG['AD_TOP']; ?></option>
                            </select>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['TEMPLATE']; ?></label>
                            <select id="template" class="form-control" style="width:100%" name="template"  >
                                <option value="0" <?php if (!cmsCore::getArrVal($mod, 'template')) { echo 'selected="selected"'; } ?>><?php echo $_LANG['AD_BY_DEFAULT'];?></option>
                                <?php
                                $templates = cmsCore::getDirsList('/templates');
                                foreach ($templates as $template) {
                                    if ($template == 'admin') { continue; }
                                    echo '<option value="'. $template .'" '.(cmsCore::getArrVal($mod, 'template') ? 'selected="selected"': '').'>'.$template.'</option>';
                                }
                                ?>
                            </select>
                            <div class="help-block"><?php echo $_LANG['AD_DESIGN_CHANGE'] ;?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_ICON_PICTURE']; ?></label>
                            <input type="text" id="iconurl" class="form-control" style="width:100%" name="iconurl" size="30" value="<?php echo cmsCore::getArrVal($mod, 'iconurl', ''); ?>" />
                                
                            <a id="iconlink" style="display:block;" href="javascript:showIcons()"><?php echo $_LANG['AD_CHECK_ICON'];?></a>
                            <div id="icondiv" style="display:none; padding:6px;border:solid 1px gray;background:#FFF">
                                <div><?php iconList(); ?></div>
                            </div>
                                
                            <div class="help-block"><?php echo $_LANG['AD_ICON_FILENAME'] ;?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_CSS_CLASS']; ?></label>
                            <input type="text" class="form-control" style="width:100%" name="css_class" size="30" value="<?php echo cmsCore::getArrVal($mod, 'css_class', ''); ?>" />
                        </div>
                    </div>
                        
                    <div id="upr_access">
                        <div class="form-group">
                            <?php
                                $groups = cmsUser::getGroups();
                                $style  = 'disabled="disabled"';
                                $public = 'checked="checked"';

                                if ($do == 'edit') {
                                    if ($mod['access_list']) {
                                        $public = '';
                                        $style  = '';
                                        $access_list = $inCore->yamlToArray($mod['access_list']);
                                    }
                                }
                            ?>
                                
                            <label>
                                <input type="checkbox" name="is_public" id="is_public" onclick="checkAccesList()" value="1" <?php echo $public; ?> />
                                <?php echo $_LANG['AD_SHARE']; ?>
                            </label>
                            <div class="help-block"><?php echo $_LANG['AD_VIEW_IF_CHECK'];?></div>
                        </div>
                            
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_GROUPS_VIEW']; ?></label>
                            <?php
                                echo '<select id="allow_group" class="form-control" style="width: 99%" name="allow_group[]"  size="6" multiple="multiple" '.$style.'>';
                                if ($groups) {
                                    foreach($groups as $group) {
                                        echo '<option value="'. $group['id'] .'"';
                                        if ($do == 'edit' && cmsCore::getArrVal($mod, 'access_list')) {
                                            if (in_array($group['id'], $access_list)){
                                                echo 'selected="selected"';
                                            }
                                        }
                                        echo '>';
                                        echo $group['title'] .'</option>';
                                    }
                                }

                                echo '</select>';
                            ?>
                            <div class="help-block"><?php echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];?></div>
                        </div>
                            
                        <div class="form-group">
                            <label>
                                <input type="checkbox" id="is_lax" name="is_lax" value="1" <?php if(cmsCore::getArrVal($mod, 'is_lax')) {?>checked="checked"<?php } ?> />
                                <?php echo $_LANG['AD_ONLY_CHILD_ITEM']; ?>
                            </label>
                        </div>
                    </div>
                        
                    <div id="upr_menu">
                        <div class="form-group">
                            <label><?php echo $_LANG['AD_MENU_TO_VIEW'];?></label>
                            <select class="form-control" style="width: 99%" name="menu[]" size="9" multiple="multiple">
                                <?php foreach ($menu_list as $menu) { ?>
                                <option value="<?php echo $menu['id']; ?>" <?php if (in_array($menu['id'], cmsCore::getArrVal($mod, 'menu', array()))) { echo 'selected="selected"'; }?>>
                                        <?php echo $menu['title']; ?>
                                    </option>
                                <?php } ?>
                            </select>
                            <div class="help-block"><?php echo $_LANG['AD_SELECT_MULTIPLE_CTRL'];?></div>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
    </table>

    <div>
        <input type="button" class="btn btn-primary" name="add_mod" onclick="submitItem()" value="<?php echo $_LANG['SAVE']; ?> " />
        <input type="button" class="btn btn-default" name="back"  value="<?php echo $_LANG['CANCEL'];?>" onclick="window.location.href='index.php?view=menu';" />
        <input type="hidden" name="do" <?php if ($do=='add') { echo 'value="submit"'; } else { echo 'value="update"'; } ?> />
        <?php
            if ($do == 'edit') {
                echo '<input type="hidden" name="id" value="'.$mod['id'].'" />';
            }
        ?>
    </div>
</form>
<?php
   }
}
Example #18
0
 /**
  * Делает апгрейд установленного модуля
  * @param array $component
  * @param array $config
  * @return bool
  */
 public function upgradeModule($module, $config)
 {
     $inDB = cmsDatabase::getInstance();
     // удалить в следующем обновлении
     if (isset($module['link'])) {
         $module['content'] = $module['link'];
     }
     //находим ID установленной версии
     $module_id = $this->getModuleId($module['content']);
     //если модуль еще не был установлен, выходим
     if (!$module_id) {
         return false;
     }
     //загружаем текущие настройки модуля
     $old_config = $this->loadModuleConfig($module_id);
     //удаляем настройки, которые больше не нужны
     foreach ($old_config as $param => $value) {
         if (!isset($config[$param])) {
             unset($old_config[$param]);
         }
     }
     //добавляем настройки, которых раньше не было
     foreach ($config as $param => $value) {
         if (!isset($old_config[$param])) {
             $old_config[$param] = $value;
         }
     }
     //конвертируем массив настроек в YAML
     $module['config'] = $inDB->escape_string(cmsCore::arrayToYaml($old_config));
     unset($module['position']);
     //обновляем модуль в базе
     $inDB->update('cms_modules', $module, $module_id);
     $inDB->query("UPDATE cms_modules SET version = '{$module['version']}' WHERE content='{$module['content']}' AND user=0");
     //модуль успешно обновлен
     return true;
 }
Example #19
0
 public function deleteVote($poll)
 {
     if (!$poll['answers']) {
         return false;
     }
     $inUser = cmsUser::getInstance();
     // Убираем голос пользователя
     foreach ($poll['answers'] as $key => $value) {
         if ($key == $poll['is_user_vote']) {
             $poll['answers'][$key] -= 1;
         }
     }
     $answers = $this->inDB->escape_string(cmsCore::arrayToYaml($poll['answers']));
     $this->inDB->query("UPDATE cms_forum_polls SET answers = '{$answers}' WHERE id = '{$poll['id']}'");
     $this->inDB->delete('cms_forum_votes', "poll_id = '{$poll['id']}' AND user_id = '{$inUser->id}'", 1);
     return true;
 }
Example #20
0
function registration()
{
    header('X-Frame-Options: DENY');
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    $inConf = cmsConfig::getInstance();
    $model = new cms_model_registration();
    cmsCore::loadModel('users');
    $users_model = new cms_model_users();
    global $_LANG;
    $do = $inCore->do;
    //============================================================================//
    if ($do == 'sendremind') {
        if ($inUser->id) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['REMINDER_PASS']);
        $inPage->addPathway($_LANG['REMINDER_PASS']);
        if (!cmsCore::inRequest('goremind')) {
            cmsPage::initTemplate('components', 'com_registration_sendremind')->display('com_registration_sendremind.tpl');
        } else {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $email = cmsCore::request('email', 'email', '');
            if (!$email) {
                cmsCore::addSessionMessage($_LANG['ERR_EMAIL'], 'error');
                cmsCore::redirectBack();
            }
            $usr = cmsUser::getShortUserData($email);
            if (!$usr || $usr['is_locked'] || $usr['is_deleted']) {
                cmsCore::addSessionMessage($_LANG['ADRESS'] . ' "' . $email . '" ' . $_LANG['NOT_IN_OUR_BASE'], 'error');
                cmsCore::redirectBack();
            }
            if (cmsUser::userIsAdmin($usr['id'])) {
                cmsCore::addSessionMessage($_LANG['NOT_ADMIN_SENDREMIND'], 'error');
                cmsCore::redirectBack();
            }
            $usercode = md5($usr['id'] . '-' . uniqid() . '-' . microtime() . '-' . PATH);
            $sql = "INSERT cms_users_activate (pubdate, user_id, code)\n                VALUES (NOW(), '{$usr['id']}', '{$usercode}')";
            $inDB->query($sql);
            $newpass_link = HOST . '/registration/remind/' . $usercode;
            $mail_message = $_LANG['HELLO'] . ', ' . $usr['nickname'] . '!' . "\n\n";
            $mail_message .= $_LANG['REMINDER_TEXT'] . ' "' . $inConf->sitename . '".' . "\n\n";
            $mail_message .= $_LANG['YOUR_LOGIN'] . ': ' . $usr['login'] . "\n\n";
            $mail_message .= $_LANG['NEW_PASS_LINK'] . ":\n" . $newpass_link . "\n\n";
            $mail_message .= $_LANG['LINK_EXPIRES'] . "\n\n";
            $mail_message .= $_LANG['SIGNATURE'] . ', ' . $inConf->sitename . ' (' . HOST . ').' . "\n";
            $mail_message .= date('d-m-Y (H:i)');
            $inCore->mailText($email, $inConf->sitename . ' - ' . $_LANG['REMINDER_PASS'], $mail_message);
            cmsCore::addSessionMessage($_LANG['NEW_PAS_SENDED'], 'info');
            cmsCore::redirect('/login');
        }
    }
    //============================================================================//
    if ($do == 'remind') {
        if ($inUser->id) {
            cmsCore::error404();
        }
        $usercode = cmsCore::request('code', 'str', '');
        //проверяем формат кода
        if (!preg_match('/^[0-9a-f]{32}$/i', $usercode)) {
            cmsCore::error404();
        }
        // проверяем код
        $user_id = $inDB->get_field('cms_users_activate', "code = '{$usercode}'", 'user_id');
        if (!$user_id) {
            cmsCore::error404();
        }
        //получаем пользователя
        $user = $inDB->get_fields('cms_users', "id = '{$user_id}'", '*');
        if (!$user) {
            cmsCore::error404();
        }
        if (cmsUser::userIsAdmin($user['id'])) {
            cmsCore::error404();
        }
        if (cmsCore::inRequest('submit')) {
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            $errors = false;
            $pass = cmsCore::request('pass', 'str', '');
            $pass2 = cmsCore::request('pass2', 'str', '');
            if (!$pass) {
                cmsCore::addSessionMessage($_LANG['TYPE_PASS'], 'error');
                $errors = true;
            }
            if ($pass && !$pass2) {
                cmsCore::addSessionMessage($_LANG['TYPE_PASS_TWICE'], 'error');
                $errors = true;
            }
            if ($pass && $pass2 && mb_strlen($pass) < 6) {
                cmsCore::addSessionMessage($_LANG['PASS_SHORT'], 'error');
                $errors = true;
            }
            if ($pass && $pass2 && $pass != $pass2) {
                cmsCore::addSessionMessage($_LANG['WRONG_PASS'], 'error');
                $errors = true;
            }
            if ($errors) {
                cmsCore::redirectBack();
            }
            $md5_pass = md5($pass);
            $inDB->query("UPDATE cms_users SET password = '******', logdate = NOW() WHERE id = '{$user['id']}'");
            $inDB->query("DELETE FROM cms_users_activate WHERE code = '{$usercode}'");
            cmsCore::addSessionMessage($_LANG['CHANGE_PASS_COMPLETED'], 'info');
            $inUser->signInUser($user['login'], $pass, true);
            cmsCore::redirect(cmsUser::getProfileURL($user['login']));
        }
        $inPage->setTitle($_LANG['RECOVER_PASS']);
        $inPage->addPathway($_LANG['RECOVER_PASS']);
        cmsPage::initTemplate('components', 'com_registration_remind')->assign('cfg', $model->config)->assign('user', $user)->display('com_registration_remind.tpl');
    }
    //============================================================================//
    if ($do == 'register') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        if ($inUser->id && !$inUser->is_admin) {
            if ($inCore->menuId() == 1) {
                return;
            } else {
                cmsCore::error404();
            }
        }
        // регистрация закрыта
        if (!$model->config['is_on']) {
            cmsCore::error404();
        }
        // регистрация по инвайтам
        if ($model->config['reg_type'] == 'invite') {
            if (!$users_model->checkInvite(cmsUser::sessionGet('invite_code'))) {
                cmsCore::error404();
            }
        }
        $errors = false;
        // получаем данные
        $item['login'] = cmsCore::request('login', 'str', '');
        $item['email'] = cmsCore::request('email', 'email');
        $item['icq'] = cmsCore::request('icq', 'str', '');
        $item['city'] = cmsCore::request('city', 'str', '');
        $item['nickname'] = cmsCore::request('nickname', 'str', '');
        $item['realname1'] = cmsCore::request('realname1', 'str', '');
        $item['realname2'] = cmsCore::request('realname2', 'str', '');
        $pass = cmsCore::request('pass', 'str', '');
        $pass2 = cmsCore::request('pass2', 'str', '');
        // проверяем логин
        if (mb_strlen($item['login']) < 2 || mb_strlen($item['login']) > 15 || is_numeric($item['login']) || !preg_match("/^([a-z0-9])+\$/ui", $item['login'])) {
            cmsCore::addSessionMessage($_LANG['ERR_LOGIN'], 'error');
            $errors = true;
        }
        // проверяем пароль
        if (!$pass) {
            cmsCore::addSessionMessage($_LANG['TYPE_PASS'], 'error');
            $errors = true;
        }
        if ($pass && !$pass2) {
            cmsCore::addSessionMessage($_LANG['TYPE_PASS_TWICE'], 'error');
            $errors = true;
        }
        if ($pass && $pass2 && mb_strlen($pass) < 6) {
            cmsCore::addSessionMessage($_LANG['PASS_SHORT'], 'error');
            $errors = true;
        }
        if ($pass && $pass2 && $pass != $pass2) {
            cmsCore::addSessionMessage($_LANG['WRONG_PASS'], 'error');
            $errors = true;
        }
        // Проверяем nickname или имя и фамилию
        if ($model->config['name_mode'] == 'nickname') {
            if (!$item['nickname']) {
                cmsCore::addSessionMessage($_LANG['TYPE_NICKNAME'], 'error');
                $errors = true;
            }
        } else {
            if (!$item['realname1']) {
                cmsCore::addSessionMessage($_LANG['TYPE_NAME'], 'error');
                $errors = true;
            }
            if (!$item['realname2']) {
                cmsCore::addSessionMessage($_LANG['TYPE_SONAME'], 'error');
                $errors = true;
            }
            $item['nickname'] = trim($item['realname1']) . ' ' . trim($item['realname2']);
        }
        if (mb_strlen($item['nickname']) < 2) {
            cmsCore::addSessionMessage($_LANG['SHORT_NICKNAME'], 'error');
            $errors = true;
        }
        if ($model->getBadNickname($item['nickname'])) {
            cmsCore::addSessionMessage($_LANG['ERR_NICK_EXISTS'], 'error');
            $errors = true;
        }
        // Проверяем email
        if (!$item['email']) {
            cmsCore::addSessionMessage($_LANG['ERR_EMAIL'], 'error');
            $errors = true;
        }
        // День рождения
        list($item['bday'], $item['bmonth'], $item['byear']) = array_values(cmsCore::request('birthdate', 'array_int', array()));
        $item['birthdate'] = sprintf('%04d-%02d-%02d', $item['byear'], $item['bmonth'], $item['bday']);
        // получаем данные конструктора форм
        $item['formsdata'] = '';
        if (isset($users_model->config['privforms'])) {
            if (is_array($users_model->config['privforms'])) {
                foreach ($users_model->config['privforms'] as $form_id) {
                    $form_input = cmsForm::getFieldsInputValues($form_id);
                    $item['formsdata'] .= $inDB->escape_string(cmsCore::arrayToYaml($form_input['values']));
                    // Проверяем значения формы
                    foreach ($form_input['errors'] as $field_error) {
                        if ($field_error) {
                            cmsCore::addSessionMessage($field_error, 'error');
                            $errors = true;
                        }
                    }
                }
            }
        }
        // Проверяем каптчу
        if (!cmsPage::checkCaptchaCode()) {
            cmsCore::addSessionMessage($_LANG['ERR_CAPTCHA'], 'error');
            $errors = true;
        }
        // проверяем есть ли такой пользователь
        $user_exist = $inDB->get_fields('cms_users', "(login LIKE '{$item['login']}' OR email LIKE '{$item['email']}') AND is_deleted = 0", 'id, login, email');
        if ($user_exist) {
            if ($user_exist['login'] == $item['login']) {
                cmsCore::addSessionMessage($_LANG['LOGIN'] . ' "' . $item['login'] . '" ' . $_LANG['IS_BUSY'], 'error');
                $errors = true;
            } else {
                cmsCore::addSessionMessage($_LANG['EMAIL_IS_BUSY'], 'error');
                $errors = true;
            }
        }
        // В случае ошибок, возвращаемся в форму
        if ($errors) {
            cmsUser::sessionPut('item', $item);
            cmsCore::redirect('/registration');
        }
        //////////////////////////////////////////////
        //////////// РЕГИСТРАЦИЯ /////////////////////
        //////////////////////////////////////////////
        $item['is_locked'] = $model->config['act'];
        $item['password'] = md5($pass);
        $item['orig_password'] = $pass;
        $item['group_id'] = $model->config['default_gid'];
        $item['regdate'] = date('Y-m-d H:i:s');
        $item['logdate'] = date('Y-m-d H:i:s');
        if (cmsUser::sessionGet('invite_code')) {
            $invite_code = cmsUser::sessionGet('invite_code');
            $item['invited_by'] = (int) $users_model->getInviteOwner($invite_code);
            if ($item['invited_by']) {
                $users_model->closeInvite($invite_code);
            }
            cmsUser::sessionDel('invite_code');
        } else {
            $item['invited_by'] = 0;
        }
        $item = cmsCore::callEvent('USER_BEFORE_REGISTER', $item);
        $item['id'] = $item['user_id'] = $inDB->insert('cms_users', $item);
        if (!$item['id']) {
            cmsCore::error404();
        }
        $inDB->insert('cms_user_profiles', $item);
        cmsCore::callEvent('USER_REGISTER', $item);
        if ($item['is_locked']) {
            $model->sendActivationNotice($pass, $item['id']);
            cmsPage::includeTemplateFile('special/regactivate.php');
            cmsCore::halt();
        } else {
            cmsActions::log('add_user', array('object' => '', 'user_id' => $item['id'], 'object_url' => '', 'object_id' => $item['id'], 'target' => '', 'target_url' => '', 'target_id' => 0, 'description' => ''));
            if ($model->config['send_greetmsg']) {
                $model->sendGreetsMessage($item['id']);
            }
            $model->sendRegistrationNotice($pass, $item['id']);
            $back_url = $inUser->signInUser($item['login'], $pass, true);
            cmsCore::redirect($back_url);
        }
    }
    //============================================================================//
    if ($do == 'view') {
        $pagetitle = $inCore->getComponentTitle();
        $inPage->setTitle($pagetitle);
        $inPage->addPathway($pagetitle);
        $inPage->addHeadJsLang(array('WRONG_PASS'));
        // Если пользователь авторизован, то не показываем форму регистрации, редирект в профиль.
        if ($inUser->id && !$inUser->is_admin) {
            if ($inCore->menuId() == 1) {
                return;
            } else {
                cmsCore::redirect(cmsUser::getProfileURL($inUser->login));
            }
        }
        $correct_invite = cmsUser::sessionGet('invite_code') ? true : false;
        if ($model->config['reg_type'] == 'invite' && cmsCore::inRequest('invite_code')) {
            $invite_code = cmsCore::request('invite_code', 'str', '');
            $correct_invite = $users_model->checkInvite($invite_code);
            if ($correct_invite) {
                cmsUser::sessionPut('invite_code', $invite_code);
            } else {
                cmsCore::addSessionMessage($_LANG['INCORRECT_INVITE'], 'error');
            }
        }
        $item = cmsUser::sessionGet('item');
        if ($item) {
            cmsUser::sessionDel('item');
        }
        if (empty($item['birthdate'])) {
            $item['birthdate'] = date('Y-m-d');
        }
        $private_forms = array();
        if (isset($users_model->config['privforms'])) {
            if (is_array($users_model->config['privforms'])) {
                foreach ($users_model->config['privforms'] as $form_id) {
                    $private_forms = array_merge($private_forms, cmsForm::getFieldsHtml($form_id, array(), true));
                }
            }
        }
        cmsPage::initTemplate('components', 'com_registration')->assign('cfg', $model->config)->assign('item', $item)->assign('pagetitle', $pagetitle)->assign('correct_invite', $correct_invite)->assign('private_forms', $private_forms)->display('com_registration.tpl');
    }
    //============================================================================//
    if ($do == 'activate') {
        $code = cmsCore::request('code', 'str', '');
        if (!$code) {
            cmsCore::error404();
        }
        $user_id = $inDB->get_field('cms_users_activate', "code = '{$code}'", 'user_id');
        if (!$user_id) {
            cmsCore::error404();
        }
        $inDB->query("UPDATE cms_users SET is_locked = 0 WHERE id = '{$user_id}'");
        $inDB->query("DELETE FROM cms_users_activate WHERE code = '{$code}'");
        cmsCore::callEvent('USER_ACTIVATED', $user_id);
        if ($model->config['send_greetmsg']) {
            $model->sendGreetsMessage($user_id);
        }
        // Регистрируем событие
        cmsActions::log('add_user', array('object' => '', 'user_id' => $user_id, 'object_url' => '', 'object_id' => $user_id, 'target' => '', 'target_url' => '', 'target_id' => 0, 'description' => ''));
        cmsCore::addSessionMessage($_LANG['ACTIVATION_COMPLETE'], 'info');
        cmsUser::goToLogin();
    }
    //============================================================================//
    if ($do == 'auth') {
        //====================//
        //==  разлогивание  ==//
        if (cmsCore::inRequest('logout')) {
            $inUser->logout();
            cmsCore::redirect('/');
        }
        //====================//
        //==  авторизация  ==//
        if (!cmsCore::inRequest('logout')) {
            // флаг неуспешных авторизаций
            $anti_brute_force = cmsUser::sessionGet('anti_brute_force');
            $login = cmsCore::request('login', 'str', '');
            $passw = cmsCore::request('pass', 'str', '');
            $remember_pass = cmsCore::inRequest('remember');
            // если нет логина или пароля, показываем форму входа
            if (!$login || !$passw) {
                if ($inUser->id && !$inUser->is_admin) {
                    cmsCore::redirect('/');
                }
                $inPage->setTitle($_LANG['SITE_LOGIN']);
                $inPage->addPathway($_LANG['SITE_LOGIN']);
                cmsPage::initTemplate('components', 'com_registration_login')->assign('cfg', $model->config)->assign('anti_brute_force', $anti_brute_force)->assign('is_sess_back', cmsUser::sessionGet('auth_back_url'))->display('com_registration_login.tpl');
                if (!mb_strstr(cmsCore::getBackURL(), 'login')) {
                    cmsUser::sessionPut('auth_back_url', cmsCore::getBackURL());
                }
                return;
            }
            if (!cmsUser::checkCsrfToken()) {
                cmsCore::error404();
            }
            // Проверяем каптчу
            if ($anti_brute_force && !cmsPage::checkCaptchaCode()) {
                cmsCore::addSessionMessage($_LANG['ERR_CAPTCHA'], 'error');
                cmsCore::redirect('/login');
            }
            cmsUser::sessionDel('anti_brute_force');
            $back_url = $inUser->signInUser($login, $passw, $remember_pass);
            cmsCore::redirect($back_url);
        }
    }
    //============================================================================//
    if ($do == 'autherror') {
        cmsUser::sessionPut('anti_brute_force', 1);
        cmsPage::includeTemplateFile('special/autherror.php');
        cmsCore::halt();
    }
    //============================================================================//
}
Example #21
0
            $item['config']['size'] = cmsCore::request('f_list_size', 'int');
            break;
        case 'menu':
            $item['config']['items'] = cmsCore::request('f_menu_list', 'str', '');
            $item['config']['size'] = cmsCore::request('f_menu_size', 'int');
            break;
        case 'file':
            $exts = cmsCore::request('f_file_ext', 'str', '');
            while (mb_strpos($exts, 'htm') || mb_strpos($exts, 'php') || mb_strpos($exts, 'ht')) {
                $exts = str_replace(array('htm', 'php', 'ht'), '', mb_strtolower($exts));
            }
            $item['config']['ext'] = str_replace(' ', '', $exts);
            $item['config']['size'] = cmsCore::request('f_file_size', 'int');
            break;
    }
    $item['config'] = cmsCore::c('db')->escape_string(cmsCore::arrayToYaml($item['config']));
    if ($opt == 'add_field') {
        cmsCore::c('db')->insert('cms_form_fields', cmsCore::callEvent('ADD_FORM_FIELD', $item));
    } else {
        cmsCore::c('db')->update('cms_form_fields', cmsCore::callEvent('UPDATE_FORM_FIELD', $item), cmsCore::request('field_id', 'int'));
    }
    cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS']);
    cmsCore::redirect('?view=components&do=config&id=' . $id . '&opt=edit&item_id=' . $item['form_id']);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (in_array($opt, array('submit', 'update'))) {
    if (!cmsUser::checkCsrfToken()) {
        cmsCore::error404();
    }
    $item['title'] = cmsCore::request('title', 'str', $_LANG['AD_FORM_UNTITLED']);
    $item['description'] = cmsCore::c('db')->escape_string(cmsCore::request('description', 'html', ''));
Example #22
0
    $category_id = cmsCore::request('category_id', 'int');
    $title       = cmsCore::request('title', 'str', 'NO_TITLE');
    $pagetitle   = cmsCore::request('pagetitle', 'str', '');
    $meta_keys   = cmsCore::request('meta_keys', 'str', '');
    $meta_desc   = cmsCore::request('meta_desc', 'str', '');
    $published   = cmsCore::request('published', 'int');
    $parent_id   = cmsCore::request('parent_id', 'int');
    $description = cmsCore::request('description', 'str');
    $topic_cost  = cmsCore::request('topic_cost', 'int', 0);
    $moder_list  = cmsCore::request('moder_list', 'array_int', array());
    $moder_list  = $moder_list ? cmsCore::arrayToYaml($moder_list) : '';

    $is_access = cmsCore::request('is_access', 'int', '');
    if (!$is_access) {
        $access_list = cmsCore::request('access_list', 'array_int');
        $group_access = $access_list ? cmsCore::arrayToYaml($access_list) : '';
        cmsCore::c('db')->query("UPDATE cms_forum_threads SET is_hidden = 1 WHERE forum_id = '". $item_id ."'");
    } else {
        $group_access = '';
        cmsCore::c('db')->query("UPDATE cms_forum_threads SET is_hidden = 0 WHERE forum_id = '". $item_id ."'");
    }

    $ns = $inCore->nestedSetsInit('cms_forums');
    $old = cmsCore::c('db')->get_fields('cms_forums', "id='". $item_id ."'", '*');

    $icon = uploadCategoryIcon($old['icon']);

    if ($parent_id != $old['parent_id']) {
        $ns->MoveNode($item_id, $parent_id);
    }
Example #23
0
function applet_menu()
{
    $inCore = cmsCore::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/menu', $adminAccess)) {
        cpAccessDenied();
    }
    cmsCore::c('page')->setTitle($_LANG['AD_MENU']);
    cpAddPathway($_LANG['AD_MENU'], 'index.php?view=menu');
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    if ($do == 'list') {
        $toolmenu = array(array('icon' => 'new.gif', 'title' => $_LANG['AD_MENU_POINT_ADD'], 'link' => '?view=menu&do=add'), array('icon' => 'newmenu.gif', 'title' => $_LANG['AD_MENU_ADD'], 'link' => '?view=menu&do=addmenu'), array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=edit&multiple=1');"), array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=delete&multiple=1');"), array('icon' => 'show.gif', 'title' => $_LANG['AD_ALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=show&multiple=1');"), array('icon' => 'hide.gif', 'title' => $_LANG['AD_DISALLOW_SELECTED'], 'link' => "javascript:checkSel('?view=menu&do=hide&multiple=1');"), array('icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=menu'));
        cpToolMenu($toolmenu);
        $fields = array(array('title' => 'Lt', 'field' => 'NSLeft', 'width' => '40'), array('title' => $_LANG['TITLE'], 'field' => array('title', 'titles'), 'width' => '', 'link' => '?view=menu&do=edit&id=%id%', 'prc' => function ($i) {
            $i['titles'] = cmsCore::yamlToArray($i['titles']);
            // переопределяем название пункта меню в зависимости от языка
            if (!empty($i['titles'][cmsConfig::getConfig('lang')])) {
                $i['title'] = $i['titles'][cmsConfig::getConfig('lang')];
            }
            return $i['title'];
        }), array('title' => $_LANG['SHOW'], 'field' => 'published', 'width' => '80'), array('title' => $_LANG['AD_ORDER'], 'field' => 'ordering', 'width' => '100'), array('title' => $_LANG['AD_LINK'], 'field' => array('linktype', 'linkid', 'link'), 'width' => '240', 'prc' => 'cpMenutypeById'), array('title' => $_LANG['AD_MENU'], 'field' => 'menu', 'width' => '80', 'filter' => '10', 'filterlist' => cpGetList('menu'), 'prc' => 'list_menu'), array('title' => $_LANG['TEMPLATE'], 'field' => 'template', 'width' => '90', 'prc' => 'cpTemplateById'));
        $actions = array(array('title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=menu&do=edit&id=%id%'), array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_MENU_POINT_CONFIRM'], 'link' => '?view=menu&do=delete&id=%id%'));
        cpListTable('cms_menu', $fields, $actions, 'parent_id>0', 'NSLeft, ordering');
    } else {
        $toolmenu = array(array('icon' => 'save.gif', 'title' => $_LANG['SAVE'], 'link' => 'javascript:document.addform.submit();'), array('icon' => 'cancel.gif', 'title' => $_LANG['CANCEL'], 'link' => 'index.php?view=menu'));
        cpToolMenu($toolmenu);
    }
    if ($do == 'move_up') {
        cmsCore::c('db')->moveNsCategory('cms_menu', $id, 'up');
        cmsCore::redirectBack();
    }
    if ($do == 'move_down') {
        cmsCore::c('db')->moveNsCategory('cms_menu', $id, 'down');
        cmsCore::redirectBack();
    }
    if ($do == 'show') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) {
                cmsCore::c('db')->setFlag('cms_menu', $id, 'published', '1');
            }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_menu', $_REQUEST['item'], 'published', '1');
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'hide') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) {
                cmsCore::c('db')->setFlag('cms_menu', $id, 'published', '0');
            }
            cmsCore::halt('1');
        } else {
            cmsCore::c('db')->setFlags('cms_menu', cmsCore::request('item', 'array_int', array()), 'published', '0');
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) {
                cmsCore::c('db')->deleteNS('cms_menu', (int) $id);
            }
        } else {
            cmsCore::c('db')->deleteListNS('cms_menu', cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirectBack();
    }
    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $id = cmsCore::request('id', 'int', 0);
        if (!$id) {
            cmsCore::redirectBack();
        }
        $title = cmsCore::request('title', 'str', '');
        $titles = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $menu = cmsCore::arrayToYaml(cmsCore::request('menu', 'array_str', ''));
        $linktype = cmsCore::request('mode', 'str', '');
        $linkid = cmsCore::request($linktype, 'str', '');
        $link = $inCore->getMenuLink($linktype, $linkid);
        $target = cmsCore::request('target', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $template = cmsCore::request('template', 'str', '');
        $iconurl = cmsCore::request('iconurl', 'str', '');
        $parent_id = cmsCore::request('parent_id', 'int', 0);
        $oldparent = cmsCore::request('oldparent', 'int', 0);
        $is_lax = cmsCore::request('is_lax', 'int', 0);
        $css_class = cmsCore::request('css_class', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }
        $ns = $inCore->nestedSetsInit('cms_menu');
        if ($oldparent != $parent_id) {
            $ns->MoveNode($id, $parent_id);
        }
        $sql = "UPDATE cms_menu\r\n                SET title='" . $title . "',\r\n                    titles='" . $titles . "',\r\n                    css_class='" . $css_class . "',\r\n                    menu='" . $menu . "',\r\n                    link='" . $link . "',\r\n                    linktype='" . $linktype . "',\r\n                    linkid='" . $linkid . "',\r\n                    target='" . $target . "',\r\n                    published='" . $published . "',\r\n                    template='" . $template . "',\r\n                    access_list='" . $access_list . "',\r\n                    is_lax='" . $is_lax . "',\r\n                    iconurl='" . $iconurl . "'\r\n                WHERE id = '" . $id . "'\r\n                LIMIT 1";
        cmsCore::c('db')->query($sql);
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        if (!isset($_SESSION['editlist']) || count($_SESSION['editlist']) == 0) {
            cmsCore::redirect('?view=menu');
        } else {
            cmsCore::redirect('?view=menu&do=edit');
        }
    }
    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $title = cmsCore::request('title', 'str', '');
        $titles = cmsCore::arrayToYaml(cmsCore::request('titles', 'array_str', array()));
        $menu = cmsCore::arrayToYaml(cmsCore::request('menu', 'array_str', ''));
        $linktype = cmsCore::request('mode', 'str', '');
        $linkid = cmsCore::request($linktype, 'str', '');
        $link = $inCore->getMenuLink($linktype, $linkid);
        $target = cmsCore::request('target', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $template = cmsCore::request('template', 'str', '');
        $iconurl = cmsCore::request('iconurl', 'str', '');
        $parent_id = cmsCore::request('parent_id', 'int', 0);
        $css_class = cmsCore::request('css_class', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        $is_lax = cmsCore::request('is_lax', 'int', 0);
        if (!$is_public) {
            $access_list = cmsCore::arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }
        $ns = $inCore->nestedSetsInit('cms_menu');
        $myid = $ns->AddNode($parent_id);
        $sql = "UPDATE cms_menu\r\n                        SET menu='" . $menu . "',\r\n                                title='" . $title . "',\r\n                                titles='" . $titles . "',\r\n                                css_class='" . $css_class . "',\r\n                                link='" . $link . "',\r\n                                linktype='" . $linktype . "',\r\n                                linkid='" . $linkid . "',\r\n                                target='" . $target . "',\r\n                                published='" . $published . "',\r\n                                template='" . $template . "',\r\n                                access_list='" . $access_list . "',\r\n                                is_lax='" . $is_lax . "',\r\n                                iconurl='" . $iconurl . "'\r\n                        WHERE id = '" . $myid . "'";
        cmsCore::c('db')->query($sql);
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('?view=menu');
    }
    if ($do == 'submitmenu') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $sql = "SELECT ordering as max_o FROM cms_modules ORDER BY ordering DESC LIMIT 1";
        $result = cmsCore::c('db')->query($sql);
        $row = cmsCore::c('db')->fetch_assoc($result);
        $maxorder = $row['max_o'] + 1;
        $menu = cmsCore::request('menu', 'str', '');
        $title = cmsCore::request('title', 'str', '');
        $position = cmsCore::request('position', 'str', '');
        $published = cmsCore::request('published', 'int', 0);
        $css_prefix = cmsCore::request('css_prefix', 'str', '');
        $is_public = cmsCore::request('is_public', 'int', '');
        if (!$is_public) {
            $access_list = $inCore->arrayToYaml(cmsCore::request('allow_group', 'array_int'));
        }
        $cfg['menu'] = $menu;
        $cfg_str = cmsCore::arrayToYaml($cfg);
        $sql = "INSERT INTO cms_modules (position, name, title, is_external, content, ordering, showtitle, published, user, config, css_prefix, access_list)\r\n                VALUES ('" . $position . "', '" . $_LANG['AD_MENU'] . "', '" . $title . "', 1, 'mod_menu', " . $maxorder . ", 1, " . $published . ", 0, '" . $cfg_str . "', '" . $css_prefix . "', '" . $access_list . "')";
        cmsCore::c('db')->query($sql);
        $newid = cmsCore::c('db')->get_last_id('cms_modules');
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('?view=modules&do=edit&id=' . $newid);
    }
    if ($do == 'addmenu' || $do == 'add' || $do == 'edit') {
        cmsCore::c('page')->addHeadJS('admin/js/menu.js');
        echo '<script>';
        echo cmsPage::getLangJS('AD_SPECIFY_LINK_MENU');
        echo '</script>';
    }
    if ($do == 'addmenu') {
        cmsCore::c('page')->setTitle($_LANG['AD_MENU_ADD']);
        cpAddPathway($_LANG['AD_MENU_ADD']);
        cmsCore::c('page')->initTemlate('applets', 'menu_addmenu')->assign('menu_list', cpGetList('menu'))->assign('pos', cpModulePositions(cmsCore::c('config')->template))->assign('groups', cmsUser::getGroups())->assign('access_list', !empty($mod['access_list']) ? $inCore->yamlToArray($mod['access_list']) : array())->assign('mod', $mod)->display();
    }
    if ($do == 'add' || $do == 'edit') {
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_MENU_POINT_ADD']);
            $mod['menu'] = array('mainmenu');
        } else {
            if (isset($_REQUEST['multiple'])) {
                if (isset($_REQUEST['item'])) {
                    $_SESSION['editlist'] = cmsCore::request('item', 'array_int', array());
                } else {
                    cmsCore::addSessionMessage($_LANG['AD_NO_SELECT_OBJECTS'], 'error');
                    cmsCore::redirectBack();
                }
            }
            $ostatok = '';
            if (isset($_SESSION['editlist'])) {
                $item_id = array_shift($_SESSION['editlist']);
                if (sizeof($_SESSION['editlist']) == 0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '(' . $_LANG['AD_NEXT_IN'] . sizeof($_SESSION['editlist']) . ')';
                }
            } else {
                $item_id = cmsCore::request('id', 'int', 0);
            }
            $mod = cmsCore::c('db')->get_fields('cms_menu', "id = '{$item_id}'", '*');
            if (!$mod) {
                cmsCore::error404();
            }
            $mod['menu'] = cmsCore::yamlToArray($mod['menu']);
            $mod['titles'] = cmsCore::yamlToArray($mod['titles']);
            cpAddPathway($_LANG['AD_MENU_POINT_EDIT'] . $ostatok . ' "' . $mod['title'] . '"');
        }
        $linktype = cmsCore::getArrVal($mod, 'linktype', 'link');
        $tpl = cmsCore::c('page')->initTemplate('applets', 'menu_add')->assign('linktype', $linktype)->assign('langs', cmsCore::getDirsList('/languages'))->assign('templates', cmsCore::getDirsList('/templates'))->assign('menu_list', cpGetList('menu'))->assign('rootid', cmsCore::c('db')->get_field('cms_menu', 'parent_id=0', 'id'))->assign('menu_opt', $inCore->getListItemsNS('cms_menu', cmsCore::getArrVal($mod, 'parent_id', 0)))->assign('content_opt', $inCore->getListItems('cms_content', $linktype == 'content' ? $mod['linkid'] : 0))->assign('category_opt', $inCore->getListItemsNS('cms_category', $link_type == 'category' ? $mod['linkid'] : 0))->assign('components_opt', $inCore->getListItems('cms_components', $link_type == 'component' ? $mod['linkid'] : 0, 'title', 'asc', 'internal=0', 'link'))->assign('blogs_opt', $inCore->getListItems('cms_blogs', $link_type == 'blog' ? $mod['linkid'] : 0, 'title', 'asc', "owner='user'"))->assign('uc_cats_opt', $inCore->getListItems('cms_uc_cats', $link_type == 'uccat' ? $mod['linkid'] : 0))->assign('photo_albums_opt', $inCore->getListItems('cms_photo_albums', $link_type == 'photoalbum' ? $mod['linkid'] : 0, 'id', 'ASC', 'NSDiffer = ""'))->assign('video_installed', $inCore->isComponentInstalled('video'))->assign('iconList', iconList())->assign('mod', $mod);
        if ($inCore->isComponentInstalled('video')) {
            $tpl->assign('video_cats_opt', $inCore->getListItemsNS('cms_video_category', $linktype == 'video_cat' ? $mod['linkid'] : 0));
        }
        $tpl->display();
    }
}