Esempio n. 1
0
function applet_templates()
{
    global $adminAccess;
    global $_LANG;
    if (!cmsUser::isAdminCan('admin/config', $adminAccess)) {
        cpAccessDenied();
    }
    $do = cmsCore::request('do', array('config', 'save_config'), 'main');
    cmsCore::c('page')->setTitle($_LANG['AD_TEMPLATES_SETTING']);
    cpAddPathway($_LANG['AD_TEMPLATES_SETTING'], 'index.php?view=templates');
    if ($do == 'main') {
        cmsCore::c('page')->initTemplate('applets', 'templates')->assign('templates', cmsCore::getDirsList('/templates'))->display();
    }
    if ($do == 'config') {
        $template = cmsCore::request('template', 'str', '');
        cpAddPathway($_LANG['AD_TEMPLATE'] . ': ' . $template, 'index.php?view=templates&do=config&template=' . $template);
        if (!file_exists(PATH . '/templates/' . $template) || !file_exists(PATH . '/templates/' . $template . '/config.php')) {
            cmsCore::error404();
        }
        include PATH . '/templates/' . $template . '/config.php';
        if (function_exists('get_template_cfg_fields')) {
            $tpl_cfgs = get_template_cfg_fields();
            if (!empty($tpl_cfgs)) {
                $tpl_cfgs_val = cmsCore::getTplCfg($template);
                cmsCore::c('page')->initTemplate('applets', 'templates')->assign('template', $template)->assign('form_gen_form', cmsCore::c('form_gen')->generateForm($tpl_cfgs, $tpl_cfgs_val))->display();
            } else {
                cmsCore::addSessionMessage($_LANG['AD_TEMPLATE_NO_CONFIG'], 'error');
                cmsCore::redirectBack();
            }
        } else {
            cmsCore::addSessionMessage($_LANG['AD_TEMPLATE_CFG_ERROR'], 'error');
            cmsCore::redirectBack();
        }
    }
    if ($do == 'save_config') {
        $template = cmsCore::request('template', 'str', '');
        if (!file_exists(PATH . '/templates/' . $template) || !file_exists(PATH . '/templates/' . $template . '/config.php') || !cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        include PATH . '/templates/' . $template . '/config.php';
        if (function_exists('get_template_cfg_fields')) {
            $tpl_cfgs = get_template_cfg_fields();
            if (!empty($tpl_cfgs)) {
                $tpl_cfgs = cmsCore::c('form_gen')->requestForm($tpl_cfgs);
                cmsCore::saveTplCfg($tpl_cfgs, $template);
                cmsCore::addSessionMessage($_LANG['AD_TEMPLATE_CFG_SAVED'], 'success');
                cmsCore::redirect('/admin/index.php?view=templates');
            } else {
                cmsCore::error404();
            }
        } else {
            cmsCore::error404();
        }
    }
}
Esempio n. 2
0
function applet_arhive()
{
    $inCore = cmsCore::getInstance();
    global $_LANG;
    cmsCore::c('page')->setTitle($_LANG['AD_ARTICLES_ARCHIVE']);
    $cfg = $inCore->loadComponentConfig('content');
    $cfg_arhive = $inCore->loadComponentConfig('arhive');
    cpAddPathway($_LANG['AD_ARTICLE_SITE'], 'index.php?view=tree');
    cpAddPathway($_LANG['AD_ARTICLES_ARCHIVE'], 'index.php?view=arhive');
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    if ($do == 'saveconfig') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $cfg['source'] = cmsCore::request('source', 'str', '');
        $inCore->saveComponentConfig('arhive', $cfg);
        cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        cmsCore::redirect('?view=arhive&do=config');
    }
    if ($do == 'config') {
        $toolmenu = array(array('icon' => 'folders.gif', 'title' => $_LANG['AD_LIST_OF_ARTICLES'], 'link' => '?view=arhive'));
        cpToolMenu($toolmenu);
        cpAddPathway($_LANG['AD_SETTINGS'], 'index.php?view=arhive&do=config');
        cmsCore::c('page')->initTemplate('applets', 'arhive')->assign('cfg_arhive', $cfg_arhive)->display();
    }
    if ($do == 'list') {
        $toolmenu = array(array('icon' => 'config.gif', 'title' => $_LANG['AD_SETTINGS'], 'link' => '?view=arhive&do=config'), array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=arhive&do=delete&multiple=1');"));
        cpToolMenu($toolmenu);
        //TABLE COLUMNS
        $fields = array(array('title' => 'id', 'field' => 'id', 'width' => '40'), array('title' => $_LANG['AD_CREATE'], 'field' => 'pubdate', 'width' => '80', 'filter' => 15, 'fdate' => '%d/%m/%Y'), array('title' => $_LANG['TITLE'], 'field' => 'title', 'width' => '', 'link' => '?view=content&do=edit&id=%id%', 'filter' => 15), array('title' => $_LANG['AD_PARTITION'], 'field' => 'category_id', 'width' => '150', 'filter' => 1, 'prc' => 'cpCatById', 'filterlist' => cpGetList('cms_category')));
        //ACTIONS
        $actions = array(array('title' => $_LANG['AD_TO_ARTICLES_CATALOG'], 'icon' => 'arhive_off.gif', 'link' => '?view=arhive&do=arhive_off&id=%id%'), array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'link' => '?view=content&do=delete&id=%id%', 'confirm' => $_LANG['AD_DELETE_MATERIALS']));
        //Print table
        cpListTable('cms_content', $fields, $actions, 'is_arhive=1');
    }
    if ($do == 'arhive_off') {
        if (cmsCore::inRequest('id')) {
            cmsCore::c('db')->setFlag('cms_content', $id, 'is_arhive', '0');
            cmsCore::redirect('?view=arhive');
        }
    }
    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) {
                cmsCore::m('content')->deleteArticle($id, $cfg['af_delete']);
            }
        } else {
            cmsCore::m('content')->deleteArticles(cmsCore::request('item', 'array_int'), $cfg['af_delete']);
        }
        cmsCore::redirect('?view=arhive');
    }
}
Esempio n. 3
0
function files()
{
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    $do = cmsCore::getInstance()->do;
    $model = new cms_model_files();
    //============================================================================//
    // Скачивание
    if ($do == 'view') {
        $fileurl = cmsCore::request('fileurl', 'html', '');
        if (mb_strpos($fileurl, '-') === 0) {
            $fileurl = htmlspecialchars_decode(base64_decode(ltrim($fileurl, '-')));
        }
        $fileurl = cmsCore::strClear($fileurl);
        if (!$fileurl || mb_strstr($fileurl, '..') || strpos($fileurl, '.') === 0) {
            cmsCore::error404();
        }
        if (strpos($fileurl, 'http') === 0) {
            $model->increaseDownloadCount($fileurl);
            cmsCore::redirect($fileurl);
        } elseif (file_exists(PATH . $fileurl)) {
            $model->increaseDownloadCount($fileurl);
            header('Content-Disposition: attachment; filename=' . basename($fileurl) . "\n");
            header('Content-Type: application/x-force-download; name="' . $fileurl . '"' . "\n");
            header('Location:' . $fileurl);
            cmsCore::halt();
        } else {
            cmsCore::halt($_LANG['FILE_NOT_FOUND']);
        }
    }
    //============================================================================//
    if ($do == 'redirect') {
        $url = str_replace(array('--q--', ' '), array('?', '+'), cmsCore::request('url', 'str', ''));
        if (mb_strpos($url, '-') === 0) {
            $url = htmlspecialchars_decode(base64_decode(ltrim($url, '-')));
        }
        $url = cmsCore::strClear($url);
        if (!$url || mb_strstr($url, '..') || strpos($url, '.') === 0) {
            cmsCore::error404();
        }
        // кириллические домены
        $url_host = parse_url($url, PHP_URL_HOST);
        if (preg_match('/^[а-яё]+/iu', $url_host)) {
            cmsCore::loadClass('idna_convert');
            $IDN = new idna_convert();
            $host = $IDN->encode($url_host);
            $url = str_ireplace($url_host, $host, $url);
        }
        cmsCore::redirect($url);
    }
    //============================================================================//
}
Esempio n. 4
0
function applet_help()
{
    $topic = cmsCore::request('topic', 'str', '');
    $help_url = array('components' => 'http://cmsrudi.ru/docs/components', 'modules' => 'http://cmsrudi.ru/docs/modules', 'plugins' => 'http://cmsrudi.ru/docs/plugins');
    $help_url['menu'] = 'http://www.instantcms.ru/wiki/doku.php/%D0%BC%D0%B5%D0%BD%D1%8E_%D1%81%D0%B0%D0%B9%D1%82%D0%B0';
    $help_url['content'] = 'http://www.instantcms.ru/wiki/doku.php/%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82';
    $help_url['cats'] = 'http://www.instantcms.ru/wiki/doku.php/%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82';
    $help_url['users'] = 'http://www.instantcms.ru/wiki/doku.php/%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D0%B8';
    $help_url['config'] = 'http://www.instantcms.ru/wiki/doku.php/%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0_%D1%81%D0%B0%D0%B9%D1%82%D0%B0';
    if (isset($help_url[$topic])) {
        cmsCore::redirect($help_url[$topic]);
    }
    cmsCore::redirect('http://cmsrudi.ru/docs');
}
Esempio n. 5
0
function applet_help()
{
    $topic = cmsCore::request('topic', 'str', '');
    $help_url['menu'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BC%D0%B5%D0%BD%D1%8E_%D1%81%D0%B0%D0%B9%D1%82%D0%B0';
    $help_url['modules'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BC%D0%BE%D0%B4%D1%83%D0%BB%D0%B8';
    $help_url['content'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82';
    $help_url['cats'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82';
    $help_url['components'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BA%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D1%8B';
    $help_url['users'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D0%B8';
    $help_url['config'] = 'http://www.cms.vadyus.com/wiki/doku.php/%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0_%D1%81%D0%B0%D0%B9%D1%82%D0%B0';
    if (isset($help_url[$topic])) {
        cmsCore::redirect($help_url[$topic]);
    }
    cmsCore::redirect('http://www.cms.vadyus.com/wiki');
}
Esempio n. 6
0
function banners()
{
    $inCore = cmsCore::getInstance();
    $model = new cms_model_banners();
    $do = $inCore->do;
    $banner_id = cmsCore::request('id', 'int', 0);
    //======================================================================================================================//
    if ($do == 'view') {
        $banner = $model->getBanner($banner_id);
        if (!$banner || !$banner['published']) {
            cmsCore::error404();
        }
        $model->clickBanner($banner_id);
        cmsCore::redirect($banner['link']);
    }
}
Esempio n. 7
0
function applet_config()
{
    // получаем оригинальный конфиг
    $config = cmsConfig::getDefaultConfig();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/config', $adminAccess)) {
        cpAccessDenied();
    }
    cmsCore::c('page')->setTitle($_LANG['AD_SITE_SETTING']);
    cpAddPathway($_LANG['AD_SITE_SETTING'], 'index.php?view=config');
    $do = cmsCore::request('do', 'str', 'list');
    if ($do == 'save') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $newCFG = cmsCore::getArrayFromRequest(array('scheme' => array('scheme', array('http', 'https'), ''), 'sitename' => array('sitename', 'str', ''), 'title_and_sitename' => array('title_and_sitename', 'int', 0), 'title_and_page' => array('title_and_page', 'int', 0), 'hometitle' => array('hometitle', 'str', ''), 'homecom' => array('homecom', 'str', ''), 'com_without_name_in_url' => array('com_without_name_in_url', 'str', ''), 'siteoff' => array('siteoff', 'int', 0), 'only_authorized' => array('only_authorized', 'int', 0), 'debug' => array('debug', 'int', 0), 'offtext' => array('offtext', 'str', ''), 'keywords' => array('keywords', 'str', ''), 'metadesc' => array('metadesc', 'str', ''), 'seourl' => array('seourl', 'int', 0), 'lang' => array('lang', 'str', 'ru'), 'is_change_lang' => array('is_change_lang', 'int', 0), 'sitemail' => array('sitemail', 'str', ''), 'sitemail_name' => array('sitemail_name', 'str', ''), 'wmark' => array('wmark', 'str', ''), 'template' => array('template', 'str', ''), 'admin_template' => array('admin_template', 'str', ''), 'cache' => array('cache', 'int', 0), 'cache_type' => array('cache_type', array('file', 'memcached'), ''), 'memcached_host' => array('memcached_host', 'str', ''), 'memcached_port' => array('memcached_port', 'int', 0), 'combine_css_enable' => array('combine_css_enable', 'int', 0), 'combine_css' => array('combine_css', 'html', ''), 'combine_js_enable' => array('combine_js_enable', 'int', 0), 'combine_js' => array('combine_js', 'html', ''), 'splash' => array('splash', 'int', 0), 'slight' => array('slight', 'int', 0), 'show_pw' => array('show_pw', 'int', 0), 'last_item_pw' => array('last_item_pw', 'int', 0), 'index_pw' => array('index_pw', 'int', 0), 'fastcfg' => array('fastcfg', 'int', 0), 'mailer' => array('mailer', 'str', ''), 'smtpsecure' => array('smtpsecure', 'str', ''), 'smtpauth' => array('smtpauth', 'int', 0), 'smtpuser' => array('smtpuser', 'str', $config['smtpuser']), 'smtppass' => array('smtppass', 'str', $config['smtppass']), 'smtphost' => array('smtphost', 'str', ''), 'smtpport' => array('smtpport', 'int', '25'), 'timezone' => array('timezone', 'str', $config['timezone']), 'user_stats' => array('user_stats', 'int', 0), 'seo_url_count' => array('seo_url_count', 'int', 0), 'max_pagebar_links' => array('max_pagebar_links', 'int', 0), 'allow_ip' => array('allow_ip', 'str', ''), 'iframe_enable' => array('iframe_enable', 'int', 0), 'vk_enable' => array('vk_enable', 'int', 0), 'vk_id' => array('vk_id', 'str', ''), 'vk_private_key' => array('vk_private_key', 'str', '')));
        $newCFG['sitename'] = stripslashes($newCFG['sitename']);
        $newCFG['hometitle'] = stripslashes($newCFG['hometitle']);
        $newCFG['offtext'] = htmlspecialchars($newCFG['offtext'], ENT_QUOTES);
        $newCFG['db_host'] = $config['db_host'];
        $newCFG['db_base'] = $config['db_base'];
        $newCFG['db_user'] = $config['db_user'];
        $newCFG['db_pass'] = $config['db_pass'];
        $newCFG['db_prefix'] = $config['db_prefix'];
        if (cmsConfig::saveToFile($newCFG)) {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        } else {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SITE_ERROR'], 'error');
        }
        cmsCore::clearCache();
        cmsCore::redirect('index.php?view=config');
    }
    cpCheckWritable('/includes/config/config.inc.json');
    $result = cmsCore::c('db')->query("SELECT (sum(data_length)+sum(index_length))/1024/1024 as size FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" . $config['db_base'] . "'", true);
    if (!cmsCore::c('db')->error()) {
        $s = cmsCore::c('db')->fetch_assoc($result);
    } else {
        $s['size'] = 0;
    }
    cmsCore::c('page')->initTemplate('applets', 'config')->assign('config', $config)->assign('timezone_opt', cmsCore::getTimeZonesOptions($config['timezone']))->assign('admin_templates', cmsCore::getDirsList('/templates/admin'))->assign('templates', cmsCore::getDirsList('/templates'))->assign('tpl_info', cmsCore::c('page')->getTplInfo(cmsCore::c('page')->template))->assign('components_opt', cmsCore::getListItems('cms_components', $config['com_without_name_in_url'], 'title', 'ASC', 'internal=0', 'link'))->assign('homecom_opt', cmsCore::getListItems('cms_components', $config['homecom'], 'title', 'ASC', 'internal=0', 'link'))->assign('langs', cmsCore::getDirsList('/languages'))->assign('db_size', round($s['size'], 2))->display();
}
Esempio n. 8
0
    $sql = "SELECT id, filename FROM cms_user_files WHERE user_id = '{$id}' AND {$fsql}";
    $result = $inDB->query($sql);
    if ($inDB->num_rows($result)) {
        while ($file = $inDB->fetch_assoc($result)) {
            @unlink(PATH . '/upload/userfiles/' . $id . '/' . $file['filename']);
            cmsActions::removeObjectLog('add_file', $file['id']);
        }
        $inDB->query("DELETE FROM cms_user_files WHERE user_id = '{$id}' AND {$fsql}");
    }
    cmsCore::redirect('/users/' . $id . '/files.html');
}
/////////////////////////////// MULTIPLE FILES PUBLISHING /////////////////////////////////////////////////////////////////////////////////////////
if ($fdo == 'pubfilelist') {
    $files = cmsCore::request('files', 'array_int', array());
    if (!$files) {
        cmsCore::error404();
    }
    $allow = cmsCore::request('allow', 'str', 'nobody');
    if (!$inUser->id || $inUser->id != $id && !$inUser->is_admin) {
        cmsCore::error404();
    }
    $a_list = rtrim(implode(',', $files), ',');
    $fsql = '';
    if ($a_list) {
        $fsql .= "id IN ({$a_list})";
    } else {
        $fsql .= '1=0';
    }
    $inDB->query("UPDATE cms_user_files SET allow_who = '{$allow}' WHERE user_id = '{$id}' AND {$fsql}");
    cmsCore::redirect('/users/' . $id . '/files.html');
}
Esempio n. 9
0
            $mod['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
            $mod['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
        }
        cmsUser::sessionPut('mod', $mod);
        cmsCore::redirect('/photos/' . $album['id'] . '/submit_photo.html');
    }
}
////////////////// форма загрузки фотографий 2 шаг /////////////////////////////
if ($do_photo == 'submit_photo') {
    $mod = cmsUser::sessionGet('mod');
    if (!$mod) {
        cmsCore::error404();
    }
    $inPage->addPathway($_LANG['ADD_PHOTO'] . ': ' . $_LANG['STEP_2']);
    $inPage->setTitle($_LANG['ADD_PHOTO'] . ': ' . $_LANG['STEP_2']);
    if ($album['uplimit'] && !$inUser->is_admin) {
        $max_limit = true;
        $max_files = (int) $album['uplimit'] - $today_uploaded;
        $stop_photo = $today_uploaded >= (int) $album['uplimit'];
    } else {
        $max_limit = false;
        $max_files = 0;
        $stop_photo = false;
    }
    cmsPage::initTemplate('components', 'com_photos_add2')->assign('upload_url', '/components/photos/ajax/upload_photo.php')->assign('upload_complete_url', '/photos/' . $album['id'] . '/uploaded.html')->assign('sess_id', session_id())->assign('max_limit', $max_limit)->assign('album', $album)->assign('max_files', $max_files)->assign('uload_type', $mod['is_multi'] ? 'multi' : 'single')->assign('stop_photo', $stop_photo)->display('com_photos_add2.tpl');
}
///////////////// фотографии загружены /////////////////////////////////////////
if ($do_photo == 'uploaded') {
    cmsUser::sessionDel('mod');
    cmsCore::redirect('/photos/' . $album['id']);
}
Esempio n. 10
0
if ($opt == 'update_cat') {
    if (!cmsUser::checkCsrfToken()) { cmsCore::error404(); }

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

    $cat['title']     = cmsCore::request('title', 'str', 'NO_TITLE');
    $cat['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
    $cat['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
    $cat['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
    $cat['published'] = cmsCore::request('published', 'int');
    $cat['ordering']  = cmsCore::request('ordering', 'int');
    $cat['seolink']   = $model->getCatSeoLink($cat['title'], $item_id);

    cmsCore::c('db')->update('cms_forum_cats', $cat, $item_id);
    cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'info');
    cmsCore::redirect('?view=components&do=config&id='. $id .'&opt=list_cats');
}

if ($opt == 'list_cats') {
    cpAddPathway($_LANG['AD_FORUMS_CATS']);
    echo '<h3>'. $_LANG['AD_FORUMS_CATS'] .'</h3>';
    
    $fields = array(
        array( 'title' => 'id', 'field' => 'id', 'width' => '40' ),
        array( 'title' => $_LANG['TITLE'], 'field' => 'title', 'width' => '', 'link' => '?view=components&do=config&id='. $id .'&opt=edit_cat&item_id=%id%' ),
        array( 'title' => $_LANG['AD_IS_PUBLISHED'], 'field' => 'published', 'width' => '100', 'do' => 'opt', 'do_suffix' => '_cat' )
    );

    $actions = array(
        array( 'title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=components&do=config&id='. $id .'&opt=edit_cat&item_id=%id%' ),
        array( 'title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_DELETE_CATEGORY'], 'link' => '?view=components&do=config&id='. $id .'&opt=delete_cat&item_id=%id%' )
Esempio n. 11
0
function blogs() {
    $inCore = cmsCore::getInstance();
    
    cmsCore::c('blog')->owner = 'user';

    global $_LANG;

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

    //Получаем параметры
    $id 	 = cmsCore::request('id', 'int', 0);
    $post_id     = cmsCore::request('post_id', 'int', 0);
    $bloglink    = cmsCore::request('bloglink', 'str', '');
    $seolink     = cmsCore::request('seolink', 'str', '');
    $page        = cmsCore::request('page', 'int', 1);
    $cat_id      = cmsCore::request('cat_id', 'int', 0);
    $ownertype   = cmsCore::request('ownertype', 'str', '');
    $on_moderate = cmsCore::request('on_moderate', 'int', 0);

    $pagetitle = $inCore->getComponentTitle();

    cmsCore::c('page')->addPathway($pagetitle, '/blogs');
    cmsCore::c('page')->setTitle($pagetitle);
    cmsCore::c('page')->setDescription(cmsCore::m('blogs')->config['meta_desc'] ? cmsCore::m('blogs')->config['meta_desc'] : $pagetitle);
    cmsCore::c('page')->setKeywords(cmsCore::m('blogs')->config['meta_keys'] ? cmsCore::m('blogs')->config['meta_keys'] : $pagetitle);
    cmsCore::c('page')->addHeadJsLang(array('CONFIG_BLOG','DEL_BLOG','YOU_REALY_DELETE_BLOG','NEW_CAT','RENAME_CAT','YOU_REALY_DELETE_CAT','YOU_REALY_DELETE_POST','NO_PUBLISHED'));

    ///////////////////////// МОЙ БЛОГ /////////////////////////////////////////
    if ($inCore->do == 'my_blog'){
        
        if(!cmsCore::c('user')->id){ cmsCore::error404(); }

	$my_blog = cmsCore::c('blog')->getBlogByUserId(cmsCore::c('user')->id);

        if (!$my_blog) {
            cmsCore::redirect('/blogs/createblog.html');
	} else {
            cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($my_blog['seolink']));
	}

    }
    ///////////////////////// ПОСЛЕДНИЕ ПОСТЫ //////////////////////////////////
    if ($inCore->do=='view'){

	cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['RSS_BLOGS'].'" href="'.HOST.'/rss/blogs/all/feed.rss">');

	// кроме админов в списке только с доступом для всех
	if(!cmsCore::c('user')->is_admin){
            cmsCore::c('blog')->whereOnlyPublic();
	}

	// ограничиваем по рейтингу если надо
	if(cmsCore::m('blogs')->config['list_min_rating']){
            cmsCore::c('blog')->ratingGreaterThan(cmsCore::m('blogs')->config['list_min_rating']);
	}

	// всего постов
	$total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin);

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

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage']);

	// сами посты
	$posts = cmsCore::c('blog')->getPosts(cmsCore::c('user')->is_admin, cmsCore::m('blogs'));
	if(!$posts && $page > 1){ cmsCore::error404(); }

	cmsPage::initTemplate('components', 'com_blog_view_posts')->
            assign('pagetitle', $pagetitle)->
            assign('ownertype', $ownertype)->
            assign('total', $total)->
            assign('posts', $posts)->
            assign('pagination', cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], '/blogs/latest-%page%.html'))->
            assign('cfg', cmsCore::m('blogs')->config)->
            display();
    }

    ////////// СОЗДАНИЕ БЛОГА //////////////////////////////////////////////////
    if ($inCore->do=='create'){
        //Проверяем авторизацию
        if (!cmsCore::c('user')->id){ cmsUser::goToLogin();  }

        //Если у пользователя уже есть блог, то выходим
        if (cmsCore::c('blog')->getUserBlogId(cmsCore::c('user')->id)) { cmsCore::redirectBack(); }

        cmsCore::c('page')->addPathway($_LANG['PATH_CREATING_BLOG']);
        cmsCore::c('page')->setTitle($_LANG['CREATE_BLOG']);

        if (IS_BILLING){ cmsBilling::checkBalance('blogs', 'add_blog'); }

        //Показ формы создания блога
        if (!cmsCore::inRequest('goadd')){
            cmsPage::initTemplate('components', 'com_blog_create')->
                assign('is_restrictions', (!cmsCore::c('user')->is_admin && cmsCore::m('blogs')->config['min_karma']))->
                assign('cfg', cmsCore::m('blogs')->config)->
                display();
        }

        //Сам процесс создания блога
        if (cmsCore::inRequest('goadd')){
            $title     = cmsCore::request('title', 'str');
            $allow_who = cmsCore::request('allow_who', 'str', 'all');
            $ownertype = cmsCore::request('ownertype', 'str', 'single');

            //Проверяем название
            if (mb_strlen($title)<5){
                cmsCore::addSessionMessage($_LANG['BLOG_ERR_TITLE'], 'error');
                cmsCore::redirect('/blogs/createblog.html');
            }

            //Проверяем хватает ли кармы, но только если это не админ
            if (cmsCore::m('blogs')->config['min_karma'] && !cmsCore::c('user')->is_admin){
                // если персональный блог
                if ($ownertype=='single' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_private'])){
                    cmsCore::addSessionMessage($_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_PERSON_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_private'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma, 'error');
                    cmsCore::redirect('/blogs/createblog.html');
                }

                // если коллективный блог
                if ($ownertype=='multi' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_public'])){
                    cmsCore::addSessionMessage($_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_TEAM_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_public'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma, 'error');
                    cmsCore::redirect('/blogs/createblog.html');
                }
            }

            //Добавляем блог в базу
            $blog_id   = cmsCore::c('blog')->addBlog(array('user_id'=>cmsCore::c('user')->id, 'title'=>$title, 'allow_who'=>$allow_who, 'ownertype'=>$ownertype, 'forall'=>1));
            $blog_link = cmsCore::c('db')->get_field('cms_blogs', "id='{$blog_id}'", 'seolink');
            //регистрируем событие
            cmsActions::log('add_blog', array(
                'object' => $title,
                'object_url' => cmsCore::m('blogs')->getBlogURL($blog_link),
                'object_id' => $blog_id,
                'target' => '',
                'target_url' => '',
                'target_id' => 0,
                'description' => ''
            ));

            if (IS_BILLING){ cmsBilling::process('blogs', 'add_blog'); }

            cmsCore::addSessionMessage($_LANG['BLOG_CREATED_TEXT'], 'info');
            cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($blog_link));
        }
    }
    
    ////////// НАСТРОЙКИ БЛОГА /////////////////////////////////////////////////
    if ($inCore->do=='config'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::error404(); }

        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }

        //Если нет запроса на сохранение, показываем форму настроек блога
        if (!cmsCore::inRequest('goadd')){
            //Получаем список авторов блога
            $authors = cmsCore::c('blog')->getBlogAuthors($blog['id']);

            cmsPage::initTemplate('components', 'com_blog_config')->
                assign('blog', $blog)->
                assign('form_action', '/blogs/'.$blog['id'].'/editblog.html')->
                assign('authors_list', cmsUser::getAuthorsList($authors))->
                assign('users_list', cmsUser::getUsersList(false, $authors))->
                assign('is_restrictions', (!cmsCore::c('user')->is_admin && cmsCore::m('blogs')->config['min_karma']))->
                assign('cfg', cmsCore::m('blogs')->config)->
                assign('is_admin', cmsCore::c('user')->is_admin)->
                display();

            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }

        //Если пришел запрос на сохранение
        if (cmsCore::inRequest('goadd')){
            //Получаем настройки
            $title     = cmsCore::request('title', 'str');
            $allow_who = cmsCore::request('allow_who', 'str', 'all');
            $ownertype = cmsCore::request('ownertype', 'str', 'single');
            $premod    = cmsCore::request('premod', 'int', 0);
            $forall    = cmsCore::request('forall', 'int', 1);
            $showcats  = cmsCore::request('showcats', 'int', 1);
            $authors   = cmsCore::request('authorslist', 'array_int', array());
            if (cmsCore::m('blogs')->config['seo_user_access'] || cmsCore::c('user')->is_admin) {
                $page_title = cmsCore::request('pagetitle', 'str', '');
                $meta_keys  = cmsCore::request('meta_keys', 'str', '');
                $meta_desc  = cmsCore::request('meta_desc', 'str', '');
            } else {
                $page_title = $meta_keys = $meta_desc = '';
            }
            //Проверяем настройки
            if (mb_strlen($title)<5) { $title = $blog['title']; }

            //Проверяем ограничения по карме (для смены типа блога)
            if (cmsCore::m('blogs')->config['min_karma'] && !cmsCore::c('user')->is_admin){
                // если персональный блог
                if ($ownertype=='single' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_private'])){
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_PERSON_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_private'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma));

                }
                
                // если коллективный блог
                if ($ownertype=='multi' && (cmsCore::c('user')->karma < cmsCore::m('blogs')->config['min_karma_public'])){
                    cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['BLOG_YOU_NEED'].' <a href="/users/'.cmsCore::c('user')->id.'/karma.html">'.$_LANG['BLOG_KARMS'].'</a> '.$_LANG['FOR_CREATE_TEAM_BLOG'].' &mdash; '.cmsCore::m('blogs')->config['min_karma_public'].', '.$_LANG['BLOG_HEAVING'].' &mdash; '.cmsCore::c('user')->karma));
                }
            }

            if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

            //сохраняем авторов
            cmsCore::c('blog')->updateBlogAuthors($blog['id'], $authors);

            //сохраняем настройки блога
            $blog['seolink_new'] = cmsCore::c('blog')->updateBlog($blog['id'], array(
                'title'     => $title,
                'pagetitle' => $page_title,
                'meta_keys' => $meta_keys,
                'meta_desc' => $meta_desc,
                'allow_who' => $allow_who,
                'showcats'  => $showcats,
                'ownertype' => $ownertype,
                'premod'    => $premod,
                'forall'    => $forall
            ), cmsCore::m('blogs')->config['update_seo_link_blog']);

            $blog['seolink'] = $blog['seolink_new'] ? $blog['seolink_new'] : $blog['seolink'];

            if(stripslashes($title) != $blog['title']){
                // обновляем записи постов
                cmsActions::updateLog('add_post', array('target' => $title, 'target_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink'])), 0, $blog['id']);
                // обновляем запись добавления блога
                cmsActions::updateLog('add_blog', array('object' => $title, 'object_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink'])), $blog['id']);
            }

            cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'])));
        }
    }
    
    ////////// СПИСОК БЛОГОВ ///////////////////////////////////////////////////
    if ($inCore->do=='view_blogs'){
        // rss в адресной строке
        cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'.$_LANG['BLOGS'].'" href="'.HOST.'/rss/blogs/all/feed.rss">');

        // тип блога
        if($ownertype && $ownertype != 'all'){
            cmsCore::c('blog')->whereOwnerTypeIs($ownertype);
        }

        // всего блогов
        $total = cmsCore::c('blog')->getBlogsCount();

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

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage_blog']);

        //Получаем список блогов
        $blogs = cmsCore::c('blog')->getBlogs(cmsCore::m('blogs'));
        if(!$blogs && $page > 1){ cmsCore::error404(); }

        //Генерируем панель со страницами и устанавливаем заголовки страниц и глубиномера
        switch ($ownertype){
            case 'all':
                cmsCore::c('page')->setTitle($_LANG['ALL_BLOGS']);
                cmsCore::c('page')->setDescription($_LANG['BLOGS'] .' - '. $_LANG['ALL_BLOGS']);
                cmsCore::c('page')->addPathway($_LANG['ALL_BLOGS']);
                $link = '/blogs/all-%page%.html';
            break;
        
            case 'single':
                cmsCore::c('page')->setTitle($_LANG['PERSONALS']);
                cmsCore::c('page')->setDescription($_LANG['PERSONALS'] .' '. $_LANG['BLOGS']);
                cmsCore::c('page')->addPathway($_LANG['PERSONALS']);
                $link = '/blogs/single-%page%.html';
            break;
        
            case 'multi':
                cmsCore::c('page')->setTitle($_LANG['COLLECTIVES']);
                cmsCore::c('page')->setDescription($_LANG['COLLECTIVES'] .' '. $_LANG['BLOGS']);
                cmsCore::c('page')->addPathway($_LANG['COLLECTIVES']);
                $link = '/blogs/multi-%page%.html';
            break;
        }
        
        if ($blogs) {
            foreach ($blogs as $b) {
                $k[] = $b['title'];
            }
            
            cmsCore::c('page')->setKeywords(implode(', ', $k));
        }

        cmsPage::initTemplate('components', 'com_blog_view_all')->
            assign('cfg', cmsCore::m('blogs')->config)->
            assign('total', $total)->
            assign('ownertype', $ownertype)->
            assign('blogs', $blogs)->
            assign('pagination', cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage_blog'], $link))->
            display();
    }
    
    ////////// ПРОСМОТР БЛОГА //////////////////////////////////////////////////
    if ($inCore->do == 'blog'){
        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($bloglink);

        // Совместимость со старыми ссылками на клубные блоги
        // Пробуем клубный блог получить по ссылке
        if (!$blog) {
            $blog_user_id = cmsCore::c('db')->get_field('cms_blogs', "seolink = '$bloglink' AND owner = 'club'", 'user_id');
            if($blog_user_id){
                cmsCore::redirect('/clubs/'.$blog_user_id.'_blog', '301');
            }
        }

        if (!$blog) { cmsCore::error404(); }

        // Права доступа
        $myblog = (cmsCore::c('user')->id && cmsCore::c('user')->id == $blog['user_id']); // автор блога
        $is_writer = cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id); // может ли пользователь писать в блог

        cmsCore::c('page')->addPathway($blog['title'], cmsCore::m('blogs')->getBlogURL($blog['seolink']));
        // rss в адресной строке
        cmsCore::c('page')->addHead('<link rel="alternate" type="application/rss+xml" title="'.htmlspecialchars(strip_tags($blog['title'])).'" href="'.HOST.'/rss/blogs/'.$blog['id'].'/feed.rss">');
        if($myblog || cmsCore::c('user')->is_admin){
            cmsCore::c('page')->addHeadJS('components/blogs/js/blog.js');
        }

        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'].'<br>'.$_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blogs');
        }

        // Если показываем посты на модерации, если запрашиваем их
        if($on_moderate){
            if(!cmsCore::c('user')->is_admin && !($myblog && $blog['ownertype'] == 'multi' && $blog['premod'])){
                cmsCore::error404();
            }

            cmsCore::c('blog')->whereNotPublished();

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

            $blog['title'] .= ' - '.$_LANG['POSTS_ON_MODERATE'];
        }

        //Получаем html-код ссылки на автора с иконкой его пола
        $blog['author'] = cmsUser::getGenderLink($blog['user_id']);

        // посты данного блога
        cmsCore::c('blog')->whereBlogIs($blog['id']);

        // кроме админов автора в списке только с доступом для всех
        if(!cmsCore::c('user')->is_admin && !$myblog && !cmsCore::c('user')->isFriend($blog['user_id'])){
            cmsCore::c('blog')->whereOnlyPublic();
        }

        // если пришла категория
        if($cat_id){
            $all_total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin || $myblog);
            cmsCore::c('blog')->whereCatIs($cat_id);
        }

        // всего постов
        $total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin || $myblog);

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

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage']);

        // сами посты
        $posts = cmsCore::c('blog')->getPosts((cmsCore::c('user')->is_admin || $myblog), cmsCore::m('blogs'));
        if(!$posts && $page > 1){ cmsCore::error404(); }

        //Если нужно, получаем список рубрик (категорий) этого блога
        $blogcats = $blog['showcats'] ? cmsCore::c('blog')->getBlogCats($blog['id']) : false;

        //Считаем количество постов, ожидающих модерации
        $on_moderate = (cmsCore::c('user')->is_admin || $myblog) && !$on_moderate ? cmsCore::c('blog')->getModerationCount($blog['id']) : false;

        // админлинки
        $blog['moderate_link'] = cmsCore::m('blogs')->getBlogURL($blog['seolink']).'/moderate.html';
        $blog['blog_link']     = cmsCore::m('blogs')->getBlogURL($blog['seolink']);
        $blog['add_post_link'] = '/blogs/'.$blog['id'].'/newpost'.($cat_id ? $cat_id : '').'.html';

        //Генерируем панель со страницами
        if ($cat_id){
            $pagination = cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], $blog['blog_link'].'/page-%page%/cat-'.$cat_id);
        } else {
            $pagination = cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], $blog['blog_link'].'/page-%page%');
        }
        
        // SEO
        cmsCore::c('page')->setTitle($blog['pagetitle'] ? $blog['pagetitle'] : $blog['title']);
        cmsCore::c('page')->setDescription($blog['meta_desc'] ? $blog['meta_desc'] : $blog['title']);
        // keywords
        if ($blog['meta_keys']) {
            $meta_keys = $blog['meta_keys'];
        } else if ($posts) {
            foreach ($posts as $p) {
                $k[] = $p['title'];
            }
            $meta_keys = implode(', ', $k);
        } else {
            $meta_keys = $blog['title'];
        }
        cmsCore::c('page')->setKeywords($meta_keys);

        cmsPage::initTemplate('components', 'com_blog_view')->
            assign('myblog', $myblog)->
            assign('is_config', true)->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('is_writer', $is_writer)->
            assign('on_moderate', $on_moderate)->
            assign('cat_id', $cat_id)->
            assign('blogcats', $blogcats)->
            assign('total', $total)->
            assign('all_total', (isset($all_total) ? $all_total : 0))->
            assign('blog', $blog)->assign('posts', $posts)->
            assign('pagination', $pagination)->
            display();
    }

    ////////// НОВЫЙ ПОСТ / РЕДАКТИРОВАНИЕ ПОСТА ///////////////////////////////
    if ($inCore->do == 'newpost' || $inCore->do == 'editpost'){
        if (!cmsCore::c('user')->id){ cmsUser::goToLogin();  }

        // для редактирования сначала получаем пост
        if($inCore->do == 'editpost'){
            $post = cmsCore::c('blog')->getPost($post_id);
            
            if (!$post){ cmsCore::error404(); }
            
            $id = $post['blog_id'];
            
            $post['tags'] = cmsTagLine('blogpost', $post['id'], false);
        }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::error404(); }

        //Если доступа нет, возвращаемся и выводим сообщение об ошибке
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'].'<br>'.$_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blogs');
        }

        // Права доступа
        $myblog = (cmsCore::c('user')->id && cmsCore::c('user')->id == $blog['user_id']); // автор блога
        $is_writer = cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id); // может ли пользователь писать в блог
            // если не его блог, пользователь не писатель и не админ, вне зависимости от авторства показываем 404
        if (!$myblog && !$is_writer && !cmsCore::c('user')->is_admin ) { cmsCore::error404(); }
        // проверяем является ли пользователь автором, если редактируем пост
        if (($inCore->do == 'editpost') && !cmsCore::c('user')->is_admin && $post['user_id'] != cmsCore::c('user')->id) { cmsCore::error404(); }

        //Если еще не было запроса на сохранение
        if (!cmsCore::inRequest('goadd')){
            cmsCore::c('page')->addPathway($blog['title'], cmsCore::m('blogs')->getBlogURL($blog['seolink']));

            //для нового поста
            if ($inCore->do == 'newpost'){
                if (IS_BILLING){ cmsBilling::checkBalance('blogs', 'add_post'); }

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

                $post = cmsUser::sessionGet('mod');
                if ($post){
                    cmsUser::sessionDel('mod');
                } else {
                    $post['cat_id'] = $cat_id;
                    $post['comments'] = 1;

                }
            }

            //для редактирования поста
            if ($inCore->do=='editpost'){
                cmsCore::c('page')->addPathway($post['title'], cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']));
                cmsCore::c('page')->addPathway($_LANG['EDIT_POST']);
                cmsCore::c('page')->setTitle($_LANG['EDIT_POST']);
            }

            cmsCore::c('page')->initAutocomplete();
            $autocomplete_js = cmsCore::c('page')->getAutocompleteJS('tagsearch', 'tags');

            //получаем рубрики блога
            $cat_list = cmsCore::getListItems('cms_blog_cats', $post['cat_id'], 'id', 'ASC', "blog_id = '{$blog['id']}'");

            //получаем код панелей bbcode и смайлов
            $bb_toolbar = cmsPage::getBBCodeToolbar('message',cmsCore::m('blogs')->config['img_on'], 'blogs', 'blog_post', $post_id);
            $smilies    = cmsPage::getSmilesPanel('message');

            $inCore->initAutoGrowText('#message');

            //показываем форму
            cmsPage::initTemplate('components', 'com_blog_edit_post')->
                assign('blog', $blog)->
                assign('pagetitle', ($inCore->do=='editpost' ? $_LANG['EDIT_POST'] : $_LANG['NEW_POST']))->
                assign('mod', $post)->
                assign('cat_list', $cat_list)->
                assign('bb_toolbar', $bb_toolbar)->
                assign('smilies', $smilies)->
                assign('is_admin', cmsCore::c('user')->is_admin)->
                assign('cfg', cmsCore::m('blogs')->config)->
                assign('myblog', $myblog)->
                assign('user_can_iscomments', cmsUser::isUserCan('comments/iscomments'))->
                assign('autocomplete_js', $autocomplete_js)->
                display();
        }

        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')) {
            $errors = false;

            //Получаем параметры
            $mod['title']    = cmsCore::request('title', 'str');
            $mod['content']  = cmsCore::request('content', 'html');
            $mod['feel']     = cmsCore::request('feel', 'str', '');
            $mod['music']    = cmsCore::request('music', 'str', '');
            $mod['cat_id']   = cmsCore::request('cat_id', 'int');
            $mod['allow_who']= cmsCore::request('allow_who', 'str', $blog['allow_who']);
            $mod['tags']     = cmsCore::request('tags', 'str', '');
            $mod['comments'] = cmsCore::request('comments', 'int', 1);
            
            if (cmsCore::m('blogs')->config['seo_user_access'] || cmsCore::c('user')->is_admin) {
                $mod['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
                $mod['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
                $mod['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
            }
            
            $mod['published']= ($myblog || !$blog['premod']) ? 1 : 0;
            $mod['blog_id']  = $blog['id'];

            //Проверяем их
            if (mb_strlen($mod['title'])<2) {  cmsCore::addSessionMessage($_LANG['POST_ERR_TITLE'], 'error'); $errors = true; }
            if (mb_strlen($mod['content'])<5) { cmsCore::addSessionMessage($_LANG['POST_ERR_TEXT'], 'error'); $errors = true; }

            // Если есть ошибки, возвращаемся назад
            if($errors){
                cmsUser::sessionPut('mod', $mod);
                cmsCore::redirectBack();
            }

            //Если нет ошибок
            //добавляем новый пост...
            if ($inCore->do=='newpost'){

                if (IS_BILLING){ cmsBilling::process('blogs', 'add_post'); }

                $mod['pubdate'] = date( 'Y-m-d H:i:s');
                $mod['user_id'] = cmsCore::c('user')->id;

                // добавляем пост, получая его id и seolink
                $added = cmsCore::c('blog')->addPost($mod);
    $mod = array_merge($mod, $added);

                if ($mod['published']) {
                    $mod['seolink'] = cmsCore::m('blogs')->getPostURL($blog['seolink'], $mod['seolink']);
                    
                    if ($blog['allow_who'] != 'nobody' && $mod['allow_who'] != 'nobody') {
                        cmsCore::callEvent('ADD_POST_DONE', $mod);

                        cmsActions::log('add_post', array(
                                'object' => $mod['title'],
                                'object_url' => $mod['seolink'],
                                'object_id' => $mod['id'],
                                'target' => $blog['title'],
                                'target_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink']),
                                'target_id' => $blog['id'],
                                'description' => '',
                                'is_friends_only' => (int)($blog['allow_who'] == 'friends' || $mod['allow_who'] == 'friends')
                        ));
                    }

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

                    cmsCore::redirect($mod['seolink']);
                }

                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink(cmsCore::c('user')->login, cmsCore::c('user')->nickname), $_LANG['MSG_POST_SUBMIT']);
                    $message = str_replace('%post%', '<a href="'.cmsCore::m('blogs')->getPostURL($blog['seolink'], $added['seolink']).'">'.$mod['title'].'</a>', $message);
                    $message = str_replace('%blog%', '<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>', $message);

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

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

                    cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($blog['seolink']));
                }
            }

            //...или сохраняем пост после редактирования
            if ($inCore->do=='editpost') {
                if (cmsCore::m('blogs')->config['update_date']){
                    $mod['pubdate'] = date( 'Y-m-d H:i:s');
                }

                $mod['edit_times'] = (int)$post['edit_times']+1;

                $new_post_seolink = cmsCore::c('blog')->updatePost($post['id'], $mod, cmsCore::m('blogs')->config['update_seo_link']);

                $post['seolink'] = is_string($new_post_seolink) ? $new_post_seolink : $post['seolink'];

                cmsActions::updateLog(
                    'add_post',
                    array(
                        'object' => $mod['title'],
                        'pubdate' => cmsCore::m('blogs')->config['update_date'] ? $mod['pubdate'] : $post['pubdate'],
                        'object_url' => cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink'])
                    ),
                    $post['id']
                );

                if (!$mod['published']) {
                    $message = str_replace('%user%', cmsUser::getProfileLink(cmsCore::c('user')->login, cmsCore::c('user')->nickname), $_LANG['MSG_POST_UPDATE']);
                    $message = str_replace('%post%', '<a href="'.cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']).'">'.$mod['title'].'</a>', $message);
                    $message = str_replace('%blog%', '<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>', $message);

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

                    cmsCore::addSessionMessage($_LANG['POST_PREMODER_TEXT'], 'info');
                } else {
                    cmsCore::addSessionMessage($_LANG['POST_UPDATED'], 'success');
                }

                cmsCore::redirect(cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']));
            }
        }
    }
    
    ////////// НОВАЯ РУБРИКА / РЕДАКТИРОВАНИЕ РУБРИКИ //////////////////////////
    if ($inCore->do == 'newcat' || $inCore->do == 'editcat'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        $cat = array();

        // Для редактирования сначала получаем рубрику
        if ($inCore->do == 'editcat'){
            $cat = cmsCore::c('blog')->getBlogCategory($cat_id);
            if (!$cat) { cmsCore::halt(); }
            $id = $cat['blog_id'];
        }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::halt(); }

        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }

        //Если нет запроса на сохранение
        if (!cmsCore::inRequest('goadd')){
            cmsPage::initTemplate('components', 'com_blog_edit_cat')->
                assign('mod', $cat)->
                assign('form_action', ($inCore->do=='newcat' ? '/blogs/'.$blog['id'].'/newcat.html' : '/blogs/editcat'.$cat['id'].'.html'))->
                display();

            cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));
        }

        //Если есть запрос на сохранение
        if (cmsCore::inRequest('goadd')){
            $new_cat['title']       = cmsCore::request('title', 'str', '');
            $new_cat['description'] = cmsCore::request('description', 'str', '');
            $new_cat['blog_id']     = $blog['id'];
            if (mb_strlen($new_cat['title'])<3) { cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CAT_ERR_TITLE'])); }

            if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

            //новая рубрика
            if ($inCore->do=='newcat'){
                    $cat['id'] = cmsCore::c('blog')->addBlogCategory($new_cat);
                    cmsCore::addSessionMessage($_LANG['CAT_IS_ADDED'], 'success');
            }
            //редактирование рубрики
            if ($inCore->do=='editcat'){
                    cmsCore::c('blog')->updateBlogCategory($cat['id'], $new_cat);
                    cmsCore::addSessionMessage($_LANG['CAT_IS_UPDATED'], 'success');
            }

            cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'], 1, $cat['id'])));
        }

    }
    
    ///////////////////////// УДАЛЕНИЕ РУБРИКИ /////////////////////////////////
    if ($inCore->do == 'delcat'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        $cat = cmsCore::c('blog')->getBlogCategory($cat_id);
        if (!$cat) { cmsCore::halt(); }

        $blog = cmsCore::c('blog')->getBlog($cat['blog_id']);
        if (!$blog) { cmsCore::halt(); }

        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin) { cmsCore::halt(); }

        if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

        cmsCore::c('blog')->deleteBlogCategory($cat['id']);

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

        cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'])));
    }
    
    ////////////////////////// ПРОСМОТР ПОСТА //////////////////////////////////
    if($inCore->do == 'post'){
        $post = cmsCore::c('blog')->getPost($seolink);
        if (!$post){ cmsCore::error404(); }

        $blog = cmsCore::c('blog')->getBlog($post['blog_id']);
        // Совместимость со старыми ссылками на клубные посты блога
        if (!$blog) {
            $blog_user_id = cmsCore::c('db')->get_field('cms_blogs', "id = '{$post['blog_id']}' AND owner = 'club'", 'user_id');
            if($blog_user_id){
                cmsCore::redirect('/clubs/'.$blog_user_id.'_'.$post['seolink'].'.html', '301');
            }
        }

        if (!$blog) { cmsCore::error404(); }

        // Проверяем сеолинк блога и делаем редирект если он изменился
        if($bloglink != $blog['seolink']) {
            cmsCore::redirect(cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']), '301');
        }

        // право просмотра блога
        if (!cmsUser::checkUserContentAccess($blog['allow_who'], $blog['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_BLOG'].'<br>'.$_LANG['CLOSED_BLOG_TEXT'], 'error');
            cmsCore::redirect('/blogs');
        }

        // право просмотра самого поста
        if (!cmsUser::checkUserContentAccess($post['allow_who'], $post['user_id'])){
            cmsCore::addSessionMessage($_LANG['CLOSED_POST'].'<br>'.$_LANG['CLOSED_POST_TEXT'], 'error');
            cmsCore::redirect(cmsCore::m('blogs')->getBlogURL($blog['seolink']));
        }

        if (cmsCore::c('user')->id) {
            cmsCore::c('page')->addHeadJS('components/blogs/js/blog.js');
        }
        cmsCore::c('page')->addPathway($blog['title'], cmsCore::m('blogs')->getBlogURL($blog['seolink']));
        cmsCore::c('page')->addPathway($post['title']);
        
        cmsCore::c('page')->setTitle($post['pagetitle'] ? $post['pagetitle'] : $post['title']);
        cmsCore::c('page')->setDescription($post['meta_desc'] ? $post['meta_desc'] : crop($post['content_html']));
        cmsCore::c('page')->setKeywords($post['meta_keys'] ? $post['meta_keys'] : $post['title']);

        if ($post['cat_id']){
            $cat = cmsCore::c('blog')->getBlogCategory($post['cat_id']);
        }

        $post['tags'] = cmsTagBar('blogpost', $post['id']);

        $is_author = (cmsCore::c('user')->id && cmsCore::c('user')->id == $post['user_id']);
        
        // увеличиваем кол-во просмотров
        if (!$is_author) {
            cmsCore::c('db')->setFlag('cms_blog_posts', $post['id'], 'hits', $post['hits']+1);
        }

        cmsPage::initTemplate('components', 'com_blog_view_post')->
            assign('post', $post)->
            assign('blog', $blog)->assign('cat', $cat)->
            assign('is_author', $is_author)->
            assign('is_writer', cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id))->
            assign('myblog', (cmsCore::c('user')->id && cmsCore::c('user')->id == $blog['user_id']))->
            assign('is_admin', cmsCore::c('user')->is_admin)->
            assign('karma_form', cmsKarmaForm('blogpost', $post['id'], $post['rating'], $is_author))->
            assign('navigation', cmsCore::c('blog')->getPostNavigation($post['id'], $blog['id'], cmsCore::m('blogs'), $blog['seolink']))->
            display();

        if ($inCore->isComponentEnable('comments') && $post['comments']) {
            cmsCore::includeComments();
            comments('blog', $post['id'], array(), $is_author);
        }
    }

    ///////////////////////// УДАЛЕНИЕ ПОСТА ///////////////////////////////////
    if ($inCore->do == 'delpost'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }
        
        $post = cmsCore::c('blog')->getPost($post_id);
        if (!$post){ cmsCore::halt(); }

        $blog = cmsCore::c('blog')->getBlog($post['blog_id']);
        if (!$blog) { cmsCore::halt(); }

        $myblog = (cmsCore::c('user')->id == $blog['user_id']); // автор блога
        $is_writer = cmsCore::c('blog')->isUserBlogWriter($blog, cmsCore::c('user')->id);
        
        // если не его блог, пользователь не писатель и не админ
        if (!$myblog && !$is_writer && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }
        
        // проверяем является ли пользователь автором
        if (!cmsCore::c('user')->is_admin && !$myblog && $post['user_id'] != cmsCore::c('user')->id) { cmsCore::halt(); }

        if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

        cmsCore::c('blog')->deletePost($post['id']);

        if (cmsCore::c('user')->id != $post['user_id']){
            cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'].' <b>&laquo;'.$post['title'].'&raquo;</b> '.$_LANG['WAS_DELETED_FROM_BLOG'].' <b>&laquo;<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>&raquo;</b>');
        }

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

        cmsCore::jsonOutput(array('error' => false, 'redirect'  => cmsCore::m('blogs')->getBlogURL($blog['seolink'])));
    }
    
    ///////////////////////// ПУБЛИКАЦИЯ ПОСТА /////////////////////////////////
    if ($inCore->do == 'publishpost'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        $post = cmsCore::c('blog')->getPost($post_id);
        if (!$post){ cmsCore::halt(); }

        $blog = cmsCore::c('blog')->getBlog($post['blog_id']);
        if (!$blog) { cmsCore::halt(); }

        // публикуют авторы блога и админы
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin) { cmsCore::halt(); }

        cmsCore::c('blog')->publishPost($post_id);

        $post['seolink'] = cmsCore::m('blogs')->getPostURL($blog['seolink'], $post['seolink']);

        if ($blog['allow_who'] == 'all' && $post['allow_who'] == 'all') { cmsCore::callEvent('ADD_POST_DONE', $post); }

        if ($blog['allow_who'] != 'nobody' && $post['allow_who'] != 'nobody'){
            cmsActions::log('add_post', array(
                    'object' => $post['title'],
                    'user_id' => $post['user_id'],
                    'object_url' => $post['seolink'],
                    'object_id' => $post['id'],
                    'target' => $blog['title'],
                    'target_url' => cmsCore::m('blogs')->getBlogURL($blog['seolink']),
                    'target_id' => $blog['id'],
                    'description' => '',
                    'is_friends_only' => (int)($blog['allow_who'] == 'friends' || $post['allow_who'] == 'friends')
            ));
        }

        cmsUser::sendMessage(USER_UPDATER, $post['user_id'], $_LANG['YOUR_POST'].' <b>&laquo;<a href="'.$post['seolink'].'">'.$post['title'].'</a>&raquo;</b> '.$_LANG['PUBLISHED_IN_BLOG'].' <b>&laquo;<a href="'.cmsCore::m('blogs')->getBlogURL($blog['seolink']).'">'.$blog['title'].'</a>&raquo;</b>');

        cmsCore::halt('ok');
    }

    ///////////////////////// УДАЛЕНИЕ БЛОГА ///////////////////////////////////
    if ($inCore->do == 'delblog'){
        if(!cmsCore::c('user')->id) { cmsCore::error404(); }

        if(!cmsCore::isAjax()) { cmsCore::error404(); }

        // получаем блог
        $blog = cmsCore::c('blog')->getBlog($id);
        if (!$blog) { cmsCore::error404(); }

        //Проверяем является пользователь хозяином блога или админом
        if ($blog['user_id'] != cmsCore::c('user')->id && !cmsCore::c('user')->is_admin ) { cmsCore::halt(); }

        if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

        cmsCore::c('blog')->deleteBlog($blog['id']);

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

        cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/blogs'));
    }

    ////////// VIEW POPULAR POSTS //////////////////////////////////////////////
    if ($inCore->do=='best'){
        cmsCore::c('page')->setTitle($_LANG['POPULAR_IN_BLOGS']);
        cmsCore::c('page')->addPathway($_LANG['POPULAR_IN_BLOGS']);
        cmsCore::c('page')->setDescription($_LANG['POPULAR_IN_BLOGS']);

        // кроме админов в списке только с доступом для всех
        if(!cmsCore::c('user')->is_admin){
            cmsCore::c('blog')->whereOnlyPublic();
        }

        // ограничиваем по рейтингу если надо
        if(cmsCore::m('blogs')->config['list_min_rating']){
            cmsCore::c('blog')->ratingGreaterThan(cmsCore::m('blogs')->config['list_min_rating']);
        }

        // всего постов
        $total = cmsCore::c('blog')->getPostsCount(cmsCore::c('user')->is_admin);

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

        cmsCore::c('db')->limitPage($page, cmsCore::m('blogs')->config['perpage']);

        // сами посты
        $posts = cmsCore::c('blog')->getPosts(cmsCore::c('user')->is_admin, cmsCore::m('blogs'));
        if(!$posts && $page > 1){ cmsCore::error404(); }

        cmsPage::initTemplate('components', 'com_blog_view_posts')->
            assign('pagetitle', $_LANG['POPULAR_IN_BLOGS'])->
            assign('total', $total)->
            assign('ownertype', $ownertype)->
            assign('posts', $posts)->
            assign('pagination', cmsPage::getPagebar($total, $page, cmsCore::m('blogs')->config['perpage'], '/blogs/popular-%page%.html'))->
            assign('cfg', cmsCore::m('blogs')->config)->
            display();
    }

}
Esempio n. 12
0
function applet_plugins()
{
    global $_LANG;
    $inCore = cmsCore::getInstance();
    $GLOBALS['cp_page_title'] = $_LANG['AD_PLUGINS'];
    cpAddPathway($_LANG['AD_PLUGINS'], 'index.php?view=plugins');
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) {
        cpAccessDenied();
    }
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    // ===================================================================================== //
    if ($do == 'hide') {
        dbHide('cms_plugins', $id);
        echo '1';
        exit;
    }
    // ===================================================================================== //
    if ($do == 'show') {
        dbShow('cms_plugins', $id);
        echo '1';
        exit;
    }
    // ===================================================================================== //
    if ($do == 'list') {
        $toolmenu = array();
        $toolmenu[1]['icon'] = 'install.gif';
        $toolmenu[1]['title'] = $_LANG['AD_INSTALL_PLUGINS'];
        $toolmenu[1]['link'] = '?view=install&do=plugin';
        cpToolMenu($toolmenu);
        $plugin_id = cmsCore::request('installed', 'str', '');
        if ($plugin_id) {
            $task = cmsCore::request('task', 'str', 'install');
            if ($task == 'install' || $task == 'upgrade') {
                $plugin = $inCore->loadPlugin($plugin_id);
                $task_str = $task == 'install' ? $_LANG['AD_IS_INSTALL'] : $_LANG['AD_IS_UPDATE'];
                echo '<div style="color:green;margin-top:12px;margin-bottom:5px;">' . $_LANG['AD_PLUGIN'] . ' <strong>"' . $plugin->info['title'] . '"</strong> ' . $task_str . '. ' . $_LANG['AD_ENABLE_PLUGIN'] . '.</div>';
            }
            if ($task == 'remove') {
                echo '<div style="color:green;margin-top:12px;margin-bottom:5px;">' . $_LANG['AD_REMOVE_PLUGIN_OK'] . '.</div>';
            }
        }
        $fields = array();
        $fields[0]['title'] = 'id';
        $fields[0]['field'] = 'id';
        $fields[0]['width'] = '20';
        $fields[1]['title'] = $_LANG['TITLE'];
        $fields[1]['field'] = 'title';
        $fields[1]['width'] = '250';
        $fields[2]['title'] = $_LANG['DESCRIPTION'];
        $fields[2]['field'] = 'description';
        $fields[2]['width'] = '';
        $fields[3]['title'] = $_LANG['AD_AUTHOR'];
        $fields[3]['field'] = 'author';
        $fields[3]['width'] = '160';
        $fields[4]['title'] = $_LANG['AD_VERSION'];
        $fields[4]['field'] = 'version';
        $fields[4]['width'] = '50';
        $fields[5]['title'] = $_LANG['AD_FOLDER'];
        $fields[5]['field'] = 'plugin';
        $fields[5]['width'] = '100';
        $fields[6]['title'] = $_LANG['AD_ENABLE'];
        $fields[6]['field'] = 'published';
        $fields[6]['width'] = '60';
        $actions = array();
        $actions[0]['title'] = $_LANG['AD_CONFIG'];
        $actions[0]['icon'] = 'config.gif';
        $actions[0]['link'] = '?view=plugins&do=config&id=%id%';
        $actions[1]['title'] = $_LANG['DELETE'];
        $actions[1]['icon'] = 'delete.gif';
        $actions[1]['confirm'] = $_LANG['AD_REMOVE_PLUGIN_FROM'];
        $actions[1]['link'] = '?view=install&do=remove_plugin&id=%id%';
        cpListTable('cms_plugins', $fields, $actions);
    }
    // ===================================================================================== //
    if ($do == 'save_config') {
        if (!cmsCore::validateForm()) {
            cmsCore::error404();
        }
        $plugin_name = cmsCore::request('plugin', 'str', 0);
        $config = cmsCore::request('config', 'array_str');
        if (!$config || !$plugin_name) {
            cmsCore::redirectBack();
        }
        $inCore->savePluginConfig($plugin_name, $config);
        cmsUser::clearCsrfToken();
        cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        cmsCore::redirect('index.php?view=plugins');
    }
    // ===================================================================================== //
    if ($do == 'config') {
        $plugin_name = $inCore->getPluginById($id);
        if (!$plugin_name) {
            cmsCore::error404();
        }
        $plugin = $inCore->loadPlugin($plugin_name);
        $config = $inCore->loadPluginConfig($plugin_name);
        $GLOBALS['cp_page_title'] = $plugin->info['title'];
        cpAddPathway($plugin->info['title'], 'index.php?view=plugins&do=config&id=' . $id);
        echo '<h3>' . $plugin->info['title'] . '</h3>';
        if (!$config) {
            echo '<p>' . $_LANG['AD_PLUGIN_DISABLE'] . '.</p>';
            echo '<p><a href="javascript:window.history.go(-1);">' . $_LANG['BACK'] . '</a></p>';
            return;
        }
        echo '<form action="index.php?view=plugins&do=save_config&plugin=' . $plugin_name . '" method="POST">';
        echo '<input type="hidden" name="csrf_token" value="' . cmsUser::getCsrfToken() . '" />';
        echo '<table class="proptable" width="605" cellpadding="8" cellspacing="0" border="0">';
        foreach ($config as $field => $value) {
            echo '<tr>';
            echo '<td width="150"><strong>' . (isset($_LANG[mb_strtoupper($field)]) ? $_LANG[mb_strtoupper($field)] : $field) . ':</strong></td>';
            echo '<td><input type="text" style="width:90%" name="config[' . $field . ']" value="' . htmlspecialchars($value) . '" /></td>';
            echo '</tr>';
        }
        echo '</table>';
        echo '<div style="margin-top:6px;">';
        echo '<input type="submit" name="save" value="' . $_LANG['SAVE'] . '" /> ';
        echo '<input type="button" name="back" value="' . $_LANG['CANCEL'] . '" onclick="window.history.go(-1)" />';
        echo '</div>';
        echo '</form>';
    }
    // ===================================================================================== //
}
Esempio n. 13
0
        $perpage = 21;
        $pagination = cmsPage::getPagebar($total, $page, $perpage, '/users/%user%/photos/%album%%id%-%page%.html', array('user' => $usr['login'], 'album' => $album_type, 'id' => $album_id));
        $page_photos = array();
        $start = $perpage * ($page - 1);
        for ($p = $start; $p < $start + $perpage; $p++) {
            if ($photos[$p]) {
                $page_photos[] = $photos[$p];
            }
        }
        $photos = $page_photos;
        unset($page_photos);
    }
    //Отдаем в шаблон
    cmsPage::initTemplate('components', 'com_users_photos')->assign('page_title', $album['title'])->assign('album_type', $album_type)->assign('album', $album)->assign('photos', $photos)->assign('user_id', $usr['id'])->assign('usr', $usr)->assign('my_profile', $my_profile)->assign('is_admin', $inUser->is_admin)->assign('pagebar', $pagination)->display('com_users_photos.tpl');
}
//============================================================================//
//============================ Удалить фотоальбом ============================//
//============================================================================//
if ($pdo == 'delalbum') {
    $album_id = cmsCore::request('album_id', 'int', '0');
    $album = $model->getPhotoAlbum('private', $album_id);
    if (!$album) {
        cmsCore::error404();
    }
    if (!$inUser->is_admin && $album['user_id'] != $inUser->id) {
        cmsCore::error404();
    }
    $model->deletePhotoAlbum($id, $album_id);
    $user = cmsUser::getShortUserData($album['user_id']);
    cmsCore::redirect(cmsUser::getProfileURL($user['login']));
}
Esempio n. 14
0
    $model->updateClub($item_id, $new_club);

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

    if (empty($_SESSION['editlist'])) {
        cmsCore::redirect('index.php?view=components&do=config&id='. $id .'&opt=list');
    } else {
        cmsCore::redirect('index.php?view=components&do=config&id='. $id .'&opt=edit');
    }
}

if ($opt == 'delete') {
    $model->deleteClub(cmsCore::request('item_id', 'int', 0));
    cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
    cmsCore::redirect('index.php?view=components&do=config&id='. $id .'&opt=list');
}

cpToolMenu($toolmenu);

if ($opt == 'list') {
    $fields = array(
        array( 'title' => 'id', 'field' => 'id', 'width' => '40'),
        array( 'title' => $_LANG['DATE'], 'field' => 'pubdate', 'width' => '100', 'filter' => '15', 'fdate' => '%d/%m/%Y'),
        array( 'title' => $_LANG['TITLE'], 'field' => 'title', 'width' => '', 'filter' => '15', 'link' => '?view=components&do=config&id='. $id .'&opt=edit&item_id=%id%'),
        array( 'title' => $_LANG['CLUB_TYPE'], 'field' => 'clubtype', 'width' => '100'),
        array( 'title' => $_LANG['MEMBERS'], 'field' => 'members_count', 'width' => '100'),
        array( 'title' => $_LANG['AD_IS_PUBLISHED'], 'field' => 'published', 'width' => '100', 'do' => 'opt', 'do_suffix' => '_club')
    );
    
    $actions = array(
Esempio n. 15
0
function applet_config()
{
    // получаем оригинальный конфиг
    $config = cmsConfig::getDefaultConfig();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/config', $adminAccess)) {
        cpAccessDenied();
    }
    $GLOBALS['cp_page_title'] = $_LANG['AD_SITE_SETTING'];
    cpAddPathway($_LANG['AD_SITE_SETTING'], 'index.php?view=config');
    $do = cmsCore::request('do', 'str', 'list');
    if ($do == 'save') {
        if (!cmsCore::validateForm()) {
            cmsCore::error404();
        }
        $newCFG = array();
        $newCFG['sitename'] = stripslashes(cmsCore::request('sitename', 'str', ''));
        $newCFG['title_and_sitename'] = cmsCore::request('title_and_sitename', 'int', 0);
        $newCFG['title_and_page'] = cmsCore::request('title_and_page', 'int', 0);
        $newCFG['hometitle'] = stripslashes(cmsCore::request('hometitle', 'str', ''));
        $newCFG['homecom'] = cmsCore::request('homecom', 'str', '');
        $newCFG['siteoff'] = cmsCore::request('siteoff', 'int', 0);
        $newCFG['debug'] = cmsCore::request('debug', 'int', 0);
        $newCFG['offtext'] = htmlspecialchars(cmsCore::request('offtext', 'str', ''), ENT_QUOTES);
        $newCFG['keywords'] = cmsCore::request('keywords', 'str', '');
        $newCFG['metadesc'] = cmsCore::request('metadesc', 'str', '');
        $newCFG['seourl'] = cmsCore::request('seourl', 'int', 0);
        $newCFG['lang'] = cmsCore::request('lang', 'str', 'ru');
        $newCFG['is_change_lang'] = cmsCore::request('is_change_lang', 'int', 0);
        $newCFG['sitemail'] = cmsCore::request('sitemail', 'str', '');
        $newCFG['sitemail_name'] = cmsCore::request('sitemail_name', 'str', '');
        $newCFG['wmark'] = cmsCore::request('wmark', 'str', '');
        $newCFG['template'] = cmsCore::request('template', 'str', '');
        $newCFG['splash'] = cmsCore::request('splash', 'int', 0);
        $newCFG['slight'] = cmsCore::request('slight', 'int', 0);
        $newCFG['db_host'] = $config['db_host'];
        $newCFG['db_base'] = $config['db_base'];
        $newCFG['db_user'] = $config['db_user'];
        $newCFG['db_pass'] = $config['db_pass'];
        $newCFG['db_prefix'] = $config['db_prefix'];
        $newCFG['show_pw'] = cmsCore::request('show_pw', 'int', 0);
        $newCFG['last_item_pw'] = cmsCore::request('last_item_pw', 'int', 0);
        $newCFG['index_pw'] = cmsCore::request('index_pw', 'int', 0);
        $newCFG['fastcfg'] = cmsCore::request('fastcfg', 'int', 0);
        $newCFG['mailer'] = cmsCore::request('mailer', 'str', '');
        $newCFG['smtpsecure'] = cmsCore::request('smtpsecure', 'str', '');
        $newCFG['smtpauth'] = cmsCore::request('smtpauth', 'int', 0);
        $newCFG['smtpuser'] = cmsCore::inRequest('smtpuser') ? cmsCore::request('smtpuser', 'str', '') : $config['smtpuser'];
        $newCFG['smtppass'] = cmsCore::inRequest('smtppass') ? cmsCore::request('smtppass', 'str', '') : $config['smtppass'];
        $newCFG['smtphost'] = cmsCore::request('smtphost', 'str', '');
        $newCFG['smtpport'] = cmsCore::request('smtpport', 'int', '25');
        $newCFG['timezone'] = cmsCore::request('timezone', 'str', '');
        $newCFG['timediff'] = cmsCore::request('timediff', 'str', '');
        $newCFG['user_stats'] = cmsCore::request('user_stats', 'int', 0);
        $newCFG['allow_ip'] = cmsCore::request('allow_ip', 'str', '');
        if (cmsConfig::saveToFile($newCFG)) {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SAVE_SUCCESS'], 'success');
        } else {
            cmsCore::addSessionMessage($_LANG['AD_CONFIG_SITE_ERROR'], 'error');
        }
        cmsCore::clearCache();
        cmsCore::redirect('index.php?view=config');
    }
    ?>
<div>

      <?php 
    cpCheckWritable('/includes/config.inc.php');
    ?>

<div id="config_tabs" class="uitabs">

  <ul id="tabs">
	  	<li><a href="#basic"><span><?php 
    echo $_LANG['AD_SITE'];
    ?>
</span></a></li>
	  	<li><a href="#home"><span><?php 
    echo $_LANG['AD_MAIN'];
    ?>
</span></a></li>
		<li><a href="#design"><span><?php 
    echo $_LANG['AD_DESIGN'];
    ?>
</span></a></li>
		<li><a href="#time"><span><?php 
    echo $_LANG['AD_TIME'];
    ?>
</span></a></li>
		<li><a href="#database"><span><?php 
    echo $_LANG['AD_DB'];
    ?>
</span></a></li>
		<li><a href="#mail"><span><?php 
    echo $_LANG['AD_POST'];
    ?>
</span></a></li>
		<li><a href="#other"><span><?php 
    echo $_LANG['AD_PATHWAY'];
    ?>
</span></a></li>
		<li><a href="#seq"><span><?php 
    echo $_LANG['AD_SECURITY'];
    ?>
</span></a></li>
  </ul>

	<form action="/admin/index.php?view=config" method="post" name="CFGform" target="_self" id="CFGform" style="margin-bottom:30px">
    <input type="hidden" name="csrf_token" value="<?php 
    echo cmsUser::getCsrfToken();
    ?>
" />
        <div id="basic">
			<table width="720" border="0" cellpadding="5">
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_SITENAME'];
    ?>
</strong><br/>
						<span class="hinttext"><?php 
    echo $_LANG['AD_USE_HEADER'];
    ?>
</span>
                    </td>
					<td width="350" valign="top">
                        <input name="sitename" type="text" id="sitename" value="<?php 
    echo htmlspecialchars($config['sitename']);
    ?>
" style="width:358px" />
                    </td>
				</tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_TAGE_ADD'];
    ?>
</strong>
                    </td>
					<td valign="top">
						<label><input name="title_and_sitename" type="radio" value="1" <?php 
    if ($config['title_and_sitename']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="title_and_sitename" type="radio" value="0" <?php 
    if (!$config['title_and_sitename']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
                    </td>
				</tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_TAGE_ADD_PAGINATION'];
    ?>
</strong>
                    </td>
					<td valign="top">
						<label><input name="title_and_page" type="radio" value="1" <?php 
    if ($config['title_and_page']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="title_and_page" type="radio" value="0" <?php 
    if (!$config['title_and_page']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
                    </td>
				</tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['TEMPLATE_INTERFACE_LANG'];
    ?>
:</strong>
                    </td>
					<td width="350" valign="top">
                        <select name="lang" id="lang" style="width:364px">
                            <?php 
    $langs = cmsCore::getDirsList('/languages');
    foreach ($langs as $lng) {
        echo '<option value="' . $lng . '" ' . ($config['lang'] == $lng ? 'selected="selected"' : '') . '>' . $lng . '</option>';
    }
    ?>
                        </select>
                    </td>
				</tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_SITE_LANGUAGE_CHANGE'];
    ?>
</strong><br/>
                        <span class="hinttext"><?php 
    echo $_LANG['AD_VIEW_FORM_LANGUAGE_CHANGE'];
    ?>
</span>
                    </td>
					<td valign="top">
						<label><input name="is_change_lang" type="radio" value="1" <?php 
    if ($config['is_change_lang']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="is_change_lang" type="radio" value="0" <?php 
    if (!$config['is_change_lang']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
                    </td>
				</tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_SITE_ON'];
    ?>
</strong><br/>
                        <span class="hinttext"><?php 
    echo $_LANG['AD_ONLY_ADMINS'];
    ?>
</span>
                    </td>
					<td valign="top">
                        <label><input name="siteoff" type="radio" value="0" <?php 
    if (!$config['siteoff']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
                        <label><input name="siteoff" type="radio" value="1" <?php 
    if ($config['siteoff']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
                    </td>
                </tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_DEBUG_ON'];
    ?>
</strong><br/>
						<span class="hinttext"><?php 
    echo $_LANG['AD_WIEW_DB_ERRORS'];
    ?>
</span>
                    </td>
					<td valign="top">
						<label><input name="debug" type="radio" value="1" <?php 
    if ($config['debug']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="debug" type="radio" value="0" <?php 
    if (!$config['debug']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
                    </td>
				</tr>
				<tr>
					<td valign="middle">
                        <strong><?php 
    echo $_LANG['AD_WHY_STOP'];
    ?>
</strong><br />
						<span class="hinttext"><?php 
    echo $_LANG['AD_VIEW_WHY_STOP'];
    ?>
</span>

                    </td>
					<td valign="top"><input name="offtext" type="text" id="offtext" value="<?php 
    echo htmlspecialchars($config['offtext']);
    ?>
" style="width:358px" /></td>
				</tr>
				<tr>
					<td>
                        <strong><?php 
    echo $_LANG['AD_WATERMARK'];
    ?>
 </strong><br/>
						<span class="hinttext"><?php 
    echo $_LANG['AD_WATERMARK_NAME'];
    ?>
</span>
                    </td>
					<td>
						<input name="wmark" type="text" id="wmark" value="<?php 
    echo $config['wmark'];
    ?>
" style="width:358px" />
                    </td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_QUICK_CONFIG'];
    ?>
</strong> <br />
						<span class="hinttext"><?php 
    echo $_LANG['AD_MODULE_CONFIG'];
    ?>
</span>
                    </td>
                    <td valign="top">
                        <label><input name="fastcfg" type="radio" value="1" <?php 
    if ($config['fastcfg']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
                        <label><input name="fastcfg" type="radio" value="0" <?php 
    if (!$config['fastcfg']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
                    </td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_ONLINESTATS'];
    ?>
</strong>
                    </td>
                    <td valign="top">
                        <label><input name="user_stats" type="radio" value="0" <?php 
    if (!$config['user_stats']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['AD_NO_ONLINESTATS'];
    ?>
</label><br>
                        <label><input name="user_stats" type="radio" value="1" <?php 
    if ($config['user_stats'] == 1) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['AD_YES_ONLINESTATS'];
    ?>
</label><br>
                        <label><input name="user_stats" type="radio" value="2" <?php 
    if ($config['user_stats'] == 2) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['AD_CRON_ONLINESTATS'];
    ?>
</label>
                    </td>
				</tr>
			</table>
        </div>
        <div id="home">
			<table width="720" border="0" cellpadding="5">
                <tr>
    				<td>
                        <strong><?php 
    echo $_LANG['AD_MAIN_PAGE'];
    ?>
</strong><br />
						<span class="hinttext"><?php 
    echo $_LANG['AD_MAIN_SITENAME'];
    ?>
</span><br/>
                        <span class="hinttext"><?php 
    echo $_LANG['AD_BROWSER_TITLE'];
    ?>
</span>
                    </td>
                    <td width="350" valign="top">
                        <input name="hometitle" type="text" id="hometitle" value="<?php 
    echo htmlspecialchars($config['hometitle']);
    ?>
" style="width:358px" />
                    </td>
			    </tr>
				<tr>
					<td valign="top">
						<strong><?php 
    echo $_LANG['AD_KEY_WORDS'];
    ?>
</strong><br />
						<span class="hinttext"><?php 
    echo $_LANG['AD_FROM_COMMA'];
    ?>
</span>
						<div class="hinttext" style="margin-top:4px"><a style="color:#09C" href="http://tutorial.semonitor.ru/#5" target="_blank"><?php 
    echo $_LANG['AD_WHAT_KEY_WORDS'];
    ?>
</a></div>
                    </td>
					<td>
						<textarea name="keywords" style="width:350px" rows="3" id="keywords"><?php 
    echo $config['keywords'];
    ?>
</textarea>					</td>
				</tr>
				<tr>
					<td valign="top">
						<strong><?php 
    echo $_LANG['AD_DESCRIPTION'];
    ?>
</strong><br />
						<span class="hinttext"><?php 
    echo $_LANG['AD_LESS_THAN'];
    ?>
</span>
						<div class="hinttext" style="margin-top:4px"><a style="color:#09C" href="http://tutorial.semonitor.ru/#219" target="_blank"><?php 
    echo $_LANG['AD_WHAT_DESCRIPTION'];
    ?>
</a></div>
                    </td>
					<td>
						<textarea name="metadesc" style="width:350px" rows="3" id="metadesc"><?php 
    echo $config['metadesc'];
    ?>
</textarea>
                    </td>
				</tr>
                <tr>
    				<td>
                        <strong><?php 
    echo $_LANG['AD_MAIN_PAGE_COMPONENT'];
    ?>
</strong>
                    </td>
                    <td width="350" valign="top">
                        <select name="homecom" style="width:358px">
                            <option value="" <?php 
    if (!$config['homecom']) {
        ?>
selected="selected"<?php 
    }
    ?>
><?php 
    echo $_LANG['AD_ONLY_MODULES'];
    ?>
</option>
                            <?php 
    echo cmsCore::getListItems('cms_components', $config['homecom'], 'title', 'ASC', 'internal=0', 'link');
    ?>
                        </select>
                    </td>
			    </tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_GATE_PAGE'];
    ?>
</strong> <br/>
						<span class="hinttext"><?php 
    echo $_LANG['AD_FIRST_VISIT'];
    ?>
</span> <br/>
                        <span class="hinttext"><?php 
    echo $_LANG['AD_FIRST_VISIT_TEMPLATE'];
    ?>
</strong></span>
					</td>
					<td valign="top">
						<label><input name="splash" type="radio" value="0" <?php 
    if (!$config['splash']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['HIDE'];
    ?>
</label>
						<label><input name="splash" type="radio" value="1" <?php 
    if ($config['splash']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['SHOW'];
    ?>
</label>
					</td>
				</tr>
			</table>
        </div>
		<div id="design">
			<table width="720" border="0" cellpadding="5">
				<tr>
					<td valign="top">
                        <div style="margin-top:2px">
                            <strong><?php 
    echo $_LANG['TEMPLATE'];
    ?>
:</strong><br />
                            <span class="hinttext"><?php 
    echo $_LANG['AD_TEMPLATE_FOLDER'];
    ?>
 </span>
                        </div>
					</td>
					<td>
                        <select name="template" id="template" style="width:350px" onchange="document.CFGform.submit();">
                            <?php 
    $templates = cmsCore::getDirsList('/templates');
    foreach ($templates as $template) {
        echo '<option value="' . $template . '" ' . ($config['template'] == $template ? 'selected="selected"' : '') . '>' . $template . '</option>';
    }
    $tpl_info = $inPage->getCurrentTplInfo();
    ?>
                        </select>
                            <?php 
    if (file_exists(PATH . '/templates/' . TEMPLATE . '/positions.jpg')) {
        ?>
                            <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_TPL_POS'];
        ?>
</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>
                            <?php 
    }
    ?>
                        <div style="margin-top:5px" class="hinttext">
                            <?php 
    echo sprintf($_LANG['AD_TEMPLATE_INFO'], $tpl_info['author'], $tpl_info['renderer'], $tpl_info['ext']);
    ?>
                        </div>
					</td>
				</tr>
				<tr>
					<td><strong><?php 
    echo $_LANG['AD_SEARCH_RESULT'];
    ?>
</strong></td>
					<td valign="top">
						<label><input name="slight" type="radio" value="1" <?php 
    if ($config['slight']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="slight" type="radio" value="0" <?php 
    if (!$config['slight']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
					</td>
				</tr>
			</table>
		</div>
		<div id="time">
			<table width="720" border="0" cellpadding="5">
				<tr>
					<td valign="top" width="100">
                        <div style="margin-top:2px">
                            <strong><?php 
    echo $_LANG['AD_TIME_ARREA'];
    ?>
</strong>
                        </div>
					</td>
					<td>
                        <select name="timezone" id="timezone" style="width:350px">
                            <?php 
    include PATH . '/admin/includes/timezones.php';
    ?>
                            <?php 
    foreach ($timezones as $tz) {
        ?>
                            <option value="<?php 
        echo $tz;
        ?>
" <?php 
        if ($tz == $config['timezone']) {
            ?>
selected="selected"<?php 
        }
        ?>
><?php 
        echo $tz;
        ?>
</option>
                            <?php 
    }
    ?>
                        </select>
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_TIME_SLIP'];
    ?>
</strong>
					</td>
					<td width="350">
                        <select name="timediff" id="timediff" style="width:60px">
                            <?php 
    for ($h = -12; $h <= 12; $h++) {
        ?>
                                <option value="<?php 
        echo $h;
        ?>
" <?php 
        if ($h == $config['timediff']) {
            ?>
selected="selected"<?php 
        }
        ?>
><?php 
        echo $h > 0 ? '+' . $h : $h;
        ?>
</option>
                            <?php 
    }
    ?>
                        </select>
					</td>
				</tr>
			</table>
		</div>
		<div id="database">
			<table width="720" border="0" cellpadding="5" style="margin-top:15px;">
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_DB_SIZE'];
    ?>
</strong>
					</td>
					<td width="350">
                        <?php 
    $result = $inDB->query("SELECT (sum(data_length)+sum(index_length))/1024/1024 as size FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '{$config['db_base']}'", true);
    if (!$inDB->error()) {
        $s = $inDB->fetch_assoc($result);
        echo round($s['size'], 2) . ' ' . $_LANG['SIZE_MB'];
    } else {
        echo $_LANG['AD_DB_SIZE_ERROR'];
    }
    ?>
					</td>
				</tr>
				<tr>
					<td colspan="2"><span class="hinttext"><?php 
    echo $_LANG['AD_MYSQL_CONFIG'];
    ?>
</span></td>
				</tr>
			</table>
        </div>
		<div id="mail">
			<table width="720" border="0" cellpadding="5" style="margin-top:15px;">
				<tr>
					<td width="250">
                        <strong><?php 
    echo $_LANG['AD_SITE_EMAIL'];
    ?>
 </strong><br/>
						<span class="hinttext"><?php 
    echo $_LANG['AD_SITE_EMAIL_POST'];
    ?>
</span>
                    </td>
					<td>
						<input name="sitemail" type="text" id="sitemail" value="<?php 
    echo $config['sitemail'];
    ?>
" style="width:358px" />
                    </td>
				</tr>
				<tr>
					<td width="250">
                        <strong><?php 
    echo $_LANG['AD_SENDER_EMAIL'];
    ?>
</strong><br/>
						<span class="hinttext"><?php 
    echo $_LANG['AD_IF_NOT_HANDLER'];
    ?>
</span>
                    </td>
					<td>
						<input name="sitemail_name" type="text" id="sitemail_name" value="<?php 
    echo $config['sitemail_name'];
    ?>
" style="width:358px" />
                    </td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_SEND_METHOD'];
    ?>
</strong>
					</td>
					<td>
						<select name="mailer" style="width:354px">
							<option value="mail" <?php 
    if ($config['mailer'] == 'mail') {
        echo 'selected="selected"';
    }
    ?>
><?php 
    echo $_LANG['AD_PHP_MAILER'];
    ?>
</option>
							<option value="sendmail" <?php 
    if ($config['mailer'] == 'sendmail') {
        echo 'selected="selected"';
    }
    ?>
><?php 
    echo $_LANG['AD_SEND_MAILER'];
    ?>
</option>
							<option value="smtp" <?php 
    if ($config['mailer'] == 'smtp') {
        echo 'selected="selected"';
    }
    ?>
><?php 
    echo $_LANG['AD_SMTP_MAILER'];
    ?>
</option>
						</select>
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_ENCRYPTING'];
    ?>
</strong>
					</td>
					<td>
						<label><input name="smtpsecure" type="radio" value="" <?php 
    if (!$config['smtpsecure']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
						<label><input name="smtpsecure" type="radio" value="tls" <?php 
    if ($config['smtpsecure'] == 'tls') {
        echo 'checked="checked"';
    }
    ?>
/> tls</label>
						<label><input name="smtpsecure" type="radio" value="ssl" <?php 
    if ($config['smtpsecure'] == 'ssl') {
        echo 'checked="checked"';
    }
    ?>
/> ssl</label>
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_SMTP_LOGIN'];
    ?>
</strong>
					</td>
					<td>
						<label><input name="smtpauth" type="radio" value="1" <?php 
    if ($config['smtpauth']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="smtpauth" type="radio" value="0" <?php 
    if (!$config['smtpauth']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_SMTP_USER'];
    ?>
</strong>
					</td>
					<td>
                        <?php 
    if (!$config['smtpuser']) {
        ?>
                            <input name="smtpuser" type="text" id="smtpuser" value="<?php 
        echo $config['smtpuser'];
        ?>
" style="width:350px" />
                        <?php 
    } else {
        ?>
                            <span class="hinttext"><?php 
        echo $_LANG['AD_IF_CHANGE_USER'];
        ?>
</span>
                        <?php 
    }
    ?>
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_SMTP_PASS'];
    ?>
</strong>
					</td>
					<td>
                        <?php 
    if (!$config['smtppass']) {
        ?>
                            <input name="smtppass" type="password" id="smtppass" value="<?php 
        echo $config['smtppass'];
        ?>
" style="width:350px" />
                        <?php 
    } else {
        ?>
                            <span class="hinttext"><?php 
        echo $_LANG['AD_IF_CHANGE_PASS'];
        ?>
</span>
                        <?php 
    }
    ?>
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_SMTP_HOST'];
    ?>
</strong><br>
                        <span class="hinttext"><?php 
    echo $_LANG['AD_SOME_HOST'];
    ?>
</span>
					</td>
					<td>
						<input name="smtphost" type="text" id="smtphost" value="<?php 
    echo $config['smtphost'];
    ?>
" style="width:350px" />
					</td>
				</tr>
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_SMTP_PORT'];
    ?>
</strong>
					</td>
					<td>
						<input name="smtpport" type="text" id="smtpport" value="<?php 
    echo $config['smtpport'];
    ?>
" style="width:350px" />
					</td>
				</tr>
			</table>
		</div>
		<div id="other">
			<table width="720" border="0" cellpadding="5">
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_VIEW_PATHWAY'];
    ?>
</strong><br />
						<span class="hinttext">
                            <?php 
    echo $_LANG['AD_PATH_TO_CATEGORY'];
    ?>
                        </span>
					</td>
					<td>
						<label><input name="show_pw" type="radio" value="1" <?php 
    if ($config['show_pw']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="show_pw" type="radio" value="0" <?php 
    if (!$config['show_pw']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
					</td>
				</tr>
				<tr>
					<td><strong><?php 
    echo $_LANG['AD_MAINPAGE_PATHWAY'];
    ?>
</strong></td>
					<td>
						<label><input name="index_pw" type="radio" value="1" <?php 
    if ($config['index_pw']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['YES'];
    ?>
</label>
						<label><input name="index_pw" type="radio" value="0" <?php 
    if (!$config['index_pw']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['NO'];
    ?>
</label>
					</td>
				</tr>
				<tr>
					<td><strong><?php 
    echo $_LANG['AD_PAGE_PATHWAY'];
    ?>
</strong></td>
					<td>
						<label><input name="last_item_pw" type="radio" value="0" <?php 
    if (!$config['last_item_pw']) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['HIDE'];
    ?>
</label>
						<label><input name="last_item_pw" type="radio" value="1" <?php 
    if ($config['last_item_pw'] == 1) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['AD_PAGE_PATHWAY_LINK'];
    ?>
</label>
						<label><input name="last_item_pw" type="radio" value="2" <?php 
    if ($config['last_item_pw'] == 2) {
        echo 'checked="checked"';
    }
    ?>
/><?php 
    echo $_LANG['AD_PAGE_PATHWAY_TEXT'];
    ?>
</label>
					</td>
				</tr>
			</table>
        </div>
        <div id="seq">
			<table width="720" border="0" cellpadding="5">
				<tr>
					<td>
						<strong><?php 
    echo $_LANG['AD_IP_ADMIN'];
    ?>
</strong> <br />
						<span class="hinttext"><?php 
    echo $_LANG['AD_IP_COMMA'];
    ?>
</span></td>
				<td valign="top">
					<input name="allow_ip" type="text" id="allow_ip" value="<?php 
    echo htmlspecialchars($config['allow_ip']);
    ?>
" style="width:358px" /></td>
				</tr>
			</table>
    <p style="color:#900"><?php 
    echo $_LANG['AD_ATTENTION'];
    ?>
</p>
        </div>

	<div align="left">
		<input name="do" type="hidden" id="do" value="save" />
		<input name="save" type="submit" id="save" value="<?php 
    echo $_LANG['SAVE'];
    ?>
" />
        <input name="back" type="button" id="back" value="<?php 
    echo $_LANG['CANCEL'];
    ?>
" onclick="window.history.back();" />
	</div>
</form>
</div></div>
<?php 
}
Esempio n. 16
0
function content()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    $model = new cms_model_content();
    define('IS_BILLING', $inCore->isComponentInstalled('billing'));
    if (IS_BILLING) {
        cmsCore::loadClass('billing');
    }
    global $_LANG;
    $id = cmsCore::request('id', 'int', 0);
    $do = $inCore->do;
    $seolink = cmsCore::strClear(urldecode(cmsCore::request('seolink', 'html', '')));
    if (is_numeric($seolink)) {
        cmsCore::error404();
    }
    $page = cmsCore::request('page', 'int', 1);
    ///////////////////////////////////// VIEW CATEGORY ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'view') {
        $cat = $inDB->getNsCategory('cms_category', $seolink);
        // если не найдена категория и мы не на главной, 404
        if (!$cat && $inCore->menuId() !== 1) {
            cmsCore::error404();
        }
        // языки
        $cat = translations::process(cmsConfig::getConfig('lang'), 'content_category', $cat);
        // Плагины
        $cat = cmsCore::callEvent('GET_CONTENT_CAT', $cat);
        // Неопубликованные показываем только админам
        if (!$cat['published'] && !$inUser->is_admin) {
            cmsCore::error404();
        }
        // Проверяем доступ к категории
        if (!$inCore->checkUserAccess('category', $cat['id'])) {
            cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
            cmsCore::redirect('/content');
        }
        // если не корень категорий
        if ($cat['NSLevel'] > 0) {
            $inPage->setTitle($cat['pagetitle'] ? $cat['pagetitle'] : $cat['title']);
            $pagetitle = $cat['title'];
            $showdate = $cat['showdate'];
            $showcomm = $cat['showcomm'];
            $inPage->addHead('<link rel="alternate" type="application/rss+xml" title="' . htmlspecialchars($cat['title']) . '" href="' . HOST . '/rss/content/' . $cat['id'] . '/feed.rss">');
        }
        // Если корневая категория
        if ($cat['NSLevel'] == 0) {
            if ($model->config['hide_root']) {
                cmsCore::error404();
            }
            $inPage->setTitle($_LANG['CATALOG_ARTICLES']);
            $pagetitle = $_LANG['CATALOG_ARTICLES'];
            $showdate = 1;
            $showcomm = 1;
        }
        // Получаем дерево категорий
        $path_list = $inDB->getNsCategoryPath('cms_category', $cat['NSLeft'], $cat['NSRight'], 'id, title, NSLevel, seolink, url');
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'content_category', $path_list);
            foreach ($path_list as $pcat) {
                if (!$inCore->checkUserAccess('category', $pcat['id'])) {
                    cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
                    cmsCore::redirect('/content');
                }
                $inPage->addPathway($pcat['title'], $model->getCategoryURL(null, $pcat['seolink']));
            }
        }
        // Получаем подкатегории
        $subcats_list = $model->getSubCats($cat['id']);
        // Привязанный фотоальбом
        $cat_photos = $model->getCatPhotoAlbum($cat['photoalbum']);
        // Получаем статьи
        // Редактор/администратор
        $is_editor = $cat['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd') || $inUser->is_admin;
        // Условия
        $model->whereCatIs($cat['id']);
        // Общее количество статей
        $total = $model->getArticlesCount($is_editor);
        // Сортировка и разбивка на страницы
        $inDB->orderBy($cat['orderby'], $cat['orderto']);
        $inDB->limitPage($page, $model->config['perpage']);
        // Получаем статьи
        $content_list = $total ? $model->getArticlesList(!$is_editor) : array();
        $inDB->resetConditions();
        if (!$content_list && $page > 1) {
            cmsCore::error404();
        }
        $pagebar = cmsPage::getPagebar($total, $page, $model->config['perpage'], $model->getCategoryURL(null, $cat['seolink'], 0, true));
        $template = $cat['tpl'] ? $cat['tpl'] : 'com_content_view.tpl';
        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 ($content_list) {
                foreach ($content_list as $c) {
                    $k[] = $c['title'];
                }
                $meta_keys = implode(', ', $k);
            } else {
                $meta_keys = $cat['title'];
            }
            $inPage->setKeywords($meta_keys);
        }
        cmsPage::initTemplate('components', $template)->assign('cat', $cat)->assign('is_homepage', (bool) ($inCore->menuId() == 1))->assign('showdate', $showdate)->assign('showcomm', $showcomm)->assign('pagetitle', $pagetitle)->assign('subcats', $subcats_list)->assign('cat_photos', $cat_photos)->assign('articles', $content_list)->assign('pagebar', $pagebar)->display($template);
    }
    ///////////////////////////////////// READ ARTICLE ////////////////////////////////////////////////////////////////////////////////
    if ($do == 'read') {
        // Получаем статью
        $article = $model->getArticle($seolink);
        if (!$article) {
            cmsCore::error404();
        }
        $article = translations::process(cmsConfig::getConfig('lang'), 'content_content', $article);
        $article = cmsCore::callEvent('GET_ARTICLE', $article);
        $is_admin = $inUser->is_admin;
        $is_author = $inUser->id == $article['user_id'];
        $is_author_del = cmsUser::isUserCan('content/delete');
        $is_editor = $article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd');
        // если статья не опубликована или дата публикации позже, 404
        if ((!$article['published'] || strtotime($article['pubdate']) > time()) && !$is_admin && !$is_editor && !$is_author) {
            cmsCore::error404();
        }
        if (!$inCore->checkUserAccess('material', $article['id'])) {
            cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
            cmsCore::redirect($model->getCategoryURL(null, $article['catseolink']));
        }
        // увеличиваем кол-во просмотров
        if (@(!$is_author)) {
            $inDB->setFlag('cms_content', $article['id'], 'hits', $article['hits'] + 1);
        }
        // Картинка статьи
        $article['image'] = file_exists(PATH . '/images/photos/medium/article' . $article['id'] . '.jpg') ? 'article' . $article['id'] . '.jpg' : '';
        // Заголовок страницы
        $article['pagetitle'] = $article['pagetitle'] ? $article['pagetitle'] : $article['title'];
        // Тело статьи в зависимости от настроек
        $article['content'] = $model->config['readdesc'] ? $article['description'] . $article['content'] : $article['content'];
        // Дата публикации
        $article['pubdate'] = cmsCore::dateFormat($article['pubdate']);
        // Шаблон статьи
        $article['tpl'] = $article['tpl'] ? $article['tpl'] : 'com_content_read.tpl';
        $inPage->setTitle($article['pagetitle']);
        // Получаем дерево категорий
        $path_list = $article['showpath'] ? $inDB->getNsCategoryPath('cms_category', $article['leftkey'], $article['rightkey'], 'id, title, NSLevel, seolink, url') : array();
        if ($path_list) {
            $path_list = translations::process(cmsConfig::getConfig('lang'), 'content_category', $path_list);
            foreach ($path_list as $pcat) {
                if (!$inCore->checkUserAccess('category', $pcat['id'])) {
                    cmsCore::addSessionMessage($_LANG['NO_PERM_FOR_VIEW_TEXT'] . '<br>' . $_LANG['NO_PERM_FOR_VIEW_RULES'], 'error');
                    cmsCore::redirect('/content');
                }
                $inPage->addPathway($pcat['title'], $model->getCategoryURL(null, $pcat['seolink']));
            }
        }
        $inPage->addPathway($article['title']);
        // Мета теги KEYWORDS и DESCRIPTION
        if ($article['meta_keys']) {
            $inPage->setKeywords($article['meta_keys']);
        } else {
            if (mb_strlen($article['content']) > 30) {
                $inPage->setKeywords(cmsCore::getKeywords(cmsCore::strClear($article['content'])));
            }
        }
        if (mb_strlen($article['meta_desc'])) {
            $inPage->setDescription($article['meta_desc']);
        }
        // Выполняем фильтры
        $article['content'] = cmsCore::processFilters($article['content']);
        // Разбивка статей на страницы
        $pt_pages = array();
        if (!empty($GLOBALS['pt'])) {
            foreach ($GLOBALS['pt'] as $num => $page_title) {
                $pt_pages[$num]['title'] = $page_title;
                $pt_pages[$num]['url'] = $model->getArticleURL(null, $article['seolink'], $num + 1);
            }
        }
        // Рейтинг статьи
        if ($model->config['rating'] && $article['canrate']) {
            $karma = cmsKarma('content', $article['id']);
            $karma_points = cmsKarmaFormatSmall($karma['points']);
            $btns = cmsKarmaButtonsText('content', $article['id'], $karma['points'], $is_author);
        }
        cmsPage::initTemplate('components', $article['tpl'])->assign('article', $article)->assign('cfg', $model->config)->assign('page', $page)->assign('is_pages', !empty($GLOBALS['pt']))->assign('pt_pages', $pt_pages)->assign('is_admin', $is_admin)->assign('is_editor', $is_editor)->assign('is_author', $is_author)->assign('is_author_del', $is_author_del)->assign('tagbar', cmsTagBar('content', $article['id']))->assign('karma_points', @$karma_points)->assign('karma_votes', @$karma['votes'])->assign('karma_buttons', @$btns)->display($article['tpl']);
        // Комментарии статьи
        if ($article['published'] && $article['comments'] && $inCore->isComponentInstalled('comments')) {
            cmsCore::includeComments();
            comments('article', $article['id'], array(), $is_author);
        }
    }
    ///////////////////////////////////// ADD ARTICLE //////////////////////////////////////////////////////////////////////////////////
    if ($do == 'addarticle' || $do == 'editarticle') {
        $is_add = cmsUser::isUserCan('content/add');
        // может добавлять статьи
        $is_auto_add = cmsUser::isUserCan('content/autoadd');
        // добавлять статьи без модерации
        if (!$is_add && !$is_auto_add) {
            cmsCore::error404();
        }
        // Для редактирования получаем статью и проверяем доступ
        if ($do == 'editarticle') {
            // Получаем статью
            $item = $model->getArticle($id);
            if (!$item) {
                cmsCore::error404();
            }
            $pubcats = array();
            // доступ к редактированию админам, авторам и редакторам
            if (!$inUser->is_admin && $item['user_id'] != $inUser->id && !($item['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd'))) {
                cmsCore::error404();
            }
        }
        // Для добавления проверяем не вводили ли мы данные ранее
        if ($do == 'addarticle') {
            $item = cmsUser::sessionGet('article');
            if ($item) {
                cmsUser::sessionDel('article');
            }
            // Категории, в которые разрешено публиковать
            $pubcats = $model->getPublicCats();
            if (!$pubcats) {
                cmsCore::addSessionMessage($_LANG['ADD_ARTICLE_ERR_CAT'], 'error');
                cmsCore::redirectBack();
            }
        }
        // не было запроса на сохранение, показываем форму
        if (!cmsCore::inRequest('add_mod')) {
            $dynamic_cost = false;
            // Если добавляем статью
            if ($do == 'addarticle') {
                $pagetitle = $_LANG['ADD_ARTICLE'];
                $inPage->setTitle($pagetitle);
                $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
                $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
                $inPage->addPathway($_LANG['MY_ARTICLES'], '/content/my.html');
                $inPage->addPathway($pagetitle);
                // поддержка биллинга
                if (IS_BILLING) {
                    $action = cmsBilling::getAction('content', 'add_content');
                    foreach ($pubcats as $p => $pubcat) {
                        if ($pubcat['cost']) {
                            $dynamic_cost = true;
                        } else {
                            $pubcats[$p]['cost'] = $action['point_cost'][$inUser->group_id];
                        }
                    }
                    cmsBilling::checkBalance('content', 'add_content', $dynamic_cost);
                }
            }
            // Если редактируем статью
            if ($do == 'editarticle') {
                $pagetitle = $_LANG['EDIT_ARTICLE'];
                $inPage->setTitle($pagetitle);
                $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
                if ($item['user_id'] != $inUser->id) {
                    $user = $inDB->get_fields('cms_users', "id='{$item['user_id']}'", 'login, nickname');
                    $inPage->addPathway($user['nickname'], cmsUser::getProfileURL($user['login']));
                } else {
                    $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
                }
                $inPage->addPathway($_LANG['MY_ARTICLES'], '/content/my.html');
                $inPage->addPathway($pagetitle);
                $item['tags'] = cmsTagLine('content', $item['id'], false);
                $item['image'] = file_exists(PATH . '/images/photos/small/article' . $item['id'] . '.jpg') ? 'article' . $item['id'] . '.jpg' : '';
                if (!$is_auto_add) {
                    cmsCore::addSessionMessage($_LANG['ATTENTION'] . ': ' . $_LANG['EDIT_ARTICLE_PREMODER'], 'info');
                }
            }
            $inPage->initAutocomplete();
            $autocomplete_js = $inPage->getAutocompleteJS('tagsearch', 'tags');
            $item = cmsCore::callEvent('PRE_EDIT_ARTICLE', @$item ? $item : array());
            cmsPage::initTemplate('components', 'com_content_edit')->assign('mod', $item)->assign('do', $do)->assign('cfg', $model->config)->assign('pubcats', $pubcats)->assign('pagetitle', $pagetitle)->assign('is_admin', $inUser->is_admin)->assign('is_billing', IS_BILLING)->assign('dynamic_cost', $dynamic_cost)->assign('autocomplete_js', $autocomplete_js)->display('com_content_edit.tpl');
        }
        // Пришел запрос на сохранение статьи
        if (cmsCore::inRequest('add_mod')) {
            $errors = false;
            $article['category_id'] = cmsCore::request('category_id', 'int', 1);
            $article['user_id'] = $item['user_id'] ? $item['user_id'] : $inUser->id;
            $article['title'] = cmsCore::request('title', 'str', '');
            $article['tags'] = cmsCore::request('tags', 'str', '');
            $article['description'] = cmsCore::request('description', 'html', '');
            $article['content'] = cmsCore::request('content', 'html', '');
            $article['description'] = cmsCore::badTagClear($article['description']);
            $article['content'] = cmsCore::badTagClear($article['content']);
            $article['published'] = $is_auto_add ? 1 : 0;
            if ($do == 'editarticle') {
                $article['published'] = $item['published'] == 0 ? $item['published'] : $article['published'];
            }
            $article['pubdate'] = $do == 'editarticle' ? $item['pubdate'] : date('Y-m-d H:i');
            $article['enddate'] = $do == 'editarticle' ? $item['enddate'] : $article['pubdate'];
            $article['is_end'] = $do == 'editarticle' ? $item['is_end'] : 0;
            $article['showtitle'] = $do == 'editarticle' ? $item['showtitle'] : 1;
            $article['meta_desc'] = $do == 'addarticle' ? mb_strtolower($article['title']) : $inDB->escape_string($item['meta_desc']);
            $article['meta_keys'] = $do == 'addarticle' ? $inCore->getKeywords($article['content']) : $inDB->escape_string($item['meta_keys']);
            $article['showdate'] = $do == 'editarticle' ? $item['showdate'] : 1;
            $article['showlatest'] = $do == 'editarticle' ? $item['showlatest'] : 1;
            $article['showpath'] = $do == 'editarticle' ? $item['showpath'] : 1;
            $article['comments'] = $do == 'editarticle' ? $item['comments'] : 1;
            $article['canrate'] = $do == 'editarticle' ? $item['canrate'] : 1;
            $article['pagetitle'] = '';
            if ($do == 'editarticle') {
                $article['tpl'] = $item['tpl'];
            }
            if (mb_strlen($article['title']) < 2) {
                cmsCore::addSessionMessage($_LANG['REQ_TITLE'], 'error');
                $errors = true;
            }
            if (mb_strlen($article['content']) < 10) {
                cmsCore::addSessionMessage($_LANG['REQ_CONTENT'], 'error');
                $errors = true;
            }
            if ($errors) {
                // При добавлении статьи при ошибках сохраняем введенные поля
                if ($do == 'addarticle') {
                    cmsUser::sessionPut('article', $article);
                }
                cmsCore::redirectBack();
            }
            $article['description'] = $inDB->escape_string($article['description']);
            $article['content'] = $inDB->escape_string($article['content']);
            $article = cmsCore::callEvent('AFTER_EDIT_ARTICLE', $article);
            // добавление статьи
            if ($do == 'addarticle') {
                $article_id = $model->addArticle($article);
            }
            // загрузка фото
            $file = 'article' . (@$article_id ? $article_id : $item['id']) . '.jpg';
            if (cmsCore::request('delete_image', 'int', 0)) {
                @unlink(PATH . "/images/photos/small/{$file}");
                @unlink(PATH . "/images/photos/medium/{$file}");
            }
            // Загружаем класс загрузки фото
            cmsCore::loadClass('upload_photo');
            $inUploadPhoto = cmsUploadPhoto::getInstance();
            // Выставляем конфигурационные параметры
            $inUploadPhoto->upload_dir = PATH . '/images/photos/';
            $inUploadPhoto->small_size_w = $model->config['img_small_w'];
            $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
            $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
            $inUploadPhoto->is_watermark = $model->config['watermark'];
            $inUploadPhoto->input_name = 'picture';
            $inUploadPhoto->filename = $file;
            // Процесс загрузки фото
            $inUploadPhoto->uploadPhoto();
            // операции после добавления/редактирования статьи
            // добавление статьи
            if ($do == 'addarticle') {
                // Получаем добавленную статью
                $article = $model->getArticle($article_id);
                if (!$article['published']) {
                    cmsCore::addSessionMessage($_LANG['ARTICLE_PREMODER_TEXT'], 'info');
                    // отсылаем уведомление администраторам
                    $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_ARTICLE_SUBMIT']);
                    $message = str_replace('%link%', $link, $message);
                    cmsUser::sendMessageToGroup(USER_UPDATER, cmsUser::getAdminGroups(), $message);
                } else {
                    //регистрируем событие
                    cmsActions::log('add_article', array('object' => $article['title'], 'object_url' => $model->getArticleURL(null, $article['seolink']), 'object_id' => $article['id'], 'target' => $article['cat_title'], 'target_url' => $model->getCategoryURL(null, $article['catseolink']), 'target_id' => $article['category_id'], 'description' => ''));
                    if (IS_BILLING) {
                        $category_cost = $article['cost'] === '' ? false : (int) $article['cost'];
                        cmsBilling::process('content', 'add_content', $category_cost);
                    }
                    cmsUser::checkAwards($inUser->id);
                }
                cmsCore::addSessionMessage($_LANG['ARTICLE_SAVE'], 'info');
                cmsCore::redirect('/my.html');
            }
            // Редактирование статьи
            if ($do == 'editarticle') {
                $model->updateArticle($item['id'], $article, true);
                cmsActions::updateLog('add_article', array('object' => $article['title']), $item['id']);
                if (!$article['published']) {
                    $link = '<a href="' . $model->getArticleURL(null, $item['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%user%', cmsUser::getProfileLink($inUser->login, $inUser->nickname), $_LANG['MSG_ARTICLE_EDITED']);
                    $message = str_replace('%link%', $link, $message);
                    cmsUser::sendMessageToGroup(USER_UPDATER, cmsUser::getAdminGroups(), $message);
                }
                $mess = $article['published'] ? $_LANG['ARTICLE_SAVE'] : $_LANG['ARTICLE_SAVE'] . ' ' . $_LANG['ARTICLE_PREMODER_TEXT'];
                cmsCore::addSessionMessage($mess, 'info');
                cmsCore::redirect($model->getArticleURL(null, $item['seolink']));
            }
        }
    }
    ///////////////////////// PUBLISH ARTICLE /////////////////////////////////////////////////////////////////////////////
    if ($do == 'publisharticle') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $article = $model->getArticle($id);
        if (!$article) {
            cmsCore::error404();
        }
        // Редактор с правами на добавление без модерации или администраторы могут публиковать
        if (!($article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd')) && !$inUser->is_admin) {
            cmsCore::error404();
        }
        $inDB->setFlag('cms_content', $article['id'], 'published', 1);
        cmsCore::callEvent('ADD_ARTICLE_DONE', $article);
        if (IS_BILLING) {
            $author = $inDB->get_fields('cms_users', "id='{$article['user_id']}'", '*');
            $category_cost = $article['cost'] === '' ? false : (int) $article['cost'];
            cmsBilling::process('content', 'add_content', $category_cost, $author);
        }
        //регистрируем событие
        cmsActions::log('add_article', array('object' => $article['title'], 'user_id' => $article['user_id'], 'object_url' => $model->getArticleURL(null, $article['seolink']), 'object_id' => $article['id'], 'target' => $article['cat_title'], 'target_url' => $model->getCategoryURL(null, $article['catseolink']), 'target_id' => $article['cat_id'], 'description' => ''));
        $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
        $message = str_replace('%link%', $link, $_LANG['MSG_ARTICLE_ACCEPTED']);
        cmsUser::sendMessage(USER_UPDATER, $article['user_id'], $message);
        cmsUser::checkAwards($article['user_id']);
        cmsCore::redirectBack();
    }
    ///////////////////////////////////// DELETE ARTICLE ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'deletearticle') {
        if (!$inUser->id) {
            cmsCore::error404();
        }
        $article = $model->getArticle($id);
        if (!$article) {
            cmsCore::error404();
        }
        // права доступа
        $is_author = cmsUser::isUserCan('content/delete') && $article['user_id'] == $inUser->id;
        $is_editor = $article['modgrp_id'] == $inUser->group_id && cmsUser::isUserCan('content/autoadd');
        if (!$is_author && !$is_editor && !$inUser->is_admin) {
            cmsCore::error404();
        }
        if (!cmsCore::inRequest('goadd')) {
            $inPage->setTitle($_LANG['ARTICLE_REMOVAL']);
            $inPage->addPathway($_LANG['ARTICLE_REMOVAL']);
            $confirm['title'] = $_LANG['ARTICLE_REMOVAL'];
            $confirm['text'] = $_LANG['ARTICLE_REMOVAL_TEXT'] . ' <a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>?';
            $confirm['action'] = $_SERVER['REQUEST_URI'];
            $confirm['yes_button'] = array();
            $confirm['yes_button']['type'] = 'submit';
            $confirm['yes_button']['name'] = 'goadd';
            cmsPage::initTemplate('components', 'action_confirm')->assign('confirm', $confirm)->display('action_confirm.tpl');
        } else {
            $model->deleteArticle($article['id']);
            if ($_SERVER['HTTP_REFERER'] == '/my.html') {
                cmsCore::addSessionMessage($_LANG['ARTICLE_DELETED'], 'info');
                cmsCore::redirectBack();
            } else {
                // если удалили как администратор или редактор и мы не авторы статьи, отсылаем сообщение автору
                if (($is_editor || $inUser->is_admin) && $article['user_id'] != $inUser->id) {
                    $link = '<a href="' . $model->getArticleURL(null, $article['seolink']) . '">' . $article['title'] . '</a>';
                    $message = str_replace('%link%', $link, $article['published'] ? $_LANG['MSG_ARTICLE_DELETED'] : $_LANG['MSG_ARTICLE_REJECTED']);
                    cmsUser::sendMessage(USER_UPDATER, $article['user_id'], $message);
                } else {
                    cmsCore::addSessionMessage($_LANG['ARTICLE_DELETED'], 'info');
                }
                cmsCore::redirect($model->getCategoryURL(null, $article['catseolink']));
            }
        }
    }
    ///////////////////////////////////// MY ARTICLES ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'my') {
        if (!cmsUser::isUserCan('content/add')) {
            cmsCore::error404();
        }
        $inPage->setTitle($_LANG['MY_ARTICLES']);
        $inPage->addPathway($_LANG['USERS'], '/' . str_replace('/', '', cmsUser::PROFILE_LINK_PREFIX));
        $inPage->addPathway($inUser->nickname, cmsUser::getProfileURL($inUser->login));
        $inPage->addPathway($_LANG['MY_ARTICLES']);
        $perpage = 15;
        // Условия
        $model->whereUserIs($inUser->id);
        // Общее количество статей
        $total = $model->getArticlesCount(false);
        // Сортировка и разбивка на страницы
        $inDB->orderBy('con.pubdate', 'DESC');
        $inDB->limitPage($page, $perpage);
        // Получаем статьи
        $content_list = $total ? $model->getArticlesList(false) : array();
        $inDB->resetConditions();
        cmsPage::initTemplate('components', 'com_content_my')->assign('articles', $content_list)->assign('total', $total)->assign('user_can_delete', cmsUser::isUserCan('content/delete'))->assign('pagebar', cmsPage::getPagebar($total, $page, $perpage, '/content/my%page%.html'))->display('com_content_my.tpl');
    }
    ///////////////////////////////////// BEST ARTICLES ///////////////////////////////////////////////////////////////////////////////////
    if ($do == 'best') {
        $inPage->setTitle($_LANG['ARTICLES_RATING']);
        $inPage->addPathway($_LANG['ARTICLES_RATING']);
        // Только статьи, за которые можно голосовать
        $inDB->where("con.canrate = 1");
        // Сортировка и разбивка на страницы
        $inDB->orderBy('con.rating', 'DESC');
        $inDB->limitPage(1, 30);
        // Получаем статьи
        $content_list = $model->getArticlesList();
        cmsPage::initTemplate('components', 'com_content_rating')->assign('articles', $content_list)->display('com_content_rating.tpl');
    }
}
Esempio n. 17
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();
    }
    //============================================================================//
}
Esempio n. 18
0
function applet_usergroups()
{
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/users', $adminAccess)) {
        cpAccessDenied();
    }
    $GLOBALS['cp_page_title'] = $_LANG['AD_USERS_GROUP'];
    cpAddPathway($_LANG['AD_USERS'], 'index.php?view=users');
    cpAddPathway($_LANG['AD_USERS_GROUP'], 'index.php?view=usergroups');
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    cmsCore::loadModel('users');
    $model = new cms_model_users();
    if ($do == 'list') {
        $toolmenu[] = array('icon' => 'usergroupadd.gif', 'title' => $_LANG['AD_CREATE_GROUP'], 'link' => '?view=usergroups&do=add');
        $toolmenu[] = array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=usergroups&do=edit&multiple=1');");
        $toolmenu[] = array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:if(confirm('{$_LANG['AD_REMOVE_GROUP']}')) { checkSel('?view=users&do=delete&multiple=1'); }");
        cpToolMenu($toolmenu);
        $fields[] = array('title' => 'id', 'field' => 'id', 'width' => '30');
        $fields[] = array('title' => $_LANG['TITLE'], 'field' => 'title', 'width' => '', 'link' => '?view=usergroups&do=edit&id=%id%', 'filter' => '12');
        $fields[] = array('title' => $_LANG['AD_FROM_USERS'], 'field' => 'id', 'width' => '100', 'prc' => 'getCountUsers');
        $fields[] = array('title' => $_LANG['AD_IF_ADMIN'], 'field' => 'is_admin', 'width' => '110', 'prc' => 'cpYesNo');
        $fields[] = array('title' => $_LANG['AD_ALIAS'], 'field' => 'alias', 'width' => '75', 'filter' => '12');
        $actions[] = array('title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=usergroups&do=edit&id=%id%');
        $actions[] = array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_REMOVE_GROUP'], 'link' => '?view=usergroups&do=delete&id=%id%');
        cpListTable('cms_user_groups', $fields, $actions);
    }
    if ($do == 'delete') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                $model->deleteGroup($id);
            }
        } else {
            $model->deleteGroups(cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
        cmsCore::redirect('index.php?view=usergroups');
    }
    if ($do == 'submit' || $do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $types = array('title' => array('title', 'str', ''), 'alias' => array('alias', 'str', ''), 'is_admin' => array('is_admin', 'int', 0), 'access' => array('access', 'array_str', array(), create_function('$a_list', 'return implode(\',\', $a_list);')));
        $items = cmsCore::getArrayFromRequest($types);
        if ($do == 'submit') {
            $inDB->insert('cms_user_groups', $items);
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            cmsCore::redirect('index.php?view=usergroups');
        } else {
            $inDB->update('cms_user_groups', $items, $id);
            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            if (empty($_SESSION['editlist'])) {
                cmsCore::redirect('index.php?view=usergroups');
            } else {
                cmsCore::redirect('index.php?view=usergroups&do=edit');
            }
        }
    }
    if ($do == 'add' || $do == 'edit') {
        $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);');
        cpToolMenu($toolmenu);
        if ($do == 'add') {
            cpAddPathway($_LANG['AD_CREATE_GROUP']);
        } 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_user_groups', "id = '{$item_id}'", '*');
            if (!$mod) {
                cmsCore::error404();
            }
            echo '<h3>' . $_LANG['AD_EDIT_GROUP'] . ' ' . $ostatok . '</h3>';
            cpAddPathway($_LANG['AD_EDIT_GROUP'] . ' ' . $mod['title']);
        }
        if (isset($mod['access'])) {
            $mod['access'] = str_replace(', ', ',', $mod['access']);
            $mod['access'] = explode(',', $mod['access']);
        }
        ?>
	<form id="addform" name="addform" method="post" action="index.php?view=usergroups">
        <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
		<table width="660" border="0" cellspacing="5" class="proptable">
			<tr>
				<td width="198" valign="top"><div><strong><?php 
        echo $_LANG['AD_GROUP_NAME'];
        ?>
: </strong></div><span class="hinttext"><?php 
        echo $_LANG['AD_VIEW_SITE'];
        ?>
</span></td>
				<td width="475" valign="top"><input name="title" type="text" id="title" size="30" value="<?php 
        echo htmlspecialchars($mod['title']);
        ?>
"/></td>
			</tr>
			<tr>
				<td valign="top"><div><strong><?php 
        echo $_LANG['AD_ALIAS'];
        ?>
:</strong></div><?php 
        if ($do == 'edit') {
            ?>
<span class="hinttext"><?php 
            echo $_LANG['AD_DONT_CHANGE'];
            ?>
</span><?php 
        }
        ?>
</td>
    <td valign="top"><input name="alias" type="text" id="title3" <?php 
        if (@$mod['alias'] == 'guest') {
            ?>
readonly="readonly"<?php 
        }
        ?>
 size="30" value="<?php 
        echo @$mod['alias'];
        ?>
"/></td>
			</tr>
			<tr>
				<td><strong><?php 
        echo $_LANG['AD_IF_ADMIN'];
        ?>
</strong></td>
				<td>
					<label><input name="is_admin" type="radio" value="1" <?php 
        if (@$mod['is_admin']) {
            echo 'checked="checked"';
        }
        ?>
 onclick="$('#accesstable').hide();$('#admin_accesstable').show();"/> <?php 
        echo $_LANG['YES'];
        ?>
 </label>
					<label><input name="is_admin" type="radio" value="0"  <?php 
        if (@(!$mod['is_admin'])) {
            echo 'checked="checked"';
        }
        ?>
 onclick="$('#accesstable').show();$('#admin_accesstable').hide();"/> <?php 
        echo $_LANG['NO'];
        ?>
</label>
				</td>
			</tr>
		</table>

		<!--------------------------------------------------------------------------------------------------------------------------------------------->

		<table width="660" border="0" cellspacing="5" class="proptable" id="admin_accesstable" style="<?php 
        if (@(!$mod['is_admin'])) {
            echo 'display:none;';
        }
        ?>
">
			<tr>
				<td width="191" valign="top">
					<div><strong><?php 
        echo $_LANG['AD_AVAILABLE_SECTIONS'];
        ?>
 </strong></div>
					<span class="hinttext"><?php 
        echo $_LANG['AD_ALL_SECTIONS'];
        ?>
</span>
				</td>
				<td width="475" valign="top">
					<table width="100%" border="0" cellspacing="2" cellpadding="0">
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_menu" value="admin/menu" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/menu', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_menu"><?php 
        echo $_LANG['AD_MENU_CONTROL'];
        ?>
</label></td>
						</tr>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_modules" value="admin/modules" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/modules', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_modules"><?php 
        echo $_LANG['AD_MODULES_CONTROL'];
        ?>
</label></td>
						</tr>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_content" value="admin/content" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/content', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_content"><?php 
        echo $_LANG['AD_CONTENTS_CONTROL'];
        ?>
</label></td>
						</tr>
                        <tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_plugins" value="admin/plugins" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/filters', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_plugins"><?php 
        echo $_LANG['AD_PLUGINS_CONTROL'];
        ?>
</label></td>
						</tr>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_filters" value="admin/filters" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/filters', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_filters"><?php 
        echo $_LANG['AD_FILTERS_CONTROL'];
        ?>
</label></td>
						</tr>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_components" value="admin/components" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/components', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_components"><?php 
        echo $_LANG['AD_COMPONENTS_CONTROL'];
        ?>
</label></td>
						</tr>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_users" value="admin/users" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/users', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_users"><?php 
        echo $_LANG['AD_USERS_CONTROL'];
        ?>
</label></td>
						</tr>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_config" value="admin/config" <?php 
        if (isset($mod['access'])) {
            if (in_array('admin/config', $mod['access'])) {
                echo 'checked="checked"';
            }
        }
        ?>
></td>
							<td><label for="admin_config"><?php 
        echo $_LANG['AD_SETTINGS_CONTROL'];
        ?>
</label></td>
						</tr>
					</table>
                </td>
			</tr>
			<tr>
			  <td valign="top">
			  	<div><strong><?php 
        echo $_LANG['AD_COMPONENTS_SETTINGS_FREE'];
        ?>
 </strong></div>
				<span class="hinttext"><?php 
        echo $_LANG['AD_COMPONENTS_SETTINGS_ON'];
        ?>
</span>
			  </td>
			  <td valign="top">
				  <table width="100%" border="0" cellspacing="2" cellpadding="0">

						<?php 
        $coms = cmsCore::getInstance()->getAllComponents();
        foreach ($coms as $com) {
            if (!file_exists(PATH . '/admin/components/' . $com['link'] . '/backend.php')) {
                continue;
            }
            ?>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="admin_com_<?php 
            echo $com['link'];
            ?>
" value="admin/com_<?php 
            echo $com['link'];
            ?>
" <?php 
            if (isset($mod['access'])) {
                if (in_array('admin/com_' . $com['link'], $mod['access'])) {
                    echo 'checked="checked"';
                }
            }
            ?>
 /></td>
							<td><label for="admin_com_<?php 
            echo $com['link'];
            ?>
"><?php 
            echo $com['title'];
            ?>
</label></td>
						</tr>
						<?php 
        }
        ?>

				  </table>
			  </td>
		  </tr>
		</table>

		<!--------------------------------------------------------------------------------------------------------------------------------------------->

		<table width="660" border="0" cellspacing="5" class="proptable" id="accesstable" style="<?php 
        if (@$mod['is_admin']) {
            echo 'display:none;';
        }
        ?>
">
			<tr>
				<td width="191" valign="top"><strong><?php 
        echo $_LANG['AD_GROUP_RULE'];
        ?>
 </strong></td>
				<td width="475" valign="top">
					<table width="100%" border="0" cellspacing="2" cellpadding="0">

					<?php 
        $sql = "SELECT * FROM cms_user_groups_access ORDER BY access_type";
        $res = $inDB->query($sql);
        while ($ga = $inDB->fetch_assoc($res)) {
            if ($mod['alias'] == 'guest' && $ga['hide_for_guest']) {
                continue;
            }
            ?>
						<tr>
							<td width="16"><input type="checkbox" name="access[]" id="<?php 
            echo str_replace('/', '_', $ga['access_type']);
            ?>
" value="<?php 
            echo $ga['access_type'];
            ?>
" <?php 
            if (isset($mod['access'])) {
                if (in_array($ga['access_type'], $mod['access'])) {
                    echo 'checked="checked"';
                }
            }
            ?>
></td>
							<td><label for="<?php 
            echo str_replace('/', '_', $ga['access_type']);
            ?>
"><?php 
            echo $ga['access_name'];
            ?>
</label></td>
						</tr>
                    <?php 
        }
        ?>
					</table>
				</td>
			</tr>
		</table>

		<!--------------------------------------------------------------------------------------------------------------------------------------------->

		<p>
			<input name="add_mod" type="submit" id="add_mod" <?php 
        if ($do == 'add') {
            echo 'value="' . $_LANG['AD_CREATE_GROUP'] . '"';
        } else {
            echo 'value="' . $_LANG['SAVE'] . '"';
        }
        ?>
 />
			<span style="margin-top:15px"><input name="back" type="button" id="back" value="<?php 
        echo $_LANG['CANCEL'];
        ?>
" onclick="window.history.back();"/></span>
			<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 
    }
}
Esempio n. 19
0
File: cp.php Progetto: deltas1/icms1
function cpListTable($table, $_fields, $_actions, $where = '', $orderby = 'title')
{
    $event = 'ADMIN_CPLISTTABLE_' . strtoupper($table) . '_' . strtoupper($GLOBALS['applet']) . (!empty($GLOBALS['component']) ? '_' . strtoupper($GLOBALS['component']) : '');
    list($table, $_fields, $_actions, $where, $orderby) = cmsCore::callEvent($event, array($table, $_fields, $_actions, $where, $orderby));
    global $_LANG;
    $inDB = cmsDatabase::getInstance();
    $perpage = 60;
    $sql = 'SELECT *';
    $is_actions = sizeof($_actions);
    foreach ($_fields as $key => $value) {
        if (isset($_fields[$key]['fdate'])) {
            $sql .= ", DATE_FORMAT(" . $_fields[$key]['field'] . ", '" . $_fields[$key]['fdate'] . "') as `" . $_fields[$key]['field'] . "`";
        }
    }
    $sql .= ' FROM ' . $table;
    if (isset($_SESSION['filter_table']) && $_SESSION['filter_table'] != $table) {
        unset($_SESSION['filter']);
    }
    if (cmsCore::inRequest('nofilter')) {
        unset($_SESSION['filter']);
        cmsCore::redirect('/admin/index.php?' . str_replace('&nofilter', '', $_SERVER['QUERY_STRING']));
    }
    $filter = false;
    if (cmsCore::inRequest('filter')) {
        $filter = cmsCore::request('filter', 'array_str', '');
        $_SESSION['filter'] = $filter;
    } elseif (isset($_SESSION['filter'])) {
        $filter = $_SESSION['filter'];
    }
    if ($filter) {
        $f = 0;
        $sql .= ' WHERE 1=1';
        foreach ($filter as $key => $value) {
            if ($filter[$key] && $filter[$key] != -100) {
                $sql .= ' AND ';
                if (!is_numeric($filter[$key])) {
                    $sql .= $key . " LIKE '%" . $filter[$key] . "%'";
                } else {
                    $sql .= $key . " = '" . $filter[$key] . "'";
                }
                $f++;
            }
        }
        if (!isset($_SESSION['filter'])) {
            $_SESSION['filter'] = $filter;
        }
    }
    if (mb_strlen($where) > 3) {
        if (mb_strstr($sql, 'WHERE')) {
            $sql .= ' AND ' . $where;
        } else {
            $sql .= ' WHERE ' . $where;
        }
    }
    $sort = cmsCore::request('sort', 'str', '');
    if ($sort == false) {
        if ($orderby) {
            $sort = $orderby;
        } else {
            foreach ($_fields as $key => $value) {
                if ($_fields[$key]['field'] == 'ordering' && $sort != 'NSLeft') {
                    $sort = 'ordering';
                    $so = 'asc';
                }
            }
        }
    }
    if ($sort) {
        $sql .= ' ORDER BY ' . $sort;
        if (cmsCore::inRequest('so')) {
            $sql .= ' ' . cmsCore::request('so', 'str', '');
        }
    }
    $page = cmsCore::request('page', 'int', 1);
    $total_rs = $inDB->query($sql);
    $total = $inDB->num_rows($total_rs);
    $sql .= " LIMIT " . ($page - 1) * $perpage . ", {$perpage}";
    $result = $inDB->query($sql);
    $_SESSION['filter_table'] = $table;
    if ($inDB->error()) {
        unset($_SESSION['filter']);
        cmsCore::redirect('/admin/index.php?' . $_SERVER['QUERY_STRING']);
    }
    $filters = 0;
    $f_html = '';
    //Find and render filters
    foreach ($_fields as $key => $value) {
        if (isset($_fields[$key]['filter'])) {
            $f_html .= '<td width="">' . $_fields[$key]['title'] . ': </td>';
            if (!isset($filter[$_fields[$key]['field']])) {
                $initval = '';
            } else {
                $initval = $filter[$_fields[$key]['field']];
            }
            $f_html .= '<td width="">';
            $inputname = 'filter[' . $_fields[$key]['field'] . ']';
            if (!isset($_fields[$key]['filterlist'])) {
                $f_html .= '<input name="' . $inputname . '" type="text" size="' . $_fields[$key]['filter'] . '" class="filter_input" value="' . $initval . '"/></td>';
            } else {
                $f_html .= cpBuildList($inputname, $_fields[$key]['filterlist'], $initval);
            }
            $f_html .= '</td>';
            $filters += 1;
            $_SERVER['QUERY_STRING'] = str_replace('filter[' . $_fields[$key]['field'] . ']=', '', $_SERVER['QUERY_STRING']);
        }
    }
    //draw filters
    if ($filters > 0) {
        echo '<div class="filter">';
        echo '<form name="filterform" action="index.php?' . $_SERVER['QUERY_STRING'] . '" method="POST">';
        echo '<table width="250"><tr>';
        echo $f_html;
        echo '<td width="80"><input type="submit" class="filter_submit" value="' . $_LANG['AD_FILTER'] . '" /></td>';
        if (@$f > 0) {
            echo '<td width="80"><input type="button" onclick="window.location.href=\'index.php?' . $_SERVER['QUERY_STRING'] . '&nofilter\'" class="filter_submit" value="' . $_LANG['AD_ALL'] . '" /></td>';
        }
        echo '</tr></table>';
        echo '</form>';
        echo '</div>';
    }
    if ($inDB->num_rows($result)) {
        //DRAW LIST TABLE
        echo '<form name="selform" action="index.php?view=' . $GLOBALS['applet'] . '&do=saveorder" method="post">';
        echo '<table id="listTable" border="0" class="tablesorter" width="100%" cellpadding="0" cellspacing="0">';
        //TABLE HEADING
        echo '<thead>' . "\n";
        echo '<tr>' . "\n";
        echo '<th width="20" class="lt_header" align="center"><a class="lt_header_link" href="javascript:invert();" title="' . $_LANG['AD_INVERT_SELECTION'] . '">#</a></th>' . "\n";
        foreach ($_fields as $key => $value) {
            echo '<th width="' . $_fields[$key]['width'] . '" class="lt_header">';
            echo $_fields[$key]['title'];
            echo '</th>' . "\n";
        }
        if ($is_actions) {
            echo '<th width="80" class="lt_header" align="center">' . $_LANG['AD_ACTIONS'] . '</th>' . "\n";
        }
        echo '</tr>' . "\n";
        echo '</thead><tbody>' . "\n";
        //TABLE BODY
        $r = 0;
        while ($item = $inDB->fetch_assoc($result)) {
            $r++;
            if ($r % 2) {
                $row_class = 'lt_row1';
            } else {
                $row_class = 'lt_row2';
            }
            echo '<tr id="lt_row2">' . "\n";
            echo '<td class="' . $row_class . '" align="center" valign="middle"><input type="checkbox" name="item[]" value="' . $item['id'] . '" /></td>' . "\n";
            foreach ($_fields as $key => $value) {
                if (isset($_fields[$key]['link'])) {
                    $link = str_replace('%id%', $item['id'], $_fields[$key]['link']);
                    if (isset($_fields[$key]['prc'])) {
                        // функция обработки под названием $_fields[$key]['prc']
                        // какие параметры передать функции - один ключ или произвольный массив ключей
                        if (is_array($_fields[$key]['field'])) {
                            foreach ($_fields[$key]['field'] as $func_field) {
                                $in_func_array[$func_field] = $item[$func_field];
                            }
                            $data = call_user_func($_fields[$key]['prc'], $in_func_array);
                        } else {
                            $data = call_user_func($_fields[$key]['prc'], $item[$_fields[$key]['field']]);
                        }
                    } else {
                        $data = $item[$_fields[$key]['field']];
                        if (isset($_fields[$key]['maxlen'])) {
                            if (mb_strlen($data) > $_fields[$key]['maxlen']) {
                                $data = mb_substr($data, 0, $_fields[$key]['maxlen']) . '...';
                            }
                        }
                    }
                    //nested sets otstup
                    if (isset($item['NSLevel']) && ($_fields[$key]['field'] == 'title' || is_array($_fields[$key]['field']) && in_array('title', $_fields[$key]['field']))) {
                        $otstup = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $item['NSLevel'] - 1);
                        if ($item['NSLevel'] - 1 > 0) {
                            $otstup .= ' &raquo; ';
                        }
                    } else {
                        $otstup = '';
                    }
                    if ($table != 'cms_components') {
                        echo '<td class="' . $row_class . '" valign="middle">' . $otstup . '<a class="lt_link" href="' . $link . '">' . $data . '</a></td>' . "\n";
                    } else {
                        $data = function_exists('cpComponentHasConfig') && cpComponentHasConfig($item['link']) ? '<a class="lt_link" href="' . $link . '">' . $data . '</a>' : $data;
                        echo '<td class="' . $row_class . '" valign="middle">
                                            <span class="lt_link" style="padding:1px; padding-left:24px; background:url(/admin/images/components/' . $item['link'] . '.png) no-repeat">' . $data . '</span>
                                      </td>' . "\n";
                    }
                } else {
                    if ($_fields[$key]['field'] != 'ordering') {
                        if ($_fields[$key]['field'] == 'published') {
                            if (isset($_fields[$key]['do'])) {
                                $do = $_fields[$key]['do'];
                            } else {
                                $do = 'do';
                            }
                            if (isset($_fields[$key]['do_suffix'])) {
                                $dos = $_fields[$key]['do_suffix'];
                                $ids = 'item_id';
                            } else {
                                $dos = '';
                                $ids = 'id';
                            }
                            if ($item['published']) {
                                $qs = cpAddParam($_SERVER['QUERY_STRING'], $do, 'hide' . $dos);
                                $qs = cpAddParam($qs, $ids, $item['id']);
                                $qs2 = cpAddParam($_SERVER['QUERY_STRING'], $do, 'show' . $dos);
                                $qs2 = cpAddParam($qs2, $ids, $item['id']);
                                $qs = "pub(" . $item['id'] . ", '" . $qs . "', '" . $qs2 . "', 'off', 'on');";
                                echo '<td class="' . $row_class . '" valign="middle">
												<a title="' . $_LANG['HIDE'] . '" class="uittip" id="publink' . $item['id'] . '" href="javascript:' . $qs . '"><img id="pub' . $item['id'] . '" src="images/actions/on.gif" border="0"/></a>
											 </td>' . "\n";
                            } else {
                                $qs = cpAddParam($_SERVER['QUERY_STRING'], $do, 'show' . $dos);
                                $qs = cpAddParam($qs, $ids, $item['id']);
                                $qs2 = cpAddParam($_SERVER['QUERY_STRING'], $do, 'hide' . $dos);
                                $qs2 = cpAddParam($qs2, $ids, $item['id']);
                                $qs = "pub(" . $item['id'] . ", '" . $qs . "', '" . $qs2 . "', 'on', 'off');";
                                echo '<td class="' . $row_class . '" valign="middle">
												<a title="' . $_LANG['SHOW'] . '" class="uittip" id="publink' . $item['id'] . '" href="javascript:' . $qs . '"><img id="pub' . $item['id'] . '" src="images/actions/off.gif" border="0"/></a>
											 </td>' . "\n";
                            }
                        } else {
                            if (isset($_fields[$key]['prc'])) {
                                // функция обработки под названием $_fields[$key]['prc']
                                // какие параметры передать функции - один ключ или произвольный массив ключей
                                if (is_array($_fields[$key]['field'])) {
                                    foreach ($_fields[$key]['field'] as $func_field) {
                                        $in_func_array[$func_field] = $item[$func_field];
                                    }
                                    $data = call_user_func($_fields[$key]['prc'], $in_func_array);
                                } else {
                                    $data = call_user_func($_fields[$key]['prc'], $item[$_fields[$key]['field']]);
                                }
                            } else {
                                $data = $item[$_fields[$key]['field']];
                                if (isset($_fields[$key]['maxlen'])) {
                                    if (mb_strlen($data) > $_fields[$key]['maxlen']) {
                                        $data = mb_substr($data, 0, $_fields[$key]['maxlen']) . '...';
                                    }
                                }
                            }
                            //nested sets otstup
                            if (isset($item['NSLevel']) && ($_fields[$key]['field'] == 'title' || is_array($_fields[$key]['field']) && in_array('title', $_fields[$key]['field']))) {
                                $otstup = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $item['NSLevel'] - 1);
                                if ($item['NSLevel'] - 1 > 0) {
                                    $otstup .= ' &raquo; ';
                                }
                            } else {
                                $otstup = '';
                            }
                            echo '<td class="' . $row_class . '" valign="middle">' . $otstup . $data . '</td>' . "\n";
                        }
                    } else {
                        if (isset($_fields[$key]['do'])) {
                            $do = 'do=config&id=' . (int) $_REQUEST['id'] . '&' . $_fields[$key]['do'];
                        } else {
                            $do = 'do';
                        }
                        if (isset($_fields[$key]['do_suffix'])) {
                            $dos = $_fields[$key]['do_suffix'];
                            $ids = 'item_id';
                        } else {
                            $dos = '';
                            $ids = 'id';
                        }
                        echo '<td class="' . $row_class . '" valign="middle">
									<a title="' . $_LANG['AD_DOWN'] . '" href="?view=' . $GLOBALS['applet'] . '&' . $do . '=move_down&co=' . $item[$_fields[$key]['field']] . '&' . $ids . '=' . $item['id'] . '"><img src="images/actions/down.gif" border="0"/></a>';
                        if ($table != 'cms_menu' && $table != 'cms_category') {
                            echo '<input class="lt_input" type="text" size="4" name="ordering[]" value="' . $item['ordering'] . '" />';
                            echo '<input name="ids[]" type="hidden" value="' . $item['id'] . '" />';
                        } else {
                            echo '<input class="lt_input" type="text" size="4" name="ordering[]" value="' . $item['ordering'] . '" disabled/>';
                        }
                        echo '<a title="' . $_LANG['AD_UP'] . '" href="?view=' . $GLOBALS['applet'] . '&' . $do . '=move_up&co=' . $item[$_fields[$key]['field']] . '&' . $ids . '=' . $item['id'] . '"><img src="images/actions/top.gif" border="0"/></a>' . '</td>' . "\n";
                    }
                }
            }
            if ($is_actions) {
                echo '<td width="110" class="' . $row_class . '" align="right" valign="middle"><div style="padding-right:8px">';
                foreach ($_actions as $key => $value) {
                    if (isset($_actions[$key]['condition'])) {
                        $print = $_actions[$key]['condition']($item);
                    } else {
                        $print = true;
                    }
                    if ($print) {
                        $icon = $_actions[$key]['icon'];
                        $title = $_actions[$key]['title'];
                        $link = $_actions[$key]['link'];
                        foreach ($item as $f => $v) {
                            $link = str_replace('%' . $f . '%', $v, $link);
                        }
                        if (!isset($_actions[$key]['confirm'])) {
                            echo '<a href="' . $link . '" class="uittip" title="' . $title . '"><img hspace="2" src="images/actions/' . $icon . '" border="0" alt="' . $title . '"/></a>';
                        } else {
                            echo '<a href="#" class="uittip" onclick="jsmsg(\'' . $_actions[$key]['confirm'] . '\', \'' . $link . '\')" title="' . $title . '"><img hspace="2" src="images/actions/' . $icon . '" border="0" alt="' . $title . '"/></a>';
                        }
                    }
                }
                echo '</div></td>' . "\n";
            }
            echo '</tr>' . "\n";
        }
        echo '</tbody></table></form>';
        echo '<script type="text/javascript">highlightTableRows("listTable","hoverRow","clickedRow");</script>';
        echo '<script type="text/javascript">activateListTable("listTable");</script>';
        $link = '?view=' . $GLOBALS['applet'];
        if ($sort) {
            $link .= '&sort=' . $sort;
            if (cmsCore::inRequest('so')) {
                $link .= '&so=' . cmsCore::request('so');
            }
        }
        echo cmsPage::getPagebar($total, $page, $perpage, $_SERVER['PHP_SELF'] . '?' . cpAddParam($_SERVER['QUERY_STRING'], 'page', '%page%'));
    } else {
        echo '<p class="cp_message">' . $_LANG['OBJECTS_NOT_FOUND'] . '</p>';
    }
}
Esempio n. 20
0
function applet_install() {
    $inCore = cmsCore::getInstance();
    global $_LANG;
    
    cmsCore::c('page')->setTitle($_LANG['AD_SETUP_EXTENSION']);

    $do = cmsCore::request('do', 'str', 'list');
    
    global $adminAccess;
    
    //-------------------------------- Модули ----------------------------------
    //----------- Список модулей готовых к установке или обновлению ------------
    if ($do == 'module') {
        if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) { cpAccessDenied(); }

      	cpAddPathway($_LANG['AD_SETUP_MODULES'], 'index.php?view=install&do=module');

        $new_modules = $inCore->getNewModules();
        $upd_modules = $inCore->getUpdatedModules();

        echo '<h3>'. $_LANG['AD_SETUP_MODULES'] .'</h3>';

        if (!$new_modules && !$upd_modules) {
            echo '<p>'. $_LANG['AD_NO_SEARCH_MODULES'] .'</p>';
            echo '<p>'. $_LANG['AD_IF_WANT_SETUP_MODULES'] .'</p>';
            echo '<p><a class="btn btn-default" href="javascript:window.history.go(-1);">'. $_LANG['BACK'] .'</a></p>';
            return;
        }

        if ($new_modules) {
            echo '<div class="panel panel-default"><div class="panel-heading">'. $_LANG['AD_SEARCH_MODULES'] .'</div><div class="panel-body">';
                modulesList($new_modules, $_LANG['AD_SETUP'], 'install_module');
            echo '</div></div>';
        }

        if ($upd_modules) {
            echo '<div class="panel panel-default"><div class="panel-heading">'. $_LANG['AD_MODULES_UPDATE'] .'</div><div class="panel-body">';
                modulesList($upd_modules, $_LANG['AD_UPDATE'], 'upgrade_module');
            echo '</div></div>';
        }

        echo '<p><a class="btn btn-default" href="javascript:window.history.go(-1);">'. $_LANG['BACK'] .'</a></p>';
    }
    
    //--------------------------- Установка модуля -----------------------------
    if ($do == 'install_module') {

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

        $error = '';

        $module_id = cmsCore::request('id', 'str', '');

        if(!$module_id){ cmsCore::redirectBack(); }

        if ($inCore->loadModuleInstaller($module_id)){
            $_module = call_user_func('info_module_'.$module_id);
            //////////////////////////////////////
            $error   = call_user_func('install_module_'.$module_id);
        } else {
            $error = $_LANG['AD_MODULE_WIZARD_FAILURE'];
        }

        if ($error === true) {
            $inCore->installModule($_module, $_module['config']);
            cmsCore::addSessionMessage($_LANG['AD_MODULE'].' <strong>"'.$_module['title'].'"</strong> '.$_LANG['AD_SUCCESS'].$_LANG['AD_IS_INSTALL'], 'success');
            cmsCore::redirect('/admin/index.php?view=modules');
        } else {
            cmsCore::addSessionMessage($error , 'error');
            cmsCore::redirectBack();
        }

    }
    
    //--------------------------- Обновление модуля ----------------------------
    if ($do == 'upgrade_module') {
	if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) { cpAccessDenied(); }

        $error = '';

        $module_id = cmsCore::request('id', 'str', '');

        if(!$module_id){ cmsCore::redirectBack(); }

        if ($inCore->loadModuleInstaller($module_id)) {
            $_module = call_user_func('info_module_'.$module_id);
            if (isset($_module['link'])) {
                $_module['content'] = $_module['link'];
            }
            $error = call_user_func('upgrade_module_'.$module_id);
        } else {
            $error = $_LANG['AD_SETUP_WIZARD_FAILURE'];
        }

        if ($error === true) {
            $inCore->upgradeModule($_module, $_module['config']);
            cmsCore::addSessionMessage($_LANG['AD_MODULE'].' <strong>"'.$_module['title'].'"</strong> '.$_LANG['AD_SUCCESS'].$_LANG['AD_IS_UPDATE'], 'success');
            cmsCore::redirect('/admin/index.php?view=modules');
        } else {
            cmsCore::addSessionMessage($error , 'error');
            cmsCore::redirectBack();
        }

    }
    //==========================================================================
    
    //------------------------------ Компоненты --------------------------------
    //--------- Список компонентов готовых к установке или обновлению ----------
    if ($do == 'component') {
        if (!cmsUser::isAdminCan('admin/components', $adminAccess)) { cpAccessDenied(); }

      	cpAddPathway($_LANG['AD_SETUP_COMPONENTS'], 'index.php?view=install&do=component');

        $new_components = $inCore->getNewComponents();
        $upd_components = $inCore->getUpdatedComponents();

        echo '<h3>'. $_LANG['AD_SETUP_COMPONENTS'] .'</h3>';

        if (!$new_components && !$upd_components) {
            echo '<p>'. $_LANG['AD_NO_SEARCH_COMPONENTS'] .'</p>';
            echo '<p>'. $_LANG['AD_IF_WANT_SETUP_COMPONENTS'] .'</p>';
            echo '<p><a href="javascript:window.history.go(-1);" class="btn btn-default">'. $_LANG['BACK'] .'</a></p>';
            return;
        }

        if ($new_components) {
            echo '<div class="panel panel-default"><div class="panel-heading">'. $_LANG['AD_COMPONENTS_SETUP'] .'</div><div class="panel-body">';
                componentsList($new_components, $_LANG['AD_SETUP'], 'install_component');
            echo '</div></div>';
        }

        if ($upd_components) {
            echo '<div class="panel panel-default"><div class="panel-heading">'. $_LANG['AD_COMPONENTS_UPDATE'] .'</div><div class="panel-body">';
                componentsList($upd_components, $_LANG['AD_UPDATE'], 'upgrade_component');
            echo '</div></div>';

        }

        echo '<p><a href="javascript:window.history.go(-1);" class="btn btn-default">'. $_LANG['BACK'] .'</a></p>';
    }

    //------------------------- Установка компонента ---------------------------
    if ($do == 'install_component') {
        $error = '';

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

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

        if ($inCore->loadComponentInstaller($component)) {
            $_component = call_user_func('info_component_'.$component);
            $error      = call_user_func('install_component_'.$component);
        } else {
            $error = $_LANG['AD_COMPONENT_WIZARD_FAILURE'];
        }

        if ($error === true) {
            $inCore->installComponent($_component, $_component['config']);

            $info_text = '<p>'. $_LANG['AD_COMPONENT'] .' <strong>"'. $_component['title'] .'"</strong> '. $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_INSTALL'] .'</p>';
            if (isset($_component['modules'])){
                if (is_array($_component['modules'])) {
                    $info_text .= '<p>'. $_LANG['AD_OPT_INSTALL_MODULES'] .':</p>';
                    $info_text .= '<ul>';
                        foreach ($_component['modules'] as $module => $title) {
                            $info_text .= '<li>'. $title .'</li>';
                        }
                    $info_text .= '</ul>';
                }
            }
            if (isset($_component['plugins'])){
                if(is_array($_component['plugins'])){
                    $info_text .= '<p>'. $_LANG['AD_OPT_INSTALL_PLUGINS'] .':</p>';
                    $info_text .= '<ul>';
                        foreach($_component['plugins'] as $module=>$title){
                            $info_text .= '<li>'. $title .'</li>';
                        }
                    $info_text .= '</ul>';
                }
            }

            cmsCore::addSessionMessage($info_text, 'success');
            cmsCore::redirect('/admin/index.php?view=components');
        } else {
            cmsCore::addSessionMessage($error , 'error');
            cmsCore::redirectBack();
        }

    }

    //------------------------- Обновление компонента --------------------------
    if ($do == 'upgrade_component') {
        cpAddPathway($_LANG['AD_UPDATE_COMPONENTS'], 'index.php?view=install&do=component');

        $error = '';

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

		if (!cmsUser::isAdminCan('admin/components', $adminAccess)) { cpAccessDenied(); }
		if (!cmsUser::isAdminCan('admin/com_'.$component, $adminAccess)) { cpAccessDenied(); }

        if ($inCore->loadComponentInstaller($component)) {
            $_component = call_user_func('info_component_'.$component);
            $error      = call_user_func('upgrade_component_'.$component);
        } else {
            $error = $_LANG['AD_COMPONENT_WIZARD_FAILURE'];
        }

        if ($error === true) {
            $inCore->upgradeComponent($_component, $_component['config']);
            $info_text = $_LANG['AD_COMPONENT'].' <strong>"'.$_component['title'].'"</strong> '.$_LANG['AD_SUCCESS'].$_LANG['AD_IS_UPDATE'];
            cmsCore::addSessionMessage($info_text, 'success');
            cmsCore::redirect('/admin/index.php?view=components');
        } else {
            cmsCore::addSessionMessage($error , 'error');
            cmsCore::redirectBack();
        }

    }

    //-------------------------- Удаление компонента ---------------------------
    if ($do == 'remove_component') {
        $component_id = cmsCore::request('id', 'int', '');

        if (!$component_id) { cmsCore::redirectBack(); }
        
        $com = $inCore->getComponentById($component_id);
        if (!cmsUser::isAdminCan('admin/components', $adminAccess)) { cpAccessDenied(); }
        if (!cmsUser::isAdminCan('admin/com_'.$com, $adminAccess)) { cpAccessDenied(); }

        if ($inCore->loadComponentInstaller($com)) {
            if (function_exists('remove_component_'. $com)) {
            	call_user_func('remove_component_'. $com);
            }
        }

        $inCore->removeComponent($component_id);

        cmsCore::addSessionMessage($_LANG['AD_COMPONENT_IS_DELETED'], 'success');
        cmsCore::redirect('/admin/index.php?view=components');
    }
    //==========================================================================

    //------------------------------- Плагины ----------------------------------
    //---------- Список плагинов готовых к установке или обновлению ------------
    if ($do == 'plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) { cpAccessDenied(); }

      	cpAddPathway($_LANG['AD_SETUP_PLUGINS']	, 'index.php?view=install&do=plugin');

        $new_plugins = $inCore->getNewPlugins();
        $upd_plugins = $inCore->getUpdatedPlugins();

        echo '<h3>'. $_LANG['AD_SETUP_PLUGINS'] .'</h3>';

        if (!$new_plugins && !$upd_plugins) {
            echo '<p>'. $_LANG['AD_NO_SEARCH_PLUGINS'] .'</p>';
            echo '<p>'. $_LANG['AD_IF_WANT_SETUP_PLUGINS'] .'</p>';
            echo '<p><a href="javascript:window.history.go(-1);" class="btn btn-default">'. $_LANG['BACK'] .'</a></p>';
            return;
        }

        if ($new_plugins) {
            echo '<div class="panel panel-default"><div class="panel-heading">'. $_LANG['AD_PLUGINS_SETUP'] .'</div><div class="panel-body">';
                pluginsList($new_plugins, $_LANG['AD_SETUP'], 'install_plugin');
            echo '</div></div>';
        }

        if ($upd_plugins) {
            echo '<div class="panel panel-default"><div class="panel-heading">'. $_LANG['AD_PLUGINS_UPDATE'] .'</div><div class="panel-body">';
                pluginsList($upd_plugins, $_LANG['AD_UPDATE'], 'upgrade_plugin');
            echo '</div></div>';
        }

        echo '<p><a href="javascript:window.history.go(-1);" class="btn btn-default">'. $_LANG['BACK'] .'</a></p>';
    }

    //--------------------------- Установка плагина ----------------------------
    if ($do == 'install_plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) { cpAccessDenied(); }

        cpAddPathway($_LANG['AD_SETUP_PLUGIN']	, 'index.php?view=install&do=plugin');

        $error = '';

        $plugin_id = cmsCore::request('id', 'str', '');

        if (!$plugin_id) { cmsCore::redirectBack(); }

        $plugin = $inCore->loadPlugin($plugin_id);

        if (!$plugin) { $error = $_LANG['AD_PLUGIN_FAILURE']	; }

        if (!$error && $plugin->install()) {
            cmsCore::addSessionMessage($_LANG['AD_PLUGIN'] .' <strong>"'. $plugin->info['title'] .'"</strong> '. $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_INSTALL'] .'. '. $_LANG['AD_ENABLE_PLUGIN'], 'success');
            cmsCore::redirect('/admin/index.php?view=plugins');
        }

        if ($error) { echo '<p style="color:red">'. $error .'</p>'; }

        echo '<p><a href="index.php?view=install&do=plugin">'. $_LANG['BACK'] .'</a></p>';
    }

    //-------------------------- Обновление плагина ----------------------------
    if ($do == 'upgrade_plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) { cpAccessDenied(); }

        cpAddPathway($_LANG['AD_UPDATE_PLUGIN'], 'index.php?view=install&do=plugin');

        $error = '';

        $plugin_id = cmsCore::request('id', 'str', '');

        if (empty($plugin_id)) { cmsCore::redirectBack(); }

        $plugin = $inCore->loadPlugin($plugin_id);

        if (!$plugin) { $error = $_LANG['AD_PLUGIN_FAILURE']; }

        if (!$error && $plugin->upgrade()) {
            cmsCore::addSessionMessage($_LANG['AD_PLUGIN'] .' <strong>"'. $plugin->info['title'] .'"</strong> '. $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_UPDATE'], 'success');
            cmsCore::redirect('/admin/index.php?view=plugins');
        }

        if ($error) { echo '<p style="color:red">'. $error .'</p>'; }

        echo '<p><a href="index.php?view=install&do=plugin">'. $_LANG['BACK'] .'</a></p>';
    }

    //--------------------------- Удаление плагина -----------------------------
    if ($do == 'remove_plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) { cpAccessDenied(); }
        
        $plugin_name = $inCore->getPluginById(cmsCore::request('id', 'int', 0));

        if (!$plugin_name) { cmsCore::redirectBack(); }
        
        $plugin = $inCore->loadPlugin($plugin_name);

        if (!$plugin) { $error = $_LANG['AD_PLUGIN_FAILURE']; }
        
        $plugin->uninstall();
        
        cmsCore::addSessionMessage($_LANG['AD_REMOVE_PLUGIN_OK'], 'success');
        cmsCore::redirect('/admin/index.php?view=plugins');
    }
    //==========================================================================
}
Esempio n. 21
0
function applet_userbanlist()
{
    $inCore = cmsCore::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    global $_LANG;
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/users', $adminAccess)) {
        cpAccessDenied();
    }
    $GLOBALS['cp_page_title'] = $_LANG['AD_BANLIST'];
    cpAddPathway($_LANG['AD_USERS'], 'index.php?view=users');
    cpAddPathway($_LANG['AD_BANLIST'], 'index.php?view=userbanlist');
    $do = cmsCore::request('do', 'str', 'list');
    $id = cmsCore::request('id', 'int', -1);
    $to = cmsCore::request('to', 'int', 0);
    // для редиректа обратно в профиль на сайт
    if ($to) {
        cmsUser::sessionPut('back_url', cmsCore::getBackURL());
    }
    if ($do == 'list') {
        $toolmenu[] = array('icon' => 'useradd.gif', 'title' => $_LANG['AD_TO_BANLIST_ADD'], 'link' => '?view=userbanlist&do=add');
        $toolmenu[] = array('icon' => 'edit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=userbanlist&do=edit&multiple=1');");
        $toolmenu[] = array('icon' => 'delete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:checkSel('?view=userbanlist&do=delete&multiple=1');");
        cpToolMenu($toolmenu);
        $fields[] = array('title' => 'id', 'field' => 'id', 'width' => '30');
        $fields[] = array('title' => $_LANG['AD_IS_ACTIVE'], 'field' => 'status', 'width' => '55', 'prc' => 'cpYesNo');
        $fields[] = array('title' => $_LANG['AD_BANLIST_USER'], 'field' => 'user_id', 'width' => '120', 'filter' => '12', 'prc' => 'cpUserNick');
        $fields[] = array('title' => $_LANG['AD_BANLIST_IP'], 'field' => 'ip', 'width' => '100', 'link' => '?view=userbanlist&do=edit&id=%id%', 'filter' => '12');
        $fields[] = array('title' => $_LANG['DATE'], 'field' => 'bandate', 'width' => '', 'fdate' => '%d/%m/%Y %H:%i:%s', 'filter' => '12');
        $fields[] = array('title' => $_LANG['AD_BANLIST_TIME'], 'field' => 'int_num', 'width' => '55');
        $fields[] = array('title' => '', 'field' => 'int_period', 'width' => '70');
        $fields[] = array('title' => $_LANG['AD_AUTOREMOVE'], 'field' => 'autodelete', 'width' => '90', 'prc' => 'cpYesNo');
        $actions[] = array('title' => $_LANG['EDIT'], 'icon' => 'edit.gif', 'link' => '?view=userbanlist&do=edit&id=%id%');
        $actions[] = array('title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_REMOVE_RULE'], 'link' => '?view=userbanlist&do=delete&id=%id%');
        cpListTable('cms_banlist', $fields, $actions, '1=1', 'ip DESC');
    }
    if ($do == 'delete') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbDelete('cms_banlist', $id);
            }
        } else {
            dbDeleteList('cms_banlist', cmsCore::request('item', 'array_int', array()));
        }
        cmsCore::redirect('?view=userbanlist');
    }
    if ($do == 'submit' || $do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $types = array('user_id' => array('user_id', 'int', 0), 'ip' => array('ip', 'str', ''), 'cause' => array('cause', 'str', ''), 'autodelete' => array('autodelete', 'int', 0), 'int_num' => array('int_num', 'int', 0), 'int_period' => array('int_period', 'str', '', create_function('$p', 'if(!in_array($p, array("MONTH","DAY","HOUR","MINUTE"))){ $p = "MINUTE"; } return $p;')));
        $items = cmsCore::getArrayFromRequest($types);
        $error = false;
        if (!$items['ip']) {
            $error = true;
            cmsCore::addSessionMessage($_LANG['AD_NEED_IP'], 'error');
        }
        if ($items['ip'] == $_SERVER['REMOTE_ADDR'] || $items['user_id'] == $inUser->id) {
            $error = true;
            cmsCore::addSessionMessage($_LANG['AD_ITS_YOUR_IP'], 'error');
        }
        if (cmsUser::userIsAdmin($items['user_id'])) {
            $error = true;
            cmsCore::addSessionMessage($_LANG['AD_ITS_ADMIN'], 'error');
        }
        if ($error) {
            cmsCore::redirectBack();
        }
        if ($do == 'update') {
            $inDB->update('cms_banlist', $items, $id);
            if (empty($_SESSION['editlist'])) {
                cmsCore::redirect('?view=userbanlist');
            } else {
                cmsCore::redirect('?view=userbanlist&do=edit');
            }
        }
        $inDB->insert('cms_banlist', $items);
        $back_url = cmsUser::sessionGet('back_url');
        cmsUser::sessionDel('back_url');
        cmsCore::redirect($back_url ? $back_url : '?view=userbanlist');
    }
    if ($do == 'add' || $do == 'edit') {
        $GLOBALS['cp_page_head'][] = '<script language="JavaScript" type="text/javascript" src="/admin/js/banlist.js"></script>';
        $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);');
        cpToolMenu($toolmenu);
        if ($do == 'add') {
            echo '<h3>' . $_LANG['AD_TO_BANLIST_ADD'] . '</h3>';
            cpAddPathway($_LANG['AD_TO_BANLIST_ADD']);
        } 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_banlist', "id = '{$item_id}'", '*');
            if (!$mod) {
                cmsCore::error404();
            }
            echo '<h3>' . $_LANG['AD_EDIT_RULE'] . ' ' . $ostatok . '</h3>';
            cpAddPathway($_LANG['AD_EDIT_RULE']);
        }
        ?>
	  <div style="margin-top:2px;padding:10px;border:dotted 1px silver; width:508px;background:#FFFFCC">
	  	<div style="font-weight:bold"><?php 
        echo $_LANG['ATTENTION'];
        ?>
!</div>
		<div><?php 
        echo $_LANG['AD_CAUTION_INFO_0'];
        ?>
</div>
		<div><?php 
        echo $_LANG['AD_CAUTION_INFO_1'];
        ?>
</div>
	  </div>
      <form id="addform" name="addform" method="post" action="index.php?view=userbanlist">
        <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
        <table width="530" border="0" cellspacing="5" class="proptable">
          <tr>
            <td width="150" valign="top"><div><strong><?php 
        echo $_LANG['AD_BANLIST_USER'];
        ?>
: </strong></div></td>
			<?php 
        if ($do == 'add' && $to) {
            $mod['user_id'] = $to;
            $mod['ip'] = $inDB->get_field('cms_users', 'id=' . $to, 'last_ip');
        }
        ?>
            <td valign="top">
				<select name="user_id" id="user_id" onchange="loadUserIp()" style="width: 250px;">
                    <option value="0" <?php 
        if (@(!$mod['user_id'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_WHITHOUT_USER'];
        ?>
</option>
                    <?php 
        if (isset($mod['user_id'])) {
            echo $inCore->getListItems('cms_users', $mod['user_id'], 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
        } else {
            echo $inCore->getListItems('cms_users', 0, 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
        }
        ?>
				</select>
            </td>
          </tr>
          <tr>
            <td valign="top"><strong><?php 
        echo $_LANG['AD_BANLIST_IP'];
        ?>
:</strong></td>
            <td valign="top"><input name="ip" type="text" id="ip" style="width: 244px;" value="<?php 
        echo @$mod['ip'];
        ?>
"/></td>
          </tr>
          <tr>
            <td valign="top"><strong><?php 
        echo $_LANG['AD_BANLIST_CAUSE'];
        ?>
:</strong></td>
            <td valign="top">
                <textarea name="cause" style="width:240px" rows="5"><?php 
        echo @$mod['cause'];
        ?>
</textarea>
            </td>
          </tr>
		  <?php 
        $forever = false;
        if (!@$mod['int_num']) {
            $forever = true;
        }
        ?>
          <tr>
            <td valign="top"><strong><?php 
        echo $_LANG['AD_BAN_FOREVER'];
        ?>
</strong></td>
            <td valign="top"><input type="checkbox" name="forever" value="1" <?php 
        if ($forever) {
            echo 'checked="checked"';
        }
        ?>
 onclick="$('tr.bantime').toggle();"/></td>
          </tr>
          <tr class="bantime">
            <td valign="top"><strong><?php 
        echo $_LANG['AD_BAN_FOR_TIME'];
        ?>
</strong> </td>

            <td valign="top"><p>
            <input name="int_num" type="text" id="int_num" size="5" value="<?php 
        echo @(int) $mod['int_num'];
        ?>
"/>
              <select name="int_period" id="int_period">
                <option value="MINUTE"  <?php 
        if (@mb_strstr($mod['int_period'], 'MINUTE')) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['MINUTE10'];
        ?>
</option>]
                <option value="HOUR"  <?php 
        if (@mb_strstr($mod['int_period'], 'HOUR')) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['HOUR10'];
        ?>
</option>
                <option value="DAY" <?php 
        if (@mb_strstr($mod['int_period'], 'DAY')) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['DAY10'];
        ?>
</option>
                <option value="MONTH" <?php 
        if (@mb_strstr($mod['int_period'], 'MONTH')) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['MONTH10'];
        ?>
</option>
              </select>
            </p>
            <p><label><input name="autodelete" type="checkbox" id="autodelete" value="1" <?php 
        if ($mod['autodelete']) {
            echo 'checked="checked"';
        }
        ?>
 /> <?php 
        echo $_LANG['AD_REMOVE_BAN'];
        ?>
</label></p>
            </td>
          </tr>
		  <?php 
        if ($forever) {
            ?>
<script type="text/javascript">$('tr.bantime').hide();</script><?php 
        }
        ?>
        </table>
        <p>
          <label>
          <input name="add_mod" type="submit" id="add_mod" <?php 
        if ($do == 'add') {
            echo 'value="' . $_LANG['AD_TO_BANLIST_ADD'] . '"';
        } else {
            echo 'value="' . $_LANG['SAVE'] . '"';
        }
        ?>
 />
          </label>
          <label><span style="margin-top:15px">
          <input name="back" type="button" id="back" value="<?php 
        echo $_LANG['CANCEL'];
        ?>
" onclick="window.history.back();"/>
          </span></label>
          <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 
    }
}
Esempio n. 22
0
function clubs() {
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB   = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();

    global $_LANG;

    $model = new cms_model_clubs();

    $inPhoto = $model->initPhoto();

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

	// js только авторизованным
	if($inUser->id){
		$inPage->addHeadJS('components/clubs/js/clubs.js');
	}

	$pagetitle = $inCore->getComponentTitle();

	$id   = cmsCore::request('id', 'int', 0);
	$do   = $inCore->do;
	$page = cmsCore::request('page', 'int', 1);

	$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);
	$inPage->addPathway($pagetitle, '/clubs');
    $inPage->addHeadJsLang(array('NO_PUBLISH','EDIT_PHOTO','YOU_REALLY_DELETE_PHOTO','YOU_REALLY_DELETE_ALBUM','RENAME_ALBUM','ALBUM_TITLE','ADD_PHOTOALBUM','REALY_EXIT_FROM_CLUB','JOINING_CLUB','SEND_MESSAGE','CREATE','CREATE_CLUB','SEND_INVITE_CLUB','YOU_NO_SELECT_USER'));

//////////////////////// КЛУБЫ ПОЛЬЗОВАТЕЛЯ/////////////////////////////////////
if ($do == 'user_clubs') {
    if (!cmsCore::isAjax()) { return false; }

    $inPage->displayLangJS(array('CREATE','CREATE_CLUB'));

    $user_id = cmsCore::request('user_id', 'int', $inUser->id);

    $user = cmsUser::getShortUserData($user_id);
    if (!$user) { return false; }

    // получаем клубы, в которых пользователь админ
    $model->whereAdminIs($user['id']);
   	$inDB->orderBy('c.pubdate', 'DESC');
    $clubs = $model->getClubs();

    // получаем клубы, в которых состоит пользователь
    $inDB->addSelect('uc.role');
    $inDB->addJoin("INNER JOIN cms_user_clubs uc ON uc.club_id = c.id AND uc.user_id = '{$user['id']}'");
   	$inDB->orderBy('uc.role', 'DESC, uc.pubdate DESC');
    $inclubs = $model->getClubs();

	cmsPage::initTemplate('components', 'com_clubs_user')->
            assign('can_create', (($inUser->id == $user['id']) && ($model->config['cancreate'] || $inUser->is_admin)))->
            assign('clubs', array_merge($clubs, $inclubs))->
            assign('user', $user)->
            assign('my_profile', $user['id'] == $inUser->id)->
            display();

}
//////////////////////// ВСЕ КЛУБЫ /////////////////////////////////////////////
if ($do=='view'){

	$inDB->orderBy('is_vip', 'DESC, rating DESC');
	$inDB->limitPage($page, $model->config['perpage']);

	$total = $model->getClubsCount();

        $clubs = $model->getClubs();
	if (!$clubs && $page > 1) { return false; }
        
        if ($page > 1) {
            foreach ($clubs as $c) {
                $keys[] = $c['title'];
            }
            $inPage->setKeywords(implode(',', $keys));
        }

	cmsPage::initTemplate('components', 'com_clubs_view')->
            assign('pagetitle', $pagetitle)->
            assign('can_create', ($inUser->id && $model->config['cancreate'] || $inUser->is_admin))->
            assign('clubs', $clubs)->
            assign('total', $total)->
            assign('pagination', cmsPage::getPagebar($total, $page, $model->config['perpage'], '/clubs/page-%page%'))->
            display();

}
/////////////////////// ПРОСМОТР КЛУБА /////////////////////////////////////////
if ($do=='club'){
    $club = $model->getClub($id);
    if (!$club) { return false; }

    if (!$club['published'] && !$inUser->is_admin) { return false; }

    $inPage->setTitle($club['pagetitle'] ? $club['pagetitle'] : $club['title']);
    $inPage->setKeywords($club['meta_keys'] ? $club['meta_keys'] : $club['title']);
    if (!$club['meta_desc']) {
        if ($club['description']) {
            $inPage->setDescription(crop($club['description']));
        } else {
            $inPage->setDescription($club['title']);
        }
    } else {
        $inPage->setDescription($club['meta_desc']);
    }
        
    $inPage->addPathway($club['title']);
    $inPage->addHeadJsLang(array('NEW_POST_ON_WALL','CONFIRM_DEL_POST_ON_WALL'));

    // Инициализируем участников клуба
    $model->initClubMembers($club['id']);
    // права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub('member');

	// Приватный или публичный клуб
    $is_access = true;
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        $is_access = false;
    }

	// Общее количество участников
    $club['members'] = $model->club_total_members;
	// Общее количество участников
    $club['moderators'] = $model->club_total_moderators;

	// Массив членов клуба
	if($club['members']){
		$inDB->limit($model->config['club_perpage']);
		$club['members_list'] = $model->getClubMembers($club['id'], 'member');
	} else { $club['members_list'] =  array(); }

	// Массив модераторов клуба
	if($club['moderators']){
		$club['moderators_list'] = $model->getClubMembers($club['id'], 'moderator');
	}

	// Стена клуба
	// количество записей на стене берем из настроек
	$inDB->limitPage(1, $model->config['wall_perpage']);
    $club['wall_html'] = cmsUser::getUserWall($club['id'], 'clubs', ($is_moder || $is_admin), ($is_moder || $is_admin));

	/////////////////////////////////////////////
	//////////// ПОСТЫ БЛОГА КЛУБА //////////////
	/////////////////////////////////////////////
	if ($club['enabled_blogs']){

		$inBlog = $model->initBlog();

		$inBlog->whereBlogUserIs($club['id']);

		$club['total_posts'] = $inBlog->getPostsCount($is_admin || $is_moder);

		$inDB->addSelect('b.user_id as bloglink');

		$inDB->orderBy('p.pubdate', 'DESC');

		$inDB->limit($model->config['club_posts_perpage']);

		$club['blog_posts'] = $inBlog->getPosts(($is_admin || $is_moder), $model, true);

	}

	/////////////////////////////////////////////
	//////////// ФОТОАЛЬБОМЫ КЛУБА //////////////
	/////////////////////////////////////////////
	if ($club['enabled_photos']){

		// Общее количество альбомов
		$club['all_albums'] = $inDB->rows_count('cms_photo_albums', "NSDiffer = 'club{$club['id']}' AND user_id = '{$club['id']}' AND parent_id > 0");

		// получаем альбомы
		if($club['all_albums']){
			$inDB->limit($model->config['club_album_perpage']);
			$inDB->orderBy('f.pubdate', 'DESC');
			$club['photo_albums'] = $inPhoto->getAlbums(0, 'club'.$club['id']);
		} else {
			$club['photo_albums'] = array();
		}

	}

	// Получаем плагины
        $plugins = cmsCore::callTabEventPlugins('GET_SINGLE_CLUB', $club);

	cmsPage::initTemplate('components', 'com_clubs_view_club')->
            assign('club', $club)->
            assign('is_access', $is_access)->
            assign('user_id', $inUser->id)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('plugins', $plugins)->
            assign('is_member', $is_member)->
            assign('is_photo_karma_enabled', ((($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false))->
            assign('is_blog_karma_enabled', ((($inUser->karma >= $club['blog_min_karma']) && $is_member) ? true : false))->
            assign('cfg', $model->config)->
            display();

}
///////////////////////// СОЗДАНИЕ КЛУБА ///////////////////////////////////////
if ($do == 'create'){

    if(!cmsCore::isAjax()) { return false; }

    if(!$inUser->id){ return false; }

    $can_create = $model->canCreate();

	// показываем форму
    if (!cmsCore::inRequest('create') ){

        cmsPage::initTemplate('components', 'com_clubs_create')->
                assign('can_create', $can_create)->
                assign('last_message', $model->last_message)->
                display();

		cmsCore::jsonOutput(array('error' => false,
								  'can_create' => (bool)$can_create,
								  'html' => ob_get_clean()));
    }

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

        if (!$can_create){ return false; }

        $title    = $inCore->request('title', 'str');
        $clubtype = $inCore->request('clubtype', 'str');

        if (!$title || !in_array($clubtype, array('public','private'))){
			cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_REQ_TITLE']));
		}

		if ($inDB->get_field('cms_clubs', "LOWER(title) = '".mb_strtolower($title)."'", 'id')){
			cmsCore::jsonOutput(array('error' => true, 'text' => $_LANG['CLUB_EXISTS']));
		}

		if(!cmsUser::checkCsrfToken()) { return false; }

		$club_id = $model->addClub(array('admin_id'=>$inUser->id,
										 'title'=>$title,
										 'clubtype'=>$clubtype,
										 'create_karma'=>$inUser->karma,
										 'enabled_blogs'=>$model->config['enabled_blogs'],
										 'enabled_photos'=>$model->config['enabled_photos']));

		if($club_id){
			//регистрируем событие
			cmsActions::log('add_club', array(
						'object' => $title,
						'object_url' => '/clubs/'.$club_id,
						'object_id' => $club_id,
						'target' => '',
						'target_url' => '',
						'target_id' => 0,
						'description' => ''
			));
		}

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

		cmsCore::jsonOutput(array('error' => false,
								'club_id' => $club_id));

    }

}

///////////////////////// НАСТРОЙКИ КЛУБА //////////////////////////////////////
if ($do == 'config'){

    if (!$inUser->id){ return false; }

    $club = $model->getClub($id);
    if (!$club){ return false; }

    // Инициализируем участников клуба
    $model->initClubMembers($club['id']);
    // настраивать клуб могут только администраторы
    $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    if (!$is_admin){ return false; }

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

        if (!cmsUser::checkCsrfToken()) { return false; }

        $description = cmsCore::badTagClear(cmsCore::request('description', 'html', ''));
        $new_club['description']      = $inDB->escape_string($description);
        $new_club['title']            = cmsCore::request('title', 'str', $club['title']);
        $new_club['clubtype']         = cmsCore::request('clubtype', 'str', 'public');
        $new_club['maxsize']          = cmsCore::request('maxsize', 'int', 0);
        $new_club['blog_min_karma']   = cmsCore::request('blog_min_karma', 'int', 0);
        $new_club['photo_min_karma']  = cmsCore::request('photo_min_karma', 'int', 0);
        $new_club['album_min_karma']  = cmsCore::request('album_min_karma', 'int', 0);
        $new_club['blog_premod']      = cmsCore::request('blog_premod', 'int', 0);
        $new_club['photo_premod']     = cmsCore::request('photo_premod', 'int', 0);
        $new_club['join_karma_limit'] = cmsCore::request('join_karma_limit', 'int', 0);
        $new_club['join_min_karma']   = cmsCore::request('join_min_karma', 'int', 0);
        if ($model->config['seo_user_access'] || $inUser->is_admin) {
            $new_club['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
            $new_club['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
            $new_club['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
        }

        // загружаем изображение клуба
        $new_imageurl = $model->uploadClubImage($club['imageurl']);
        $new_club['imageurl'] = @$new_imageurl['filename'] ? $new_imageurl['filename'] : $club['imageurl'];

        // Сохраняем
        $model->updateClub($club['id'], $new_club);

        // Обновляем ленту активности
        cmsActions::updateLog('add_club', array('object' => $new_club['title']), $club['id']);
        cmsActions::updateLog('add_club_user', array('object' => $new_club['title']), $club['id']);

        if ($inUser->is_admin && IS_BILLING){
            $is_vip    = cmsCore::request('is_vip', 'int', 0);
            $join_cost = cmsCore::request('join_cost', 'int', 0);
            $model->setVip($club['id'], $is_vip, $join_cost);
        }

        $moders  = cmsCore::request('moderslist', 'array_int', array());
        $members = cmsCore::request('memberslist', 'array_int', array());

        $all_users = array_merge($members, $moders);

        // Сохраняем пользователей
        $model->clubSaveUsers($club['id'], $all_users);
        $model->clubSetRole($club['id'], $moders, 'moderator');

        // Кешируем количество
        $model->setClubMembersCount($club['id']);

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

        cmsCore::redirect('/clubs/'.$club['id']);

    }

    if (!cmsCore::inRequest('save')){

        // Заголовки и пафвей
        $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
        $inPage->addPathway($_LANG['CONFIG_CLUB']);
        $inPage->setTitle($_LANG['CONFIG_CLUB']);

		// Список друзей, отсутствующих в клубе
		$friends_list = '';
		// массив id друзей не в клубе
		$friends_ids  = array();

		// Получаем список друзей
		$friends = cmsUser::getFriends($inUser->id);
		// Получаем список участников
		$members = $model->getClubMembersIds();
		// Формируем список друзей, которые еще не в клубе
		foreach($friends as $key=>$friend){
			if (!in_array($friend['id'], $members) && $friend['id'] != $club['admin_id']){
				$friends_list .= '<option value="'.$friend['id'].'">'.$friend['nickname'].'</option>';
				$friends_ids[] = $friend['id'];
			}
		}

		// Получаем модераторов клуба
		$moderators = $model->getClubMembersIds('moderator');
		// формируем список друзья не в клубе + участники клуба кроме модераторов
		$fr_plus_members = $members ? array_merge($friends_ids, $members) : $friends_ids;
		// Убираем модераторов если они есть
		$fr_plus_members = $moderators ? array_diff($fr_plus_members, $moderators) : $fr_plus_members;

		// Формируем список option друзей (которые еще не в этом клубе) и участников
		if ($fr_plus_members) { $fr_members_list = cmsUser::getAuthorsList($fr_plus_members); } else { $fr_members_list = ''; }
		// Формируем список option участников клуба
        if ($moderators) { $moders_list = cmsUser::getAuthorsList($moderators); } else { $moders_list = ''; }
        if ($members) { $members_list = cmsUser::getAuthorsList($members); } else { $members_list = ''; }

        cmsPage::initTemplate('components', 'com_clubs_config')->
            assign('club', $club)->
            assign('moders_list', $moders_list)->
            assign('members_list', $members_list)->
            assign('friends_list', $friends_list)->
            assign('fr_members_list', $fr_members_list)->
            assign('is_billing', IS_BILLING)->
            assign('is_admin', $inUser->is_admin)->
            assign('cfg', $model->config)->
            display();
    }

}
///////////////////////// ВЫХОД ИЗ КЛУБА ///////////////////////////////////////////
if ($do == 'leave'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// Выйти из клуба могут только его участники
    $is_admin  = $inUser->id == $club['admin_id'];
    $is_member = $model->checkUserRightsInClub();
	if ($is_admin || !$is_member){ cmsCore::halt(); }

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

		if(!cmsUser::checkCsrfToken()) { cmsCore::halt(); }

		cmsCore::callEvent('LEAVE_CLUB', $club);

        $model->removeUserFromClub($club['id'], $inUser->id);
		// Пересчитываем рейтинг
        $model->setClubRating($club['id']);
		// Кешируем (пересчитываем) количество участников
		$model->setClubMembersCount($club['id']);
		// Добавляем событие в ленте активности
		cmsActions::removeObjectLog('add_club_user', $club['id'], $inUser->id);
		cmsCore::addSessionMessage($_LANG['YOU_LEAVE_CLUB'].'"'.$club['title'].'"', 'success');

		cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/clubs/'.$club['id']));

    }

}
///////////////////////// ВСТУПЛЕНИЕ В КЛУБ ////////////////////////////////////
if ($do == 'join'){

	if (!$inUser->id){ cmsCore::halt(); }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	// В приватный клуб участников добавляет администратор
    if ($club['clubtype']=='private'){ cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// проверяем наличие пользователя в клубе
    $is_admin  = $inUser->id == $club['admin_id'];
    $is_member = $model->checkUserRightsInClub();
	if ($is_admin || $is_member){ cmsCore::halt(); }

    // Проверяем ограничения на количество участников
    if ($club['maxsize'] && ($model->club_total_members >= $club['maxsize']) && !$inUser->is_admin){
        cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['CLUB_SIZE_LIMIT']));
    }
    // Проверяем ограничения по карме на вступление
    if($club['join_karma_limit'] && ($inUser->karma < $club['join_min_karma']) && !$inUser->is_admin){

        cmsCore::jsonOutput(array('error' => true, 'text'  => '<p><strong>'.$_LANG['NEED_KARMA_TEXT'].'</strong></p><p>'.$_LANG['NEEDED'].' '.$club['join_min_karma'].', '.$_LANG['HAVE_ONLY'].' '.$inUser->karma.'.</p><p>'.$_LANG['WANT_SEE'].' <a href="/users/'.$inUser->id.'/karma.html">'.$_LANG['HISTORY_YOUR_KARMA'].'</a>?</p>'));

    }

    //
    // Обработка заявки
    //
    if (cmsCore::inRequest('confirm')){

		cmsCore::callEvent('JOIN_CLUB', $club);

        //списываем оплату если клуб платный
        if (IS_BILLING && $club['is_vip'] && $club['join_cost'] && !$inUser->is_admin){
            if ($inUser->balance >= $club['join_cost']){
                //если средств на балансе хватает
                cmsBilling::pay($inUser->id, $club['join_cost'], sprintf($_LANG['VIP_CLUB_BUY_JOIN'], $club['title']));
            } else {
                //недостаточно средств, создаем тикет
                //и отправляем оплачивать
                $billing_ticket = array(
                    'action' => sprintf($_LANG['VIP_CLUB_BUY_JOIN'], $club['title']),
                    'cost'   => $club['join_cost'],
                    'amount' => $club['join_cost'] - $inUser->balance,
                    'url'    => $_SERVER['REQUEST_URI'].'?confirm=1'
                );
                cmsUser::sessionPut('billing_ticket', $billing_ticket);
				cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/billing/pay'));
            }
        }

        //добавляем пользователя в клуб
        $model->addUserToClub($club['id'], $inUser->id);
		// Пересчитываем рейтинг клуба
        $model->setClubRating($club['id']);
		// Кешируем (пересчитываем) количество участников
		$model->setClubMembersCount($club['id']);

		//регистрируем событие
		cmsActions::log('add_club_user', array(
						'object' => $club['title'],
						'object_url' => '/clubs/'.$club['id'],
						'object_id' => $club['id'],
						'target' => '',
						'target_url' => '',
						'target_id' => 0,
						'description' => ''
		));

		cmsCore::addSessionMessage($_LANG['YOU_JOIN_CLUB'].'"'.$club['title'].'"', 'success');

		if($_SERVER['REQUEST_URI'] != '/clubs/'.$club['id'].'/join.html'){
			cmsCore::redirect('/clubs/'.$club['id']);
		} else {
	        cmsCore::jsonOutput(array('error' => false, 'redirect'  => '/clubs/'.$club['id']));
		}

    }

    //
    // Форма подтверждения заявки
    //
    if (!cmsCore::inRequest('confirm')){

        $text = '<p>'.$_LANG['YOU_REALY_JOIN_TO'].' <strong>"'.$club['title'].'"</strong>?</p>';
        if ($club['is_vip'] && $club['join_cost'] && !$inUser->is_admin){
            $text .= '<p>'.$_LANG['VIP_CLUB_JOIN_COST'].' &mdash; <strong>'.$club['join_cost'].' '.$_LANG['BILLING_POINT10'].'</strong></p>';
        }

        cmsCore::jsonOutput(array('error' => false, 'text'  => $text));

    }

}
///////////////////// РАССЫЛКА СООБЩЕНИЯ УЧАСТНИКАМ ////////////////////////////
if ($do == 'send_message'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// Расылать могут только участники и администраторы
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
	if (!$is_admin){ cmsCore::halt(); }

	if (!cmsCore::inRequest('gosend')){

        $inPage->setRequestIsAjax();

		cmsPage::initTemplate('components', 'com_clubs_messages_member')->
                assign('club', $club)->
                assign('bbcodetoolbar', cmsPage::getBBCodeToolbar('message'))->
                assign('smilestoolbar', cmsPage::getSmilesPanel('message'))->
                display();

		cmsCore::jsonOutput(array('error' => false,'html'  => ob_get_clean()));

	} else {

		// Здесь не эскейпим, в методе sendMessage эскейпится
		$message = cmsCore::parseSmiles(cmsCore::request('content', 'html', ''), true);

		$moderators_list = $model->getClubMembersIds('moderator');
		$members_list    = $model->getClubMembersIds();
		$result_list 	 = cmsCore::inRequest('only_mod') ? $moderators_list : $members_list;

		if (mb_strlen($message)<3){
			cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['ERR_SEND_MESS']));
		}
		if (!$result_list){
			cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['ERR_SEND_MESS_NO_MEMBERS']));
		}

        if (!cmsUser::checkCsrfToken()) { return false; }

		$message = str_replace('%club%', '<a href="/clubs/'.$club['id'].'">'.$club['title'].'</a>', $_LANG['MESSAGE_FROM ADMIN']).$message;

		cmsUser::sendMessages(USER_UPDATER, $result_list, $message);

		$info = cmsCore::inRequest('only_mod') ? $_LANG['SEND_MESS_TO_MODERS_OK'] : $_LANG['SEND_MESS_TO_MEMBERS_OK'];

		cmsCore::jsonOutput(array('error' => false, 'text' => $info));

	}

}

///////////////////////// ПРИГЛАСИТЬ ДРУЗЕЙ В КЛУБ /////////////////////////////
if ($do == 'join_member'){

    if (!$inUser->id) { return false; }

    if (!cmsCore::isAjax()) { return false; }

	$club = $model->getClub($id);
	if(!$club){	cmsCore::halt(); }

	if (!$club['published'] && !$inUser->is_admin) { cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// Расылать могут только участники и администраторы
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_member = $model->checkUserRightsInClub();
	if (!$is_admin && !$is_member){ cmsCore::halt(); }
	// В приватный клуб приглашения не рассылаем
    if ($club['clubtype']=='private'){ cmsCore::halt(); }

	// Получаем список друзей
	$friends = cmsUser::getFriends($inUser->id);
	// Получаем список участников
	$members = $model->getClubMembersIds();
	// Проверяем наличие друга в списке участников клуба или является ли он администратором
	foreach($friends as $key=>$friend){
		if (in_array($friend['id'], $members) || $friend['id'] == $club['admin_id']) { unset($friends[$key]); }
	}
	// Если нет друзей или все друзья уже в этом клубе, то выводим ошибку и возвращаемся назад
	if (!$friends){
		cmsCore::jsonOutput(array('error' => true, 'text'  => $_LANG['SEND_INVITE_ERROR']));
	}

	// показываем форму для приглашения
	if (!cmsCore::inRequest('join')){

		// Выводим шаблон
		cmsPage::initTemplate('components', 'com_clubs_join_member')->
                assign('club', $club)->
                assign('friends', $friends)->
                display();

		cmsCore::jsonOutput(array('error' => false,'html'  => ob_get_clean()));

	} else { // Приглашаем

	  	$users = cmsCore::request('users', 'array_int', array());

		if ($users){

			$club_link = '<a href="/clubs/'.$club['id'].'">'.$club['title'].'</a>';
			$user_link = cmsUser::getProfileLink($inUser->login, $inUser->nickname);
			$link_join = '<a href="/clubs/'.$club['id'].'">'.$_LANG['JOIN_CLUB'] .'</a>';

			$message   = str_replace(array('%user%','%club%','%link_join%'),
                                     array($user_link,$club_link,$link_join), $_LANG['INVITE_CLUB_TEXT']);

			cmsUser::sendMessages(USER_UPDATER, $users, $message);

		}

		cmsCore::jsonOutput(array('error' => false, 'text' => $_LANG['SEND_INVITE_OK']));

	}

}
///////////////////////// ПРОСМОТР УЧАСТНИКОВ //////////////////////////////////
if ($do=='members'){

	$club = $model->getClub($id);
	if(!$club){ return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

    $inPage->setTitle($_LANG['CLUB_MEMBERS'].' - '.$club['title']);
    $inPage->setDescription($_LANG['CLUB_MEMBERS'].' - '.$club['title']);
    $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
    $inPage->addPathway($_LANG['CLUB_MEMBERS'].' - '.$club['title']);

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub();

	// Приватный или публичный клуб
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        return false;
    }

	// Общее количество участников
    $total_members = $model->club_total_members;

	// Массив членов клуба
	if($total_members){
		$inDB->limitPage($page, $model->config['member_perpage']);
		$members = $model->getClubMembers($club['id']);
		if(!$members) { return false; }
	} else { return false; }

	$pagebar = cmsPage::getPagebar($total_members, $page, $model->config['member_perpage'], '/clubs/%id%/members-%page%', array('id'=>$club['id']));

	cmsPage::initTemplate('components', 'com_clubs_view_member')->
            assign('pagebar', $pagebar)->
            assign('page', $page)->
            assign('members', $members)->
            assign('club', $club)->
            assign('total_members', $total_members)->
            display();

}
////////////////////////////// ВСЕ АЛЬБОМЫ КЛУБА  //////////////////////////////
if ($do=='view_albums'){

	$club = $model->getClub($id);
	if(!$club){ return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	$pagetitle = $_LANG['PHOTOALBUMS'].' - '.$club['title'];

    $inPage->setTitle($pagetitle);
    $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
    $inPage->addPathway($_LANG['PHOTOALBUMS']);

    // Инициализируем участников клуба
    $model->initClubMembers($club['id']);
    // права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub('member');

    $is_karma_enabled = (($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false;

	// Приватный или публичный клуб
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        return false;
    }

	$inDB->orderBy('f.pubdate', 'DESC');
	$club['photo_albums'] = $inPhoto->getAlbums(0, 'club'.$club['id']);
	if(!$club['photo_albums']) { return false; }
        
        // SEO
        $inPage->setDescription($pagetitle);
        $keys = array($club['title'], $_LANG['PHOTOALBUMS']);
        foreach ($club['photo_albums'] as $p) {
            $keys[] = $p['title'];
        }
        $inPage->setKeywords(implode(',', $keys));

	cmsPage::initTemplate('components', 'com_clubs_albums')->
            assign('club', $club)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('is_karma_enabled', $is_karma_enabled)->
            assign('show_title', true)->
            assign('pagetitle', $pagetitle)->
            display();

}
///////////////////////// ПРОСМОТР АЛЬБОМА КЛУБА ///////////////////////////////
if ($do=='view_album'){

	// Получаем альбом
	$album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null);
	if (!$album) { return false; }

	// Неопубликованные альбомы показываем только админам
	if (!$album['published'] && !$inUser->is_admin) { return false; }
        
        if ($album['NSDiffer'] != 'club'. $album['user_id']) { return false; }

	// получаем клуб
	$club = $model->getClub($album['user_id']);
	if(!$club) { return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub();

	// Приватный или публичный клуб
    if ($club['clubtype']=='private' && (!$is_admin && !$is_moder && !$is_member)){
        return false;
    }

	$hidden = (bool)($is_admin || $is_moder);

	// Устанавливаем альбом
	$inPhoto->whereAlbumIs($album['id']);

    // Общее количество фото по заданным выше условиям
    $total = $inPhoto->getPhotosCount($hidden);

    //устанавливаем сортировку
    $inDB->orderBy('f.id', 'DESC');

    //устанавливаем номер текущей страницы и кол-во фото на странице
    $inDB->limitPage($page, $model->config['photo_perpage']);

    $photos = $inPhoto->getPhotos($hidden);
    if (!$photos && $page > 1) { cmsCore::error404(); }

    $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
    $inPage->addPathway($album['title'], '/clubs/photoalbum'.$album['id']);
    $inPage->setTitle($album['title']);
    $inPage->setDescription($album['title'].' - '.$_LANG['CLUB_PHOTO_ALBUM'].' "'.$club['title'].'"');
    
    $keys = array($album['title'], $club['title']);
    if ($photos) {
        foreach ($photos as $p) {
            $keys[] = $p['title'];
        }
    }
    $inPage->setKeywords(implode(',', $keys));

    cmsPage::initTemplate('components', 'com_clubs_view_album')->
            assign('club', $club)->
            assign('total', $total)->
            assign('album', $album)->
            assign('photos', $photos)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('is_member', $is_member)->
            assign('cfg', $model->config)->
            assign('pagebar', cmsPage::getPagebar($total, $page, $model->config['photo_perpage'], '/clubs/photoalbum'.$album['id'].'/page-%page%'))->
            display();

}
///////////////////////// УДАЛЕНИЕ АЛЬБОМА /////////////////////////////////////
if ($do=='delete_album'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

    if(!cmsUser::checkCsrfToken()) { return false; }

	$album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null);
	if (!$album) { cmsCore::halt(); }

	$club = $model->getClub($album['user_id']);
	if(!$club) { cmsCore::halt(); }

	$model->initClubMembers($club['id']);

    $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder = $model->checkUserRightsInClub('moderator');

	if(!$is_admin && !$is_moder) { cmsCore::halt(); }

	$inPhoto->deleteAlbum($album['id'], 'club'.$club['id'], $model->initUploadClass());

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

	cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/'.$club['id']));

}
//////////////////////////////// ПРОСМОТР ФОТО /////////////////////////////////
if ($do=='view_photo'){

	// Получаем фото
	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { return false; }

	$photo = cmsCore::callEvent('VIEW_CLUB_PHOTO', $photo);

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { return false; }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub();
	$is_author = $photo['user_id'] == $inUser->id;

	if (!$photo['published'] && !$is_admin && !$is_moder) { return false; }

	// Фото приватного клуба показываем только участникам
    if ($club['clubtype']=='private' && !$is_member && !$is_admin){ return false; }

    $inPage->addPathway($club['title'], '/clubs/'. $club['id']);
    $inPage->addPathway($photo['cat_title'], '/clubs/photoalbum'.$photo['album_id']);
    $inPage->addPathway($photo['title']);
    $inPage->setTitle($photo['pagetitle'] ? $photo['pagetitle'] : $photo['title']);
    $inPage->setKeywords($photo['meta_keys'] ? $photo['meta_keys'] : $photo['title']);
    if (!$photo['meta_desc']) {
        if ($photo['description']) {
            $inPage->setDescription(crop($photo['description']));
        } else {
            $inPage->setDescription($photo['title']);
        }
    } else {
        $inPage->setDescription($photo['meta_desc']);
    } 

	// ссылки вперед назад
	$photo['nextid'] = $inDB->get_fields('cms_photo_files', 'id<'.$photo['id'].' AND album_id = '.$photo['album_id'], 'id, file, title', 'id DESC');
	$photo['previd'] = $inDB->get_fields('cms_photo_files', 'id>'.$photo['id'].' AND album_id = '.$photo['album_id'], 'id, file, title', 'id ASC');

	// кнопки голосования
	$photo['karma_buttons'] = cmsKarmaButtons('club_photo', $photo['id'], $photo['rating'], $is_author);

	// Обновляем кол-во просмотров
	if(!$is_author){
		$inDB->setFlag('cms_photo_files', $photo['id'], 'hits', $photo['hits']+1);
	}

	// выводим в шаблон
    cmsPage::initTemplate('components', 'com_clubs_view_photo')->
            assign('club', $club)->
            assign('photo', $photo)->
            assign('is_admin', $is_admin)->
            assign('is_moder', $is_moder)->
            assign('is_exists_original', (file_exists(PATH.'/images/photos/'. $photo['file'])))->
            assign('is_author', $is_author)->
            display();

	//если есть, выводим комментарии
	if ($photo['comments'] && $inCore->isComponentEnable('comments')) {
            cmsCore::includeComments();
            comments('club_photo', $photo['id'], array(), $is_author);
	}

}
////////////////////////////// УДАЛИТЬ ФОТО ////////////////////////////////////
if ($do=='delete_photo'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	if(!cmsUser::checkCsrfToken()) { return false; }

	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { cmsCore::halt(); }

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { cmsCore::halt(); }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder = $model->checkUserRightsInClub('moderator');

	// удалять могут только модераторы и администраторы
	if(!$is_admin && !$is_moder) { cmsCore::halt(); }

	$inPhoto->deletePhoto($photo, $model->initUploadClass());

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

	cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/photoalbum'.$photo['album_id']));

}
///////////////////////// РЕДАКТИРОВАТЬ ФОТО ///////////////////////////////////
if ($do=='edit_photo'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { cmsCore::halt(); }

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { cmsCore::halt(); }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
	$is_author = $photo['user_id'] == $inUser->id;

	if(!$is_admin && !$is_moder && !$is_author) { cmsCore::halt(); }

	if (!cmsCore::inRequest('edit_photo')){

		cmsPage::initTemplate('components', 'com_photos_edit')->
                assign('photo', $photo)->
                assign('form_action', '/clubs/editphoto'.$photo['id'].'.html')->
                assign('no_tags', true)->
                assign('is_admin', ($is_admin || $is_moder))->
                display();

		cmsCore::jsonOutput(array('error' => false, 'html' => ob_get_clean()));

	} else {

		$mod['title']       = cmsCore::request('title', 'str', '');
		$mod['title']       = $mod['title'] ? $mod['title'] : $photo['title'];
		$mod['description'] = cmsCore::request('description', 'str', '');
		$mod['comments']    = ($is_admin || $is_moder) ? cmsCore::request('comments', 'int') : $photo['comments'];
                
                if ($model->config['seo_user_access'] || $inUser->is_admin) {
                    $mod['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
                    $mod['meta_keys'] = cmsCore::request('meta_keys', 'str', '');
                    $mod['meta_desc'] = cmsCore::request('meta_desc', 'str', '');
                }

		$file = $model->initUploadClass()->uploadPhoto($photo['file']);
		$mod['file'] = $file['filename'] ? $file['filename'] : $photo['file'];

		$inPhoto->updatePhoto($mod, $photo['id']);

		$description = '<a href="/clubs/photo'.$photo['id'].'.html" class="act_photo"><img border="0" src="/images/photos/small/'.$mod['file'].'" /></a>';

		cmsActions::updateLog('add_photo_club', array('object' => $mod['title'], 'description' => $description), $photo['id']);

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

		cmsCore::jsonOutput(array('error' => false, 'redirect' => '/clubs/photo'.$photo['id'].'.html'));

	}

}
/////////////////////////////// PHOTO PUBLISH //////////////////////////////////
if ($do=='publish_photo'){

    if(!$inUser->id) { return false; }

    if(!cmsCore::isAjax()) { return false; }

	$photo = $inPhoto->getPhoto(cmsCore::request('photo_id', 'int', 0));
	if (!$photo) { cmsCore::halt(); }

	// получаем клуб
	$club = $model->getClub($photo['auser_id']);
	if(!$club) { cmsCore::halt(); }

	if (!$club['published'] && !$inUser->is_admin) { return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');

	if(!$is_admin && !$is_moder) { cmsCore::halt(); }

	$inPhoto->publishPhoto($photo['id']);

	$description = $club['clubtype']=='private' ? '' :
				   '<a href="/clubs/photo'.$photo['id'].'.html" class="act_photo"><img border="0" src="/images/photos/small/'.$photo['file'].'" /></a>';

	cmsActions::log('add_photo_club', array(
		  'object' => $photo['title'],
		  'object_url' => '/clubs/photo'.$photo['id'].'.html',
		  'object_id' => $photo['id'],
          'user_id' => $photo['user_id'],
		  'target' => $club['title'],
		  'target_id' => $photo['album_id'],
		  'target_url' => '/clubs/'.$club['id'],
		  'description' => $description
	));

	cmsCore::halt('ok');

}
///////////////////////// ЗАГРУЗКА ФОТО ////////////////////////////////////////
if ($do=='add_photo'){

	// Неавторизованных просим авторизоваться
	if (!$inUser->id) { cmsUser::goToLogin(); }

	$do_photo = cmsCore::request('do_photo', 'str', 'addphoto');

	$album = $inDB->getNsCategory('cms_photo_albums', cmsCore::request('album_id', 'int', 0), null);
	if (!$album) { return false; }

	if (!$album['published'] && !$inUser->is_admin) { return false; }

	$club = $model->getClub($album['user_id']);
	if(!$club) { return false; }

	// если фотоальбомы запрещены
	if(!$club['enabled_photos']){ return false; }

	// Инициализируем участников клуба
	$model->initClubMembers($club['id']);
	// права доступа
    $is_admin  = $inUser->is_admin || ($inUser->id == $club['admin_id']);
    $is_moder  = $model->checkUserRightsInClub('moderator');
    $is_member = $model->checkUserRightsInClub('member');

    $is_karma_enabled = (($inUser->karma >= $club['photo_min_karma']) && $is_member) ? true : false;

    if(!$is_karma_enabled && !$is_admin && !$is_moder) {
        cmsCore::addSessionMessage('<p><strong>'.$_LANG['NEED_KARMA_PHOTO'].'</strong></p><p>'.$_LANG['NEEDED'].' '.$club['photo_min_karma'].', '.$_LANG['HAVE_ONLY'].' '.$inUser->karma.'.</p><p>'.$_LANG['WANT_SEE'].' <a href="/users/'.$inUser->id.'/karma.html">'.$_LANG['HISTORY_YOUR_KARMA'].'</a>?</p>', 'error');
        cmsCore::redirectBack();
    }

    $inPage->addPathway($club['title'], '/clubs/'.$club['id']);
    $inPage->addPathway($album['title'], '/clubs/photoalbum'.$album['id']);

    return include 'components/clubs/add_photo.php';
}
///////////////////////// БЛОГИ КЛУБОВ /////////////////////////////////////////
if ($do == 'club_blogs') {
    $bdo     = cmsCore::request('bdo', 'str', 'view_clubs_posts');
    $post_id = cmsCore::request('post_id', 'int', 0);
    $cat_id  = cmsCore::request('cat_id', 'int', 0);
    $seolink = cmsCore::request('seolink', 'str', '');
    $on_moderate = cmsCore::request('on_moderate', 'int', 0);

    $inBlog = $model->initBlog();
    $inPage->addHeadJsLang(array('NEW_CAT','RENAME_CAT','YOU_REALY_DELETE_CAT','YOU_REALY_DELETE_POST','NO_PUBLISHED'));

    return include 'components/clubs/club_blogs.php';
}

}
Esempio n. 23
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));
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Esempio n. 24
0
function applet_users() {
    $inCore = cmsCore::getInstance();
    cmsCore::loadClass('actions');
    cmsCore::loadModel('users');
    $model = new cms_model_users();

    // подключаем язык компонента регистрации
    cmsCore::loadLanguage('components/registration');

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

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

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

    if ($do == 'list') {
        $toolmenu = array(
            array( 'icon' => 'useradd.gif', 'title' => $_LANG['AD_USER_ADD'], 'link' => '?view=users&do=add' ),
            array( 'icon' => 'useredit.gif', 'title' => $_LANG['AD_EDIT_SELECTED'], 'link' => "javascript:checkSel('?view=users&do=edit&multiple=1');" ),
            array( 'icon' => 'userdelete.gif', 'title' => $_LANG['AD_DELETE_SELECTED'], 'link' => "javascript:if(confirm('". $_LANG['AD_IF_USERS_SELECT_REMOVE'] ."')) { checkSel('?view=users&do=delete&multiple=1'); }" ),
            array( 'icon' => 'usergroup.gif', 'title' => $_LANG['AD_USERS_GROUP'], 'link' => '?view=usergroups' ),
            array( 'icon' => 'userbanlist.gif', 'title' => $_LANG['AD_BANLIST'], 'link' => '?view=userbanlist' ),
            array( 'icon' => 'user_go.png', 'title' => $_LANG['AD_USERS_SELECT_ACTIVATE'], 'link' => "javascript:if(confirm('". $_LANG['AD_IF_USERS_SELECT_ACTIVATE'] ."')) { checkSel('?view=users&do=activate&multiple=1'); }" ),
            array( 'icon' => 'help.gif', 'title' => $_LANG['AD_HELP'], 'link' => '?view=help&topic=users' )
        );
        
        cpToolMenu($toolmenu);
        
        $fields = array(
            array( 'title' => 'id', 'field' => 'id', 'width' => '40'  ),
            array( 'title' => $_LANG['LOGIN'], 'field' => 'login', 'width' => '100', 'link' => '?view=users&do=edit&id=%id%', 'filter' => 12 ),
            array( 'title' => $_LANG['NICKNAME'], 'field' => 'nickname', 'width' => '', 'link' => '?view=users&do=edit&id=%id%', 'filter' => 12 ),
            array( 'title' => $_LANG['AD_RATING'], 'field' => array( 'rating', 'id' ), 'width' => '70', 'prc' => 'setRating' ),
            array( 'title' => $_LANG['AD_GROUP'], 'field' => 'group_id', 'width' => '110', 'prc' => 'cpGroupById', 'filter' => 1, 'filterlist' => cpGetList('cms_user_groups') ),
            array( 'title' => $_LANG['EMAIL'], 'field' => 'email', 'width' => '120' ),
            array( 'title' => $_LANG['AD_REGISTRATION_DATE'], 'field' => 'regdate', 'width' => '100' ),
            array( 'title' => $_LANG['AD_LAST_LOGIN'], 'field' => 'logdate', 'width' => '100' ),
            array( 'title' => $_LANG['AD_LAST_IP'], 'field' => 'last_ip', 'width' => '90', 'prc' => 'getIpLink' ),
            array( 'title' => $_LANG['AD_IS_LOCKED'], 'field' => 'is_locked', 'width' => '110', 'prc' => 'viewAct' ),
            array( 'title' => $_LANG['AD_IS_DELETED'], 'field' => 'is_deleted', 'width' => '80', 'prc' => 'viewDel' )
        );
        
        $actions = array(
            array( 'title' => $_LANG['AD_PROFILE'], 'icon' => 'profile.gif', 'link' => '/users/%login%' ),
            array( 'title' => $_LANG['AD_BANNED'], 'icon' => 'ban.gif', 'link' => '?view=userbanlist&do=add&to=%id%' ),
            array( 'title' => $_LANG['DELETE'], 'icon' => 'delete.gif', 'confirm' => $_LANG['AD_IS_USER_DELETE'], 'link' => '?view=users&do=delete&id=%id%' ),
            array( 'title' => $_LANG['AD_FOREVER_USER_DELETE'], 'icon' => 'off.gif', 'confirm' => $_LANG['AD_IF_FOREVER_USER_DELETE'], 'link' => '?view=users&do=delete_full&id=%id%' )
        );
        
        cpListTable('cms_users', $fields, $actions, '1=1', 'regdate DESC');
    }
    
    if ($do == 'rerating') {
        $user_id = cmsCore::request('user_id', 'int');
        if (!$user_id) { cmsCore::redirectBack(); }
        
        $rating = cmsUser::getRating($user_id);

        $user_sql = "UPDATE cms_users
                     SET rating = ". $rating ."
                     WHERE id = '". $user_id ."'";

        cmsCore::c('db')->query($user_sql);
        
        cmsCore::redirectBack();
    }
    
    if ($do == 'activate') {
        $user_ids = cmsCore::request('item', 'array_int');
        if (!$user_ids) { cmsCore::redirectBack(); }

        foreach ($user_ids as $user_id) {
            $code = cmsCore::c('db')->get_field('cms_users_activate', "user_id = '". $user_id ."'", 'code');

            $sql = "UPDATE cms_users SET is_locked = 0 WHERE id = '". $user_id ."'";
            cmsCore::c('db')->query($sql);

            $sql = "DELETE FROM cms_users_activate WHERE code = '". $code ."'";
            cmsCore::c('db')->query($sql);

            cmsCore::callEvent('USER_ACTIVATED', $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::redirectBack();
    }
    
    if ($do == 'delete') {
        if (!cmsCore::inRequest('item')) {
            if ($id >= 0) {
                $model->deleteUser($id);
            }
        } else {
            $model->deleteUsers(cmsCore::request('item', 'array_int', array()));
        }
        
        cmsCore::redirectBack();
    }

    if ($do == 'delete_full') {
        $model->deleteUser($id, true);
        cmsCore::redirectBack();
    }

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

        $types = array(
            'login' => array( 'login', 'str', '' ),
            'nickname' => array( 'nickname', 'str', '', 'htmlspecialchars' ),
            'email' => array( 'email', 'email', '' ),
            'group_id' => array( 'group_id', 'int', 1 ),
            'is_locked' => array( 'is_locked', 'int', 0 ),
            'password' => array( 'pass', 'str', '', 'stripslashes' ),
            'pass2' => array( 'pass2', 'str', '', 'stripslashes' )
        );

        $items = cmsCore::getArrayFromRequest($types);

        $errors = false;

        // проверяем логин
        if (mb_strlen($items['login']) < 2 ||
                mb_strlen($items['login']) > 15 ||
                is_numeric($items['login']) ||
                !preg_match("/^([a-zA-Z0-9])+$/ui", $items['login'])) {
            cmsCore::addSessionMessage($_LANG['ERR_LOGIN'], 'error');
            $errors = true;
        }

        // проверяем пароль
        if ($do == 'submit') {
            if (!$items['password']) {
                cmsCore::addSessionMessage($_LANG['TYPE_PASS'], 'error');
                $errors = true;
            }
        }
        
        if ($items['password'] && !$items['pass2']) {
            cmsCore::addSessionMessage($_LANG['TYPE_PASS_TWICE'], 'error');
            $errors = true;
        }
        
        if ($items['password'] && $items['pass2'] && mb_strlen($items['password']) < 6) {
            cmsCore::addSessionMessage($_LANG['PASS_SHORT'], 'error');
            $errors = true;
        }
        
        if ($items['password'] && $items['pass2'] && $items['password'] != $items['pass2']) {
            cmsCore::addSessionMessage($_LANG['WRONG_PASS'], 'error');
            $errors = true;
        }

        // никнейм
        if (mb_strlen($items['nickname']) < 2) {
            cmsCore::addSessionMessage($_LANG['SHORT_NICKNAME'], 'error');
            $errors = true;
        }
        
        // Проверяем email
        if (!$items['email']) {
            cmsCore::addSessionMessage($_LANG['ERR_EMAIL'], 'error');
            $errors = true;
        }

        // проверяем есть ли такой пользователь
        if ($do == 'submit') {
            $user_exist = cmsCore::c('db')->get_fields('cms_users', "(login LIKE '". $items['login'] ."' OR email LIKE '". $items['email'] ."') AND is_deleted = 0", 'login');
            if ($user_exist) {
                if ($user_exist['login'] == $items['login']) {
                    cmsCore::addSessionMessage($_LANG['LOGIN'] .' "'. $items['login'] .'" '. $_LANG['IS_BUSY'], 'error');
                    $errors = true;
                } else {
                    cmsCore::addSessionMessage($_LANG['EMAIL_IS_BUSY'], 'error');
                    $errors = true;
                }
            }
        }

        if ($errors) {
            if ($do == 'submit') {
                cmsUser::sessionPut('items', $items);
            }
            cmsCore::redirectBack();
        }

        if ($do == 'submit') {
            $items['regdate']  = date('Y-m-d H:i:s');
            $items['logdate']  = date('Y-m-d H:i:s');
            $items['password'] = md5($items['password']);

            $items['user_id'] = cmsCore::c('db')->insert('cms_users', $items);
            if (!$items['user_id']) { cmsCore::error404(); }

            cmsCore::c('db')->insert('cms_user_profiles', $items);

            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            cmsCore::redirect('?view=users');
        } else {
            // главного админа может редактировать только он сам
            if ($id == 1 && cmsCore::c('user')->id != $id) {
                cmsCore::error404();
            }
            
            if ($id == 1) {
                unset($items['group_id']);
                unset($items['is_locked']);
            }

            if (!$items['password']) {
                unset($items['password']);
            } else {
                $items['password'] = md5($items['password']);
            }

            cmsCore::c('db')->update('cms_users', $items, $id);

            cmsCore::addSessionMessage($_LANG['AD_DO_SUCCESS'], 'success');
            if (empty($_SESSION['editlist'])) {
                cmsCore::redirect('index.php?view=users');
            } else {
                cmsCore::redirect('index.php?view=users&do=edit');
            }
        }
    }

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

        cpToolMenu($toolmenu);

        if ($do == 'edit') {
            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_users', "id = '". $item_id ."'", '*');
            if (!$mod) { cmsCore::error404(); }

            echo '<h3>'. $_LANG['AD_USER_EDIT'] .' '. $ostatok .'</h3>';
            cpAddPathway($mod['nickname']);

        } else {
            $mod = cmsUser::sessionGet('items');
            if ($mod) { cmsUser::sessionDel('items'); }
            cpAddPathway($_LANG['AD_USER_ADD']);
        }
        
        cmsCore::c('page')->addHeadJS('components/registration/js/check.js');
?>
<form action="index.php?view=users" method="post" enctype="multipart/form-data" name="addform" id="addform">
    <input type="hidden" name="csrf_token" value="<?php echo cmsUser::getCsrfToken(); ?>" />
    
    <div style="width:500px;">
        <div class="form-group">
            <label><?php echo $_LANG['LOGIN']; ?>:</label>
            <input type="text" id="logininput" class="form-control" name="login" value="<?php echo cmsCore::getArrVal($mod, 'login', ''); ?>" onchange="checkLogin()" />
            <?php if ($do == 'edit') { echo '<div class="help-block" style="text-align:right;"><a target="_blank" href="/users/'. $mod['login'] .'" title="'. $_LANG['AD_USER_PROFILE'] .'">'. $_LANG['AD_USER_PROFILE'] .'</a></div>'; } ?>
        </div>
        
        <div class="form-group">
            <label><?php echo $_LANG['NICKNAME']; ?>:</label>
            <input type="text" id="login" class="form-control" name="nickname" value="<?php echo htmlspecialchars(cmsCore::getArrVal($mod, 'nickname', '')); ?>" />
        </div>
        
        <div class="form-group">
            <label><?php echo $_LANG['EMAIL']; ?>:</label>
            <input type="text" id="nickname" class="form-control" name="email" value="<?php echo cmsCore::getArrVal($mod, 'email', ''); ?>" />
        </div>
        
        <div class="form-group">
            <label><?php if ($do == 'edit') { echo $_LANG['AD_NEW_PASS']; } else { echo $_LANG['PASS']; } ?></label>
            <input type="password" id="pass" class="form-control" name="pass" />
        </div>
        
        <div class="form-group">
            <label><?php echo $_LANG['REPEAT_PASS']; ?>:</label>
            <input type="password" id="pass2" class="form-control" name="pass2" />
        </div>
        
        <div class="form-group">
            <label><?php echo $_LANG['AD_GROUP']; ?>:</label>
            <select id="group_id" class="form-control" name="group_id">
                <?php
                    echo $inCore->getListItems('cms_user_groups', cmsCore::getArrVal($mod, 'group_id', 0));
                ?>
            </select>
            <?php if ($do == 'edit') { echo '<div class="help-block" style="text-align:right;"><a target="_blank" href="?view=usergroups&do=edit&id='. $mod['group_id'] .'">'. $_LANG['EDIT'] .'</a></div>'; } ?>
        </div>
        
        <div class="form-group">
            <label><?php echo $_LANG['AD_IF_ACCAUNT_LOCK']; ?></label>
            <div class="btn-group" data-toggle="buttons" style="float:right;">
                <label class="btn btn-default <?php if ($mod['is_locked']) { echo 'active'; } ?>">
                    <input type="radio" name="is_locked" <?php if ($mod['is_locked']) { echo 'checked="checked"'; } ?> value="1" /> <?php echo $_LANG['YES']; ?>
                </label>
                <label class="btn btn-default <?php if (!$mod['is_locked']) { echo 'active'; } ?>">
                    <input type="radio" name="is_locked" <?php if (!$mod['is_locked']) { echo 'checked="checked"'; } ?> value="0" /> <?php echo $_LANG['NO']; ?>
                </label>
            </div>
        </div>
    </div>

    <div>
        <?php if ($do == 'edit') { ?>
            <input type="hidden" name="do" value="update" />
            <input type="submit" class="btn btn-primary" name="add_mod" value="<?php echo $_LANG['SAVE']; ?>" />
        <?php } else { ?>
            <input type="hidden" name="do" value="submit" />
            <input type="submit" class="btn btn-primary" name="add_mod" value="<?php echo $_LANG['AD_USER_ADD']; ?>" />
        <?php } ?>
        <input type="button" class="btn btn-default" name="back2" value="<?php echo $_LANG['CANCEL']; ?>" onclick="window.history.back();" />

        <?php
            if ($do == 'edit') {
                echo '<input type="hidden" name="id" value="'. $mod['id'] .'" />';
            }
        ?>
    </div>
</form>
<?php
   }
}
Esempio n. 25
0
function applet_install()
{
    $inCore = cmsCore::getInstance();
    global $_LANG;
    $GLOBALS['cp_page_title'] = $_LANG['AD_SETUP_EXTENSION'];
    $do = cmsCore::request('do', 'str', 'list');
    global $adminAccess;
    // ========================================================================== //
    if ($do == 'module') {
        if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) {
            cpAccessDenied();
        }
        cpAddPathway($_LANG['AD_SETUP_MODULES'], 'index.php?view=install&do=module');
        $new_modules = $inCore->getNewModules();
        $upd_modules = $inCore->getUpdatedModules();
        echo '<h3>' . $_LANG['AD_SETUP_MODULES'] . '</h3>';
        if (!$new_modules && !$upd_modules) {
            echo '<p>' . $_LANG['AD_NO_SEARCH_MODULES'] . '</p>';
            echo '<p>' . $_LANG['AD_IF_WANT_SETUP_MODULES'] . '</p>';
            echo '<p><a href="javascript:window.history.go(-1);">' . $_LANG['BACK'] . '</a></p>';
            return;
        }
        if ($new_modules) {
            echo '<p><strong>' . $_LANG['AD_SEARCH_MODULES'] . '</strong></p>';
            modulesList($new_modules, $_LANG['AD_SETUP'], 'install_module');
        }
        if ($upd_modules) {
            echo '<p><strong>' . $_LANG['AD_MODULES_UPDATE'] . '</strong></p>';
            modulesList($upd_modules, $_LANG['AD_UPDATE'], 'upgrade_module');
        }
        echo '<p>' . $_LANG['AD_CLICK_TO_CONTINUE_MODULE'] . '</p>';
        echo '<p><a href="javascript:window.history.go(-1);">' . $_LANG['BACK'] . '</a></p>';
    }
    // ========================================================================== //
    if ($do == 'install_module') {
        if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) {
            cpAccessDenied();
        }
        $error = '';
        $module_id = cmsCore::request('id', 'str', '');
        if (!$module_id) {
            cmsCore::redirectBack();
        }
        if ($inCore->loadModuleInstaller($module_id)) {
            $_module = call_user_func('info_module_' . $module_id);
            //////////////////////////////////////
            $error = call_user_func('install_module_' . $module_id);
        } else {
            $error = $_LANG['AD_MODULE_WIZARD_FAILURE'];
        }
        if ($error === true) {
            $inCore->installModule($_module, $_module['config']);
            cmsCore::addSessionMessage($_LANG['AD_MODULE'] . ' <strong>"' . $_module['title'] . '"</strong> ' . $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_INSTALL'], 'success');
            cmsCore::redirect('/admin/index.php?view=modules');
        } else {
            cmsCore::addSessionMessage($error, 'error');
            cmsCore::redirectBack();
        }
    }
    // ========================================================================== //
    if ($do == 'upgrade_module') {
        if (!cmsUser::isAdminCan('admin/modules', $adminAccess)) {
            cpAccessDenied();
        }
        $error = '';
        $module_id = cmsCore::request('id', 'str', '');
        if (!$module_id) {
            cmsCore::redirectBack();
        }
        if ($inCore->loadModuleInstaller($module_id)) {
            $_module = call_user_func('info_module_' . $module_id);
            if (isset($_module['link'])) {
                $_module['content'] = $_module['link'];
            }
            $error = call_user_func('upgrade_module_' . $module_id);
        } else {
            $error = $_LANG['AD_SETUP_WIZARD_FAILURE'];
        }
        if ($error === true) {
            $inCore->upgradeModule($_module, $_module['config']);
            cmsCore::addSessionMessage($_LANG['AD_MODULE'] . ' <strong>"' . $_module['title'] . '"</strong> ' . $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_UPDATE'], 'success');
            cmsCore::redirect('/admin/index.php?view=modules');
        } else {
            cmsCore::addSessionMessage($error, 'error');
            cmsCore::redirectBack();
        }
    }
    // ========================================================================== //
    if ($do == 'component') {
        if (!cmsUser::isAdminCan('admin/components', $adminAccess)) {
            cpAccessDenied();
        }
        cpAddPathway($_LANG['AD_SETUP_COMPONENTS'], 'index.php?view=install&do=component');
        $new_components = $inCore->getNewComponents();
        $upd_components = $inCore->getUpdatedComponents();
        echo '<h3>' . $_LANG['AD_SETUP_COMPONENTS'] . '</h3>';
        if (!$new_components && !$upd_components) {
            echo '<p>' . $_LANG['AD_NO_SEARCH_COMPONENTS'] . '</p>';
            echo '<p>' . $_LANG['AD_IF_WANT_SETUP_COMPONENTS'] . '</p>';
            ?>
            <h3><?php 
            echo $_LANG['AD_TRY_PREMIUM'];
            ?>
</h3>
            <div class="advert_iaudio"><a href="http://www.instantvideo.ru/software/iaudio.html"><strong>iAudio</strong></a> &mdash; <?php 
            echo $_LANG['AD_AUDIO_GALERY'];
            ?>
</div>
            <div class="advert_billing"><a href="http://www.cms.vadyus.com/billing/about.html"><strong><?php 
            echo $_LANG['AD_BILLING'];
            ?>
</strong></a> &mdash; <?php 
            echo $_LANG['AD_GAIN'];
            ?>
</div>
            <div class="advert_inmaps"><a href="http://www.instantmaps.ru/"><strong>InstantMaps</strong></a> &mdash; <?php 
            echo $_LANG['AD_OBJECT_TO_MAP'];
            ?>
</div>
            <div class="advert_inshop"><a href="http://www.cms.vadyus.com/blogs/InstantSoft/professionalnyi-magazin-dlja-vadyus.html"><strong>InstantShop</strong></a> &mdash; <?php 
            echo $_LANG['AD_SHOP'];
            ?>
</div>
            <div class="advert_invideo"><a href="http://www.instantvideo.ru/software/instantvideo.html"><strong>InstantVideo</strong></a> &mdash; <?php 
            echo $_LANG['AD_VIDEO_GALERY'];
            ?>
</div>
        <?php 
            return;
        }
        if ($new_components) {
            echo '<p><strong>' . $_LANG['AD_COMPONENTS_SETUP'] . '</strong></p>';
            componentsList($new_components, $_LANG['AD_SETUP'], 'install_component');
        }
        if ($upd_components) {
            echo '<p><strong>' . $_LANG['AD_COMPONENTS_UPDATE'] . '</strong></p>';
            componentsList($upd_components, $_LANG['AD_UPDATE'], 'upgrade_component');
        }
        echo '<p>' . $_LANG['AD_CLICK_TO_CONTINUE_COMPONENT'] . '</p>';
        echo '<p><a href="javascript:window.history.go(-1);">' . $_LANG['BACK'] . '</a></p>';
    }
    // ========================================================================== //
    if ($do == 'install_component') {
        $error = '';
        $component = cmsCore::request('id', 'str', '');
        if (!$component) {
            cmsCore::redirectBack();
        }
        if (!cmsUser::isAdminCan('admin/components', $adminAccess)) {
            cpAccessDenied();
        }
        if ($inCore->loadComponentInstaller($component)) {
            $_component = call_user_func('info_component_' . $component);
            $error = call_user_func('install_component_' . $component);
        } else {
            $error = $_LANG['AD_COMPONENT_WIZARD_FAILURE'];
        }
        if ($error === true) {
            $inCore->installComponent($_component, $_component['config']);
            $info_text = '<p>' . $_LANG['AD_COMPONENT'] . ' <strong>"' . $_component['title'] . '"</strong> ' . $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_INSTALL'] . '</p>';
            if (isset($_component['modules'])) {
                if (is_array($_component['modules'])) {
                    $info_text .= '<p>' . $_LANG['AD_OPT_INSTALL_MODULES'] . ':</p>';
                    $info_text .= '<ul>';
                    foreach ($_component['modules'] as $module => $title) {
                        $info_text .= '<li>' . $title . '</li>';
                    }
                    $info_text .= '</ul>';
                }
            }
            if (isset($_component['plugins'])) {
                if (is_array($_component['plugins'])) {
                    $info_text .= '<p>' . $_LANG['AD_OPT_INSTALL_PLUGINS'] . ':</p>';
                    $info_text .= '<ul>';
                    foreach ($_component['plugins'] as $module => $title) {
                        $info_text .= '<li>' . $title . '</li>';
                    }
                    $info_text .= '</ul>';
                }
            }
            cmsCore::addSessionMessage($info_text, 'success');
            cmsCore::redirect('/admin/index.php?view=components');
        } else {
            cmsCore::addSessionMessage($error, 'error');
            cmsCore::redirectBack();
        }
    }
    // ========================================================================== //
    if ($do == 'upgrade_component') {
        cpAddPathway($_LANG['AD_UPDATE_COMPONENTS'], 'index.php?view=install&do=component');
        $error = '';
        $component = cmsCore::request('id', 'str', '');
        if (!$component) {
            cmsCore::redirectBack();
        }
        if (!cmsUser::isAdminCan('admin/components', $adminAccess)) {
            cpAccessDenied();
        }
        if (!cmsUser::isAdminCan('admin/com_' . $component, $adminAccess)) {
            cpAccessDenied();
        }
        if ($inCore->loadComponentInstaller($component)) {
            $_component = call_user_func('info_component_' . $component);
            $error = call_user_func('upgrade_component_' . $component);
        } else {
            $error = $_LANG['AD_COMPONENT_WIZARD_FAILURE'];
        }
        if ($error === true) {
            $inCore->upgradeComponent($_component, $_component['config']);
            $info_text = $_LANG['AD_COMPONENT'] . ' <strong>"' . $_component['title'] . '"</strong> ' . $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_UPDATE'];
            cmsCore::addSessionMessage($info_text, 'success');
            cmsCore::redirect('/admin/index.php?view=components');
        } else {
            cmsCore::addSessionMessage($error, 'error');
            cmsCore::redirectBack();
        }
    }
    // ========================================================================== //
    if ($do == 'remove_component') {
        $component_id = cmsCore::request('id', 'int', '');
        if (!$component_id) {
            cmsCore::redirectBack();
        }
        $com = $inCore->getComponentById($component_id);
        if (!cmsUser::isAdminCan('admin/components', $adminAccess)) {
            cpAccessDenied();
        }
        if (!cmsUser::isAdminCan('admin/com_' . $com, $adminAccess)) {
            cpAccessDenied();
        }
        if ($inCore->loadComponentInstaller($com)) {
            if (function_exists('remove_component_' . $com)) {
                call_user_func('remove_component_' . $com);
            }
        }
        $inCore->removeComponent($component_id);
        cmsCore::addSessionMessage($_LANG['AD_COMPONENT_IS_DELETED'], 'success');
        cmsCore::redirect('/admin/index.php?view=components');
    }
    // ========================================================================== //
    if ($do == 'plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) {
            cpAccessDenied();
        }
        cpAddPathway($_LANG['AD_SETUP_PLUGINS'], 'index.php?view=install&do=plugin');
        $new_plugins = $inCore->getNewPlugins();
        $upd_plugins = $inCore->getUpdatedPlugins();
        echo '<h3>' . $_LANG['AD_SETUP_PLUGINS'] . '</h3>';
        if (!$new_plugins && !$upd_plugins) {
            echo '<p>' . $_LANG['AD_NO_SEARCH_PLUGINS'] . '</p>';
            echo '<p>' . $_LANG['AD_IF_WANT_SETUP_PLUGINS'] . '</p>';
            echo '<p><a href="javascript:window.history.go(-1);">' . $_LANG['BACK'] . '</a></p>';
            return;
        }
        if ($new_plugins) {
            echo '<p><strong>' . $_LANG['AD_PLUGINS_SETUP'] . '</strong></p>';
            pluginsList($new_plugins, $_LANG['AD_SETUP'], 'install_plugin');
        }
        if ($upd_plugins) {
            echo '<p><strong>' . $_LANG['AD_PLUGINS_UPDATE'] . '</strong></p>';
            pluginsList($upd_plugins, $_LANG['AD_UPDATE'], 'upgrade_plugin');
        }
        echo '<p>' . $_LANG['AD_CLICK_TO_CONTINUE_PLUGIN'] . '</p>';
        echo '<p><a href="javascript:window.history.go(-1);">' . $_LANG['BACK'] . '</a></p>';
    }
    // ========================================================================== //
    if ($do == 'install_plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) {
            cpAccessDenied();
        }
        cpAddPathway($_LANG['AD_SETUP_PLUGIN'], 'index.php?view=install&do=plugin');
        $error = '';
        $plugin_id = cmsCore::request('id', 'str', '');
        if (!$plugin_id) {
            cmsCore::redirectBack();
        }
        $plugin = $inCore->loadPlugin($plugin_id);
        if (!$plugin) {
            $error = $_LANG['AD_PLUGIN_FAILURE'];
        }
        if (!$error && $plugin->install()) {
            cmsCore::addSessionMessage($_LANG['AD_PLUGIN'] . ' <strong>"' . $plugin->info['title'] . '"</strong> ' . $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_INSTALL'] . '. ' . $_LANG['AD_ENABLE_PLUGIN'], 'success');
            cmsCore::redirect('/admin/index.php?view=plugins');
        }
        if ($error) {
            echo '<p style="color:red">' . $error . '</p>';
        }
        echo '<p><a href="index.php?view=install&do=plugin">' . $_LANG['BACK'] . '</a></p>';
    }
    // ========================================================================== //
    if ($do == 'upgrade_plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) {
            cpAccessDenied();
        }
        cpAddPathway($_LANG['AD_UPDATE_PLUGIN'], 'index.php?view=install&do=plugin');
        $error = '';
        $plugin_id = cmsCore::request('id', 'str', '');
        if (!$plugin_id) {
            cmsCore::redirectBack();
        }
        $plugin = $inCore->loadPlugin($plugin_id);
        if (!$plugin) {
            $error = $_LANG['AD_PLUGIN_FAILURE'];
        }
        if (!$error && $plugin->upgrade()) {
            cmsCore::addSessionMessage($_LANG['AD_PLUGIN'] . ' <strong>"' . $plugin->info['title'] . '"</strong> ' . $_LANG['AD_SUCCESS'] . $_LANG['AD_IS_UPDATE'], 'success');
            cmsCore::redirect('/admin/index.php?view=plugins');
        }
        if ($error) {
            echo '<p style="color:red">' . $error . '</p>';
        }
        echo '<p><a href="index.php?view=install&do=plugin">' . $_LANG['BACK'] . '</a></p>';
    }
    // ========================================================================== //
    if ($do == 'remove_plugin') {
        if (!cmsUser::isAdminCan('admin/plugins', $adminAccess)) {
            cpAccessDenied();
        }
        $plugin_id = cmsCore::request('id', 'str', '');
        if (!$plugin_id) {
            cmsCore::redirectBack();
        }
        $inCore->removePlugin($plugin_id);
        cmsCore::addSessionMessage($_LANG['AD_REMOVE_PLUGIN_OK'], 'success');
        cmsCore::redirect('/admin/index.php?view=plugins');
    }
}
Esempio n. 26
0
         }
         // Загружаем файл
         if ($inCore->moveUploadedFile($data_array["tmp_name"], PATH . "/upload/userfiles/{$usr['id']}/{$name}", $data_array['error'])) {
             $loaded_files[] = $name;
             $sql = "INSERT INTO cms_user_files(user_id, filename, pubdate, allow_who, filesize, hits)\n\t\t\t\t\t\tVALUES ({$usr['id']}, '{$name}', NOW(), 'all', '{$size}', 0)";
             $inDB->query($sql);
             $file_id = $inDB->get_last_id('cms_user_files');
             cmsActions::log('add_file', array('object' => $name, 'object_url' => '/users/files/download' . $file_id . '.html', 'object_id' => $file_id, 'target' => '', 'target_url' => '', 'description' => ''));
         }
     }
     if (sizeof($loaded_files)) {
         cmsCore::addSessionMessage($_LANG['FILE_UPLOAD_FINISH'], 'success');
         if ($model->config['filessize']) {
             cmsCore::addSessionMessage('<strong>' . $_LANG['FREE_SPACE_LEFT'] . ':</strong> ' . round($free_mb - $size_mb, 2) . ' ' . $_LANG['MBITE'], 'info');
         }
         cmsCore::redirect('/users/' . $usr['id'] . '/files.html');
     } else {
         cmsCore::addSessionMessage($_LANG['ERR_BIG_FILE'] . ' ' . $_LANG['ERR_FILE_NAME'], 'error');
         cmsCore::redirectBack();
     }
 }
 if (!cmsCore::inRequest('upload')) {
     $inPage->setTitle('загрузка файла');
     $inPage->addHeadJS('includes/jquery/multifile/jquery.multifile.js');
     $inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
     $inPage->addPathway($_LANG['FILES_ARCHIVE'], '/users/' . $usr['id'] . '/files.html');
     $inPage->addPathway($_LANG['UPLOAD_FILES']);
     $inPage->addHeadJsLang(array('FILE_SELECTED', 'FILE_DENIED', 'FILE_DUPLICATE'));
     $post_max_b = trim(@ini_get('upload_max_filesize'));
     $last = mb_strtolower($post_max_b[mb_strlen($post_max_b) - 1]);
     switch ($last) {
Esempio n. 27
0
function applet_content()
{
    $inCore = cmsCore::getInstance();
    $inUser = cmsUser::getInstance();
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    //check access
    global $adminAccess;
    if (!cmsUser::isAdminCan('admin/content', $adminAccess)) {
        cpAccessDenied();
    }
    $cfg = $inCore->loadComponentConfig('content');
    cmsCore::loadModel('content');
    $model = new cms_model_content();
    $GLOBALS['cp_page_title'] = $_LANG['AD_ARTICLES'];
    cpAddPathway($_LANG['AD_ARTICLES'], 'index.php?view=tree');
    $do = cmsCore::request('do', 'str', 'add');
    $id = cmsCore::request('id', 'int', -1);
    if ($do == 'arhive_on') {
        $inDB->query("UPDATE cms_content SET is_arhive = 1 WHERE id = '{$id}'");
        cmsCore::addSessionMessage($_LANG['AD_ARTICLES_TO_ARHIVE'], 'success');
        cmsCore::redirectBack();
    }
    if ($do == 'move') {
        $item_id = cmsCore::request('id', 'int', 0);
        $cat_id = cmsCore::request('cat_id', 'int', 0);
        $dir = $_REQUEST['dir'];
        $step = 1;
        $model->moveItem($item_id, $cat_id, $dir, $step);
        echo '1';
        exit;
    }
    if ($do == 'move_to_cat') {
        $items = cmsCore::request('item', 'array_int');
        $to_cat_id = cmsCore::request('obj_id', 'int', 0);
        if ($items && $to_cat_id) {
            $last_ordering = (int) $inDB->get_field('cms_content', "category_id = '{$to_cat_id}' ORDER BY ordering DESC", 'ordering');
            foreach ($items as $item_id) {
                $article = $model->getArticle($item_id);
                if (!$article) {
                    continue;
                }
                $last_ordering++;
                $model->updateArticle($article['id'], array('category_id' => $to_cat_id, 'ordering' => $last_ordering, 'url' => $article['url'], 'title' => $inDB->escape_string($article['title']), 'id' => $article['id'], 'user_id' => $article['user_id']));
            }
            cmsCore::addSessionMessage($_LANG['AD_ARTICLES_TO'], 'success');
        }
        cmsCore::redirect('?view=tree&cat_id=' . $to_cat_id);
    }
    if ($do == 'show') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbShow('cms_content', $id);
            }
            echo '1';
            exit;
        } else {
            dbShowList('cms_content', cmsCore::request('item', 'array_int'));
            cmsCore::redirectBack();
        }
    }
    if ($do == 'hide') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                dbHide('cms_content', $id);
            }
            echo '1';
            exit;
        } else {
            dbHideList('cms_content', cmsCore::request('item', 'array_int'));
            cmsCore::redirectBack();
        }
    }
    if ($do == 'delete') {
        if (!isset($_REQUEST['item'])) {
            if ($id >= 0) {
                $model->deleteArticle($id);
                cmsCore::addSessionMessage($_LANG['AD_ARTICLE_REMOVE'], 'success');
            }
        } else {
            $model->deleteArticles(cmsCore::request('item', 'array_int'));
            cmsCore::addSessionMessage($_LANG['AD_ARTICLES_REMOVE'], 'success');
        }
        cmsCore::redirectBack();
    }
    if ($do == 'update') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        if (isset($_REQUEST['id'])) {
            $id = cmsCore::request('id', 'int', 0);
            $article['category_id'] = cmsCore::request('category_id', 'int', 1);
            $article['title'] = cmsCore::request('title', 'str');
            $article['url'] = cmsCore::request('url', 'str');
            $article['showtitle'] = cmsCore::request('showtitle', 'int', 0);
            $article['description'] = cmsCore::request('description', 'html', '');
            $article['description'] = $inDB->escape_string($article['description']);
            $article['content'] = cmsCore::request('content', 'html', '');
            $article['content'] = $inDB->escape_string($article['content']);
            $article['for_img'] = cmsCore::request('for_img', 'html', '');
            $article['for_img'] = $inDB->escape_string($article['for_img']);
            $article['published'] = cmsCore::request('published', 'int', 0);
            $article['showdate'] = cmsCore::request('showdate', 'int', 0);
            $article['showlatest'] = cmsCore::request('showlatest', 'int', 0);
            $article['show_in_new'] = cmsCore::request('show_in_new', 'int', 0);
            //new
            $article['show_in_footer'] = cmsCore::request('show_in_footer', 'int', 0);
            //new
            $article['showpath'] = cmsCore::request('showpath', 'int', 0);
            $article['comments'] = cmsCore::request('comments', 'int', 0);
            $article['canrate'] = cmsCore::request('canrate', 'int', 0);
            $article['add_text'] = cmsCore::request('add_text', 'str');
            $enddate = explode('.', cmsCore::request('enddate', 'str'));
            $article['enddate'] = $enddate[2] . '-' . $enddate[1] . '-' . $enddate[0];
            $article['is_end'] = cmsCore::request('is_end', 'int', 0);
            $article['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
            $article['tags'] = cmsCore::request('tags', 'str');
            $olddate = cmsCore::request('olddate', 'str', '');
            $pubdate = cmsCore::request('pubdate', 'str', '');
            $article['user_id'] = cmsCore::request('user_id', 'int', $inUser->id);
            $article['tpl'] = cmsCore::request('tpl', 'str', 'com_content_read.tpl');
            $date = explode('.', $pubdate);
            $article['pubdate'] = $date[2] . '-' . $date[1] . '-' . $date[0] . ' ' . date('H:i');
            $autokeys = cmsCore::request('autokeys', 'int');
            switch ($autokeys) {
                case 1:
                    $article['meta_keys'] = $inCore->getKeywords($article['content']);
                    $article['meta_desc'] = $article['title'];
                    break;
                case 2:
                    $article['meta_desc'] = strip_tags($article['description']);
                    $article['meta_keys'] = $article['tags'];
                    break;
                case 3:
                    $article['meta_desc'] = cmsCore::request('meta_desc', 'str');
                    $article['meta_keys'] = cmsCore::request('meta_keys', 'str');
                    break;
            }
            $model->updateArticle($id, $article);
            if (!cmsCore::request('is_public', 'int', 0)) {
                $showfor = $_REQUEST['showfor'];
                cmsCore::setAccess($id, $showfor, 'material');
            } else {
                cmsCore::clearAccess($id, 'material');
            }
            if (isset($_SESSION['lang']) && $_SESSION['lang'] != 'ru') {
                $file = 'article' . $id . '_' . $_SESSION['lang'] . '.jpg';
            } else {
                $file = 'article' . $id . '.jpg';
            }
            //$file = 'article'.$id.'.jpg';
            if (cmsCore::request('delete_image', 'int', 0)) {
                @unlink(PATH . "/images/photos/small/{$file}");
                @unlink(PATH . "/images/photos/medium/{$file}");
            } else {
                // Загружаем класс загрузки фото
                cmsCore::loadClass('upload_photo');
                $inUploadPhoto = cmsUploadPhoto::getInstance();
                // Выставляем конфигурационные параметры
                $inUploadPhoto->upload_dir = PATH . '/images/photos/';
                $inUploadPhoto->small_size_w = $model->config['img_small_w'];
                $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
                $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
                $inUploadPhoto->is_watermark = $model->config['watermark'];
                $inUploadPhoto->input_name = 'picture';
                $inUploadPhoto->filename = $file;
                // Процесс загрузки фото
                $inUploadPhoto->uploadPhoto();
            }
            cmsCore::addSessionMessage($_LANG['AD_ARTICLE_SAVE'], 'success');
            if (!isset($_SESSION['editlist']) || @sizeof($_SESSION['editlist']) == 0) {
                cmsCore::redirect('?view=tree&cat_id=' . $article['category_id']);
            } else {
                cmsCore::redirect('?view=content&do=edit');
            }
        }
    }
    if ($do == 'submit') {
        if (!cmsUser::checkCsrfToken()) {
            cmsCore::error404();
        }
        $article['category_id'] = cmsCore::request('category_id', 'int', 1);
        $article['title'] = cmsCore::request('title', 'str');
        $article['url'] = cmsCore::request('url', 'str');
        $article['showtitle'] = cmsCore::request('showtitle', 'int', 0);
        $article['description'] = cmsCore::request('description', 'html', '');
        $article['description'] = $inDB->escape_string($article['description']);
        $article['content'] = cmsCore::request('content', 'html', '');
        $article['content'] = $inDB->escape_string($article['content']);
        $article['for_img'] = cmsCore::request('for_img', 'html', '');
        $article['for_img'] = $inDB->escape_string($article['for_img']);
        $article['published'] = cmsCore::request('published', 'int', 0);
        $article['showdate'] = cmsCore::request('showdate', 'int', 0);
        $article['showlatest'] = cmsCore::request('showlatest', 'int', 0);
        $article['show_in_new'] = cmsCore::request('show_in_new', 'int', 0);
        //new
        $article['show_in_footer'] = cmsCore::request('show_in_footer', 'int', 0);
        //new
        $article['showpath'] = cmsCore::request('showpath', 'int', 0);
        $article['comments'] = cmsCore::request('comments', 'int', 0);
        $article['canrate'] = cmsCore::request('canrate', 'int', 0);
        $article['add_text'] = cmsCore::request('add_text', 'str');
        $enddate = explode('.', cmsCore::request('enddate', 'str'));
        $article['enddate'] = $enddate[2] . '-' . $enddate[1] . '-' . $enddate[0];
        $article['is_end'] = cmsCore::request('is_end', 'int', 0);
        $article['pagetitle'] = cmsCore::request('pagetitle', 'str', '');
        $article['tags'] = cmsCore::request('tags', 'str');
        $article['pubdate'] = $_REQUEST['pubdate'];
        $date = explode('.', $article['pubdate']);
        $article['pubdate'] = $date[2] . '-' . $date[1] . '-' . $date[0] . ' ' . date('H:i');
        $article['user_id'] = cmsCore::request('user_id', 'int', $inUser->id);
        $article['tpl'] = cmsCore::request('tpl', 'str', 'com_content_read.tpl');
        $autokeys = cmsCore::request('autokeys', 'int');
        switch ($autokeys) {
            case 1:
                $article['meta_keys'] = $inCore->getKeywords($article['content']);
                $article['meta_desc'] = $article['title'];
                break;
            case 2:
                $article['meta_desc'] = strip_tags($article['description']);
                $article['meta_keys'] = $article['tags'];
                break;
            case 3:
                $article['meta_desc'] = cmsCore::request('meta_desc', 'str');
                $article['meta_keys'] = cmsCore::request('meta_keys', 'str');
                break;
        }
        $article['id'] = $model->addArticle($article);
        if (!cmsCore::request('is_public', 'int', 0)) {
            $showfor = $_REQUEST['showfor'];
            if (sizeof($showfor) > 0 && !cmsCore::request('is_public', 'int', 0)) {
                cmsCore::setAccess($article['id'], $showfor, 'material');
            }
        }
        $inmenu = cmsCore::request('createmenu', 'str', '');
        if ($inmenu) {
            createMenuItem($inmenu, $article['id'], $article['title']);
        }
        // Загружаем класс загрузки фото
        cmsCore::loadClass('upload_photo');
        $inUploadPhoto = cmsUploadPhoto::getInstance();
        // Выставляем конфигурационные параметры
        $inUploadPhoto->upload_dir = PATH . '/images/photos/';
        $inUploadPhoto->small_size_w = $model->config['img_small_w'];
        $inUploadPhoto->medium_size_w = $model->config['img_big_w'];
        $inUploadPhoto->thumbsqr = $model->config['img_sqr'];
        $inUploadPhoto->is_watermark = $model->config['watermark'];
        $inUploadPhoto->input_name = 'picture';
        $inUploadPhoto->filename = 'article' . $article['id'] . '.jpg';
        // Процесс загрузки фото
        $inUploadPhoto->uploadPhoto();
        cmsCore::addSessionMessage($_LANG['AD_ARTICLE_ADD'], 'success');
        cmsCore::redirect('?view=tree&cat_id=' . $article['category_id']);
    }
    if ($do == 'add' || $do == 'edit') {
        require '../includes/jwtabs.php';
        $GLOBALS['cp_page_head'][] = jwHeader();
        $toolmenu = array();
        $toolmenu[0]['icon'] = 'save.gif';
        $toolmenu[0]['title'] = $_LANG['SAVE'];
        $toolmenu[0]['link'] = 'javascript:document.addform.submit();';
        $toolmenu[1]['icon'] = 'cancel.gif';
        $toolmenu[1]['title'] = $_LANG['CANCEL'];
        $toolmenu[1]['link'] = 'javascript:history.go(-1);';
        cpToolMenu($toolmenu);
        $menu_list = cpGetList('menu');
        if ($do == 'add') {
            echo '<h3>' . $_LANG['AD_CREATE_ARTICLE'] . '</h3>';
            cpAddPathway($_LANG['AD_CREATE_ARTICLE'], 'index.php?view=content&do=add');
            $mod['category_id'] = (int) $_REQUEST['to'];
            $mod['showpath'] = 1;
            $mod['tpl'] = 'com_content_read.tpl';
        } else {
            if (isset($_REQUEST['item'])) {
                $_SESSION['editlist'] = $_REQUEST['item'];
            }
            $ostatok = '';
            if (isset($_SESSION['editlist'])) {
                $id = array_shift($_SESSION['editlist']);
                if (sizeof($_SESSION['editlist']) == 0) {
                    unset($_SESSION['editlist']);
                } else {
                    $ostatok = '(' . $_LANG['AD_NEXT_IN'] . sizeof($_SESSION['editlist']) . ')';
                }
            } else {
                $id = (int) $_REQUEST['id'];
            }
            $sql = "SELECT *, (TO_DAYS(enddate) - TO_DAYS(CURDATE())) as daysleft, DATE_FORMAT(pubdate, '%d.%m.%Y') as pubdate, DATE_FORMAT(enddate, '%d.%m.%Y') as enddate\n\t\t\t\t\t FROM cms_content\n\t\t\t\t\t WHERE id = {$id} LIMIT 1";
            $result = $inDB->query($sql);
            if ($inDB->num_rows($result)) {
                $mod = $inDB->fetch_assoc($result);
            }
            echo '<h3>' . $_LANG['AD_EDIT_ARTICLE'] . $ostatok . '</h3>';
            cpAddPathway($mod['title'], 'index.php?view=content&do=edit&id=' . $mod['id']);
        }
        ?>
    <form id="addform" name="addform" method="post" action="index.php" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?php 
        echo cmsUser::getCsrfToken();
        ?>
" />
        <input type="hidden" name="view" value="content" />

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

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

                    <table width="100%" cellpadding="0" cellspacing="4" border="0">
                        <tr>
                            <td valign="top">
                                <div><strong><?php 
        echo $_LANG['AD_ARTICLE_NAME'];
        ?>
</strong></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:10px;">
                                                <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>
                            </td>
                            <td width="130" valign="top">
                                <div><strong><?php 
        echo $_LANG['AD_PUBLIC_DATE'];
        ?>
</strong></div>
                                <div>
                                    <input name="pubdate" type="text" id="pubdate" style="width:100px" <?php 
        if (@(!$mod['pubdate'])) {
            echo 'value="' . date('d.m.Y') . '"';
        } else {
            echo 'value="' . $mod['pubdate'] . '"';
        }
        ?>
/>

                                    <input type="hidden" name="olddate" value="<?php 
        echo @$mod['pubdate'];
        ?>
" />
                                </div>
                            </td>
                            <td width="16" valign="bottom" style="padding-bottom:10px">
                                <input type="checkbox" name="showdate" id="showdate" title="<?php 
        echo $_LANG['AD_VIEW_DATE_AND_AUTHOR'];
        ?>
" value="1" <?php 
        if ($mod['showdate'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/>
                            </td>
<!--                             <td width="160" valign="top">
                                <div><strong><?php 
        echo $_LANG['AD_ARTICLE_TEMPLATE'];
        ?>
</strong></div>
                                <div><input name="tpl" type="text" style="width:160px" value="<?php 
        echo @$mod['tpl'];
        ?>
"></div>
                            </td> -->
							  <td width="160" valign="top">
                                <div><strong>Шаблон статьи</strong></div>
								<?php 
        $inConf = cmsConfig::getInstance();
        //задаём имя директории
        $directory = PATH . "/templates/" . $inConf->template . "/components";
        $scan_dir = scandir($directory);
        if (is_dir($directory)) {
            //проверяем наличие директории
            //директория существует
            echo '<select name="tpl">';
            $scan_dir = scandir($directory);
            //сканируем (получаем массив файлов)
            array_shift($scan_dir);
            // удаляем из массива '.'
            array_shift($scan_dir);
            // удаляем из массива '..'
            for ($i = 0; $i < sizeof($scan_dir); $i++) {
                $tpl = explode("_", $scan_dir[$i]);
                if ($_GET['view'] == $tpl['1']) {
                    if ($_GET['view']) {
                        //выводим все файлы
                        if (@$mod["tpl"] == $scan_dir[$i]) {
                            echo '<option selected>' . $scan_dir[$i] . '</option>';
                        } else {
                            echo '<option>' . $scan_dir[$i] . '</option>';
                        }
                    }
                }
            }
            echo '</select>';
        } else {
            echo '<input name="tpl" type="text" style="width:160px" value="' . @$mod["tpl"] . '">';
        }
        ?>
                            </td>

                        </tr>
                    </table>

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_NOTICE'];
        ?>
</strong></div>
                    <div><?php 
        $inCore->insertEditor('description', $mod['description'], '200', '100%');
        ?>
</div>

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_TEXT'];
        ?>
</strong></div>
                    <?php 
        insertPanel();
        ?>
                    <div><?php 
        $inCore->insertEditor('content', $mod['content'], '400', '100%');
        ?>
</div><!--Editor text in articles-->

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_IMG'];
        ?>
</strong></div>
                    <div><?php 
        $inCore->insertEditor('for_img', $mod['for_img'], '200', '100%');
        ?>
</div>

                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_ADD_TEXT'];
        ?>
</strong></div>
                    <div><input name="add_text" type="text" id="add_text" style="width:99%" value="<?php 
        echo htmlspecialchars($mod['add_text']);
        ?>
" /></div>


                    <div><strong><?php 
        echo $_LANG['AD_ARTICLE_TAGS'];
        ?>
</strong></div>
                    <div><input name="tags" type="text" id="tags" style="width:99%" value="<?php 
        if (isset($mod['id'])) {
            echo cmsTagLine('content', $mod['id'], false);
        }
        ?>
" /></div>

                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                        <tr>
                            <td width="20">
                                <input type="radio" name="autokeys" id="autokeys1" <?php 
        if ($do == 'add' && $cfg['autokeys']) {
            ?>
checked="checked"<?php 
        }
        ?>
 value="1"/>
                            </td>
                            <td>
                                <label for="autokeys1"><strong><?php 
        echo $_LANG['AD_AUTO_GEN_KEY'];
        ?>
</strong></label>
                            </td>
                        </tr>
                        <tr>
                            <td width="20">
                                <input type="radio" name="autokeys" id="autokeys2" value="2"/>
                            </td>
                            <td>
                                <label for="autokeys2"><strong><?php 
        echo $_LANG['AD_TAGS_AS_KEY'];
        ?>
</strong></label>
                            </td>
                        </tr>
                        <tr>
                            <td width="20">
                                <input type="radio" name="autokeys" id="autokeys3" value="3" <?php 
        if ($do == 'edit' || !$cfg['autokeys']) {
            ?>
checked="checked"<?php 
        }
        ?>
/>
                            </td>
                            <td>
                                <label for="autokeys3"><strong><?php 
        echo $_LANG['AD_MANUAL_KEY'];
        ?>
</strong></label>
                            </td>
                        </tr>

                        <?php 
        if ($cfg['af_on'] && $do == 'add') {
            ?>
                        <tr>
                            <td width="20"><input type="checkbox" name="noforum" id="noforum" value="1" /> </td>
                            <td><label for="noforum"><strong><?php 
            echo $_LANG['AD_NO_CREATE_THEME'];
            ?>
</strong></label></td>
                        </tr>
                        <?php 
        }
        ?>
                    </table>

                </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_PUBLIC_ARTICLE'];
        ?>
</strong></label></td>
                        </tr>
                    </table>

                    <div style="margin-top:7px">
                        <select name="category_id" size="10" id="category_id" style="width:99%;height:200px">
                            <option value="1" <?php 
        if (@$mod['category_id'] == 1 || !isset($mod['category_id'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_ROOT_CATEGORY'];
        ?>
</option>
                            <?php 
        if (isset($mod['category_id'])) {
            echo $inCore->getListItemsNS('cms_category', $mod['category_id']);
        } else {
            echo $inCore->getListItemsNS('cms_category');
        }
        ?>
                        </select>
                    </div>

                    <div style="margin-bottom:10px">
                        <select name="showpath" id="showpath" style="width:99%">
                            <option value="0" <?php 
        if (@(!$mod['showpath'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_PATHWAY_NAME_ONLY'];
        ?>
</option>
                            <option value="1" <?php 
        if (@$mod['showpath']) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_PATHWAY_FULL'];
        ?>
</option>
                        </select>
                    </div>

                    <div style="margin-top:15px">
                        <strong><?php 
        echo $_LANG['AD_ARTICLE_URL'];
        ?>
</strong><br/>
                        <div style="color:gray"><?php 
        echo $_LANG['AD_IF_UNKNOWN'];
        ?>
</div>
                    </div>
                    <div>
                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                            <tr>
                                <td><input type="text" name="url" value="<?php 
        echo $mod['url'];
        ?>
" style="width:100%"/></td>
                                <td width="40" align="center">.html</td>
                            </tr>
                        </table>
                    </div>

                    <div style="margin-top:10px">
                        <strong><?php 
        echo $_LANG['AD_ARTICLE_AUTHOR'];
        ?>
</strong>
                    </div>
                    <div>
                        <select name="user_id" id="user_id" style="width:99%">
                          <?php 
        if (isset($mod['user_id'])) {
            echo $inCore->getListItems('cms_users', $mod['user_id'], 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
        } else {
            echo $inCore->getListItems('cms_users', $inUser->id, 'nickname', 'ASC', 'is_deleted=0 AND is_locked=0', 'id', 'nickname');
        }
        ?>
                        </select>
                    </div>

                    <div style="margin-top:12px"><strong><?php 
        echo $_LANG['AD_PHOTO'];
        ?>
</strong></div>
                    <div style="margin-bottom:10px">
                        <?php 
        if ($do == 'edit') {
            if (isset($_SESSION['lang']) && $_SESSION['lang'] != 'ru') {
                $mod_id = $mod['id'] . '_' . $_SESSION['lang'];
                $id_art = $mod['id'] . '_' . $_SESSION['lang'];
            } else {
                $mod_id = $mod['id'];
                $id_art = $id;
            }
            //if (file_exists(PATH.'/images/photos/small/article'.$mod['id'].'.jpg')){
            if (file_exists(PATH . '/images/photos/small/article' . $mod_id . '.jpg')) {
                ?>
                        <div style="margin-top:3px;margin-bottom:3px;padding:10px;border:solid 1px gray;text-align:center">
                            <?/*php<img src="/images/photos/small/article<?php 
                echo $id;
                ?>
.jpg" border="0" />*/?>
                            <img src="/images/photos/small/article<?php 
                echo $id_art;
                ?>
.jpg" border="0" />
                        </div>
                        <table cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td width="16"><input type="checkbox" id="delete_image" name="delete_image" value="1" /></td>
                                <td><label for="delete_image"><?php 
                echo $_LANG['AD_PHOTO_REMOVE'];
                ?>
</label></td>
                            </tr>
                        </table>
                        <?php 
            }
        }
        ?>
                        <input type="file" name="picture" style="width:100%" />
                    </div>

                    <div style="margin-top:25px"><strong><?php 
        echo $_LANG['AD_PUBLIC_PARAMETRS'];
        ?>
</strong></div>
                    <table width="100%" cellpadding="0" cellspacing="0" border="0" class="checklist">
                        <tr>
                            <td width="20"><input type="checkbox" name="show_in_new" id="show_in_new" value="1" <?php 
        if ($mod['show_in_new'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="show_in_new"><?php 
        echo $_LANG['AD_VIEW_NEW_CATS'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="show_in_footer" id="show_in_footer" value="1" <?php 
        if ($mod['show_in_footer'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="show_in_footer"><?php 
        echo $_LANG['AD_VIEW_FOOTER'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="showlatest" id="showlatest" value="1" <?php 
        if ($mod['showlatest'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="showlatest"><?php 
        echo $_LANG['AD_VIEW_NEW_ARTICLES'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="comments" id="comments" value="1" <?php 
        if ($mod['comments'] || $do == 'add') {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="comments"><?php 
        echo $_LANG['AD_ENABLE_COMMENTS'];
        ?>
</label></td>
                        </tr>
                        <tr>
                            <td width="20"><input type="checkbox" name="canrate" id="canrate" value="1" <?php 
        if ($mod['canrate']) {
            echo 'checked="checked"';
        }
        ?>
/></td>
                            <td><label for="canrate"><?php 
        echo $_LANG['AD_ENABLE_RATING'];
        ?>
</label></td>
                        </tr>
                    </table>

                    <?php 
        if ($do == 'add') {
            ?>
                        <div style="margin-top:25px">
                            <strong><?php 
            echo $_LANG['AD_CREATE_LINK'];
            ?>
</strong>
                        </div>
                        <div>
                            <select name="createmenu" id="createmenu" style="width:99%">
                                <option value="0" selected="selected"><?php 
            echo $_LANG['AD_DONT_CREATE_LINK'];
            ?>
</option>
                            <?php 
            foreach ($menu_list as $menu) {
                ?>
                                <option value="<?php 
                echo $menu['id'];
                ?>
">
                                    <?php 
                echo $menu['title'];
                ?>
                                </option>
                            <?php 
            }
            ?>
                            </select>
                        </div>
                    <?php 
        }
        ?>

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

                    <div style="margin-top:5px">
                        <strong><?php 
        echo $_LANG['AD_ARTICLE_TIME'];
        ?>
</strong>
                    </div>
                    <div>
                        <select name="is_end" id="is_end" style="width:99%" onchange="if($(this).val() == 1){ $('#final_time').show(); }else {$('#final_time').hide();}">
                            <option value="0" <?php 
        if (@(!$mod['is_end'])) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_UNLIMITED'];
        ?>
</option>
                            <option value="1" <?php 
        if (@$mod['is_end']) {
            echo 'selected="selected"';
        }
        ?>
><?php 
        echo $_LANG['AD_TO_FINAL_TIME'];
        ?>
</option>
                        </select>
                    </div>

                    <div id="final_time" <?php 
        if (@(!$mod['is_end'])) {
            echo 'style="display: none"';
        }
        ?>
>
                    <div style="margin-top:20px">
                        <strong><?php 
        echo $_LANG['AD_FINAL_TIME'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_CALENDAR_FORMAT'];
        ?>
</span>
                    </div>
                    <div><input name="enddate" type="text" style="width:80%" <?php 
        if (@(!$mod['is_end'])) {
            echo 'value="' . date('d.m.Y') . '"';
        } else {
            echo 'value="' . $mod['enddate'] . '"';
        }
        ?>
id="enddate" /></div></div>


                    {tab=SEO}

                    <div style="margin-top:5px">
                        <strong><?php 
        echo $_LANG['AD_PAGE_TITLE'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_IF_UNKNOWN_PAGETITLE'];
        ?>
</span>
                    </div>
                    <div>
                        <input name="pagetitle" type="text" id="pagetitle" style="width:99%" value="<?php 
        if (isset($mod['pagetitle'])) {
            echo htmlspecialchars($mod['pagetitle']);
        }
        ?>
" />
                    </div>

                    <div style="margin-top:20px">
                        <strong><?php 
        echo $_LANG['KEYWORDS'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_FROM_COMMA'];
        ?>
</span>
                    </div>
                    <div>
                         <textarea name="meta_keys" style="width:97%" rows="4" id="meta_keys"><?php 
        echo htmlspecialchars($mod['meta_keys']);
        ?>
</textarea>
                    </div>

                    <div style="margin-top:20px">
                        <strong><?php 
        echo $_LANG['DESCRIPTION'];
        ?>
</strong><br/>
                        <span class="hinttext"><?php 
        echo $_LANG['AD_LESS_THAN'];
        ?>
</span>
                    </div>
                    <div>
                         <textarea name="meta_desc" style="width:97%" rows="6" id="meta_desc"><?php 
        echo htmlspecialchars($mod['meta_desc']);
        ?>
</textarea>
                    </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 
        $sql = "SELECT * FROM cms_user_groups";
        $result = $inDB->query($sql);
        $style = 'disabled="disabled"';
        $public = 'checked="checked"';
        if ($do == 'edit') {
            $sql2 = "SELECT * FROM cms_content_access WHERE content_id = " . $mod['id'] . " AND content_type = 'material'";
            $result2 = $inDB->query($sql2);
            $ord = array();
            if ($inDB->num_rows($result2)) {
                $public = '';
                $style = '';
                while ($r = $inDB->fetch_assoc($result2)) {
                    $ord[] = $r['group_id'];
                }
            }
        }
        ?>
                                <input name="is_public" type="checkbox" id="is_public" onclick="checkGroupList()" 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_NOTED'];
        ?>
                        </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="showfor[]" id="showin" size="6" multiple="multiple" ' . $style . '>';
        if ($inDB->num_rows($result)) {
            while ($item = $inDB->fetch_assoc($result)) {
                echo '<option value="' . $item['id'] . '"';
                if ($do == 'edit') {
                    if (inArray($ord, $item['id'])) {
                        echo 'selected="selected"';
                    }
                }
                echo '>';
                echo $item['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" <?php 
        if ($do == 'add') {
            echo 'value="' . $_LANG['AD_CREATE_CONTENT'] . '"';
        } else {
            echo 'value="' . $_LANG['AD_SAVE_CONTENT'] . '"';
        }
        ?>
 />
            <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 
    }
}
Esempio n. 28
0
function wishes()
{
    $inCore = cmsCore::getInstance();
    $inPage = cmsPage::getInstance();
    $inDB = cmsDatabase::getInstance();
    $inUser = cmsUser::getInstance();
    $user_id = $inUser->id;
    //$inPage->addHeadJS('');
    //$inPage->addHeadJS('');
    global $_LANG;
    $inCore->loadModel('wishes');
    $model = new cms_model_wishes();
    //Загрузка настроек встреч
    $cfg = $inCore->loadComponentConfig('wishes');
    // Проверяем включени ли компонент
    if (!$cfg['component_enabled']) {
        cmsCore::error404();
    }
    if (!isset($cfg['perpage'])) {
        $cfg['perpage'] = 10;
    }
    if (!isset($cfg['on_main'])) {
        $cfg['on_main'] = 5;
    }
    //Получаем параметры
    $id = $inCore->request('id', 'int', 0);
    $do = $inCore->request('do', 'str', 'view');
    $page = $inCore->request('page', 'int', 1);
    $pagetitle = "Потрібно - Допоможу";
    $inPage->addPathway($pagetitle, '/wishes/all.html');
    $types = array();
    $sql = "select * from `cms_wishes_cat`";
    $result = $inDB->query($sql);
    $j = 1;
    while ($tinfo = $inDB->fetch_assoc($result)) {
        $types[$j]["1"] = $tinfo['class'];
        $types[$j]["2"] = $tinfo['title'];
        $j++;
    }
    $inPage->addHead('<link rel="stylesheet" href="/components/wishes/css/style.css">');
    /***********************************************************/
    if ($do == 'load') {
        $n = $inCore->request('n', 'int', 1);
        $page = $inCore->request('page', 'int', 1);
        //echo $page." ".$n." дозагрузка данных<br/>";
        $t = $types[$n];
        $inf = $model->wish_type($n, $t, $user_id, $page, $active = 0, $types = array(), $cfg['on_main']);
        echo $inf;
        exit;
    }
    if ($do == 'delete') {
        if ($model->is_author($user_id, $id) or $inUser->is_admin) {
            $sql = "DELETE FROM `cms_wishes` WHERE `id` = " . $id . ";";
            $result = $inDB->query($sql);
            cmsCore::addSessionMessage("Успішно видалено!", 'success');
        }
        cmsCore::redirect('/wishes/');
    }
    if ($do == 'wish_item') {
        $sql = "select * from `cms_wishes` where `published`='1' and `id`='" . $id . "' ";
        //echo $sql;
        $result = $inDB->query($sql);
        $sinfo = $inDB->fetch_assoc($result);
        $us = $inUser->loadUser($sinfo['user_id']);
        $t = $types[$sinfo['type']];
        $inPage->addPathway($t[2], '/wishes/type' . $sinfo['type'] . '.html');
        $inPage->addPathway($sinfo['title'], '');
        $inPage->setTitle($sinfo['title']);
        echo "<h2><a href='/wishes/type" . $sinfo['type'] . ".html'>" . $t[2] . "</a> &raquo; " . $sinfo['title'] . "</h2>";
        echo "<div style='font-size:11px;'><a href='/users/" . $us['login'] . "'>" . $us['nickname'] . "</a> | " . $inCore->dateformat($sinfo['datetime']) . "</div>";
        if ($model->is_author($user_id, $id) or $inUser->is_admin) {
            echo "<div style='float:right;'><a href='/wishes/delete" . $id . ".html'>Видалити</a></div>";
        }
        echo "\n\t\t\t<table width='100%'><tr><td valign='top' width='10%'>\n\t\t\t<a href='/users/" . $us['login'] . "'><img src='" . $us['imageurl'] . "' style='float:left;border-radius:10px;margin:0px 10px 10px 0px;' border='0' /></a>\n\t\t\t</td>\n\t\t\t<td>\n\t\t\t<div style='padding:10px;margin-bottom:50px; background-color:#f2f0f0; border-bottom: 1px solid #DDDDDD;border-top: 1px solid #DDDDDD;'>\n\t\t\t" . $sinfo['info'] . "</div>\n\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t";
        if ($inCore->isComponentInstalled('comments')) {
            cmsCore::includeComments();
            comments('wishes', $sinfo['id']);
        }
    }
    /***********************************************************/
    if ($do == 'add_item') {
        $title = $inCore->request('title', 'str', '');
        $info = $inCore->request('info', 'str', '');
        $send = $inCore->request('send', 'str', '');
        $type = $id;
        $guest_info = $inUser->getGuestInfo();
        $user_access = $inUser->id;
        if ($user_access > 0) {
            /**/
            /**/
            /**/
            /**/
            $inf = "0";
            $success = "0";
            $tr = strlen($title);
            if ($send == "ok") {
                if ($tr > 0) {
                    $ip = $_SERVER['REMOTE_ADDR'];
                    $browser = $_SERVER['HTTP_USER_AGENT'];
                    $sql = "INSERT INTO `cms_wishes` (`id` ,\n`title` ,\n`info` ,\n`published` ,\n`datetime` ,\n`user_id` ,\n`rate` ,\n`type` ,\n`ip` ,\n`browser` \n)\nVALUES (NULL , '" . $title . "', '" . $info . "', '1', NOW(), '" . $user_id . "', '0', '" . $type . "', '" . $ip . "', '" . $browser . "'\n);";
                    $inDB->query($sql);
                    $msg = "<span style='font-size:10px;'>Інформація успішно додана</span>";
                    cmsCore::addSessionMessage($msg, 'success');
                    $inf = "1";
                    $success = "1";
                    cmsCore::redirect('/wishes/');
                } else {
                    $msg = "<span style='font-size:10px;'>Ви не ввели заголовок!</span>";
                    cmsCore::addSessionMessage($msg, 'error');
                    $inf = "1";
                }
            }
            if ($inf != "1") {
                $msg = "<span style='font-size:10px;'>Заповніть поля Заголовок та Інформація.</span>";
                cmsCore::addSessionMessage($msg, 'info');
            }
            $pagetitle = "Додання в розділ &laquo;" . $types[$id][2] . "&raquo;";
            $inPage->addPathway($pagetitle, '');
            if ($success == "0") {
                echo "<h2>Додання в розділ &laquo;" . $types[$id][2] . "&raquo;</h2>";
                echo "<form action='' method='post'>\n\t\tЗаголовок:<br/>\n\t\t<input type='text' name='title' style='width:400px;' /><br/>\n\t\tІнформація &laquo;" . $types[$id][2] . "&raquo;<br/>\n\t\t\t<textarea name='info' style='width:400px;height:150px;'></textarea><br/>\n\t\t\t\t<input type='hidden' name='type' value='" . $id . "' />\n\t\t\t\t<input type='hidden' name='send' value='ok' />\n\t\t\t\t<input type='submit' value='Відправити'> <input type='button' value='Відміна' onclick='window.history.back()' />\n\t\t\t\t\t\n\t\t\n\t</form>\n\t";
            } else {
                echo "<a href='/wishes/all.html'>Перейти на початок</a>";
            }
            /**/
            /**/
            /**/
            /**/
        } else {
            $msg = "<span style='font-size:10px;'>Доступно тільки зареєстрованим користувачам</span> <input type='button' value='Вернуться' onclick='window.history.back()' />";
            cmsCore::addSessionMessage($msg, 'error');
        }
    }
    /***********************************************************/
    if ($do == 'type') {
        $n = $id;
        $t = $types[$n];
        $active = '1';
        $inf = $model->wish_type($n, $t, $user_id, $page, $active, $types, $cfg['perpage']);
        if ($n == 0) {
            $total = $inDB->rows_count("cms_wishes", "`published`=1");
        } else {
            $total = $inDB->rows_count("cms_wishes", "`type`='" . $n . "' and `published`=1");
        }
        if ($user_id <= 0) {
            $model->modal();
        }
        $name = $t[2];
        if ($n == 0) {
            $name = "Все";
        }
        $inPage->addPathway($name, '');
        echo "<h3><a href='/wishes/all.html'>На початок</a> &raquo; " . $name . "</h3>";
        echo "<a href='/wishes/add" . $n . ".html' class='usr_wall_addlink " . $t["1"] . "'>Допомогти</a>";
        echo $inf;
        if ($n == 0) {
            $pagination = cmsPage::getPagebar($total, $page, $cfg['perpage'], '/wishes/all-page%page%.html');
        } else {
            $pagination = cmsPage::getPagebar($total, $page, $cfg['perpage'], '/wishes/type' . $n . '-page%page%.html');
        }
        echo $pagination;
    }
    /***********************************************************/
    if ($do == 'view') {
        $st = "";
        $cntt = count($types);
        foreach ($types as $n => $t) {
            $links .= "&nbsp;<span style='border-radius:3px;border:1px dotted #999;color:#333;'><a href='/wishes/type" . intval($n) . ".html'>" . $t[2] . "</a></span>&nbsp;";
            $inf = $model->wish_type($n, $t, $user_id, $page = 1, $active = 0, $types = array(), $cfg['on_main']);
            //print_r($t);
            $st .= "<tr valign='top' ><div class='wish-type'><span style='font-size:20px;font-weight:bold;color:#333;'>\n\t\t<a href='/wishes/type" . $n . ".html'>" . $t["2"] . "</span> \n\t\t<br/>\n\t\t<div  >\n\t\t<a href='/wishes/add" . $n . ".html' class='usr_wall_addlink " . $t["1"] . "'>Допомогти</a>\n\t\t</div></div>\n\t\t<br/>\n\t\t" . $inf . "<br/>\n\t\t" . $inf1 . "\n\t\t<div id='rrr" . $n . "'></div>\n\t\t<div id='temp" . $n . "' style='display:none;'></div>\t\n\t\t<div style='text-align:center;'>\n\t\t<div id='imgload" . $n . "'></div>\n\t\t<input type='hidden' id='page" . $n . "' name='page" . $n . "' value='2'>\n\t\t</div>\n\t\t<input type='button' style='width:100%;' onclick='upload_wish(rrr" . $n . ",page" . $n . ", temp" . $n . "," . $n . ")' value='Завантажити ще'>\n\t\t</tr>";
        }
    }
}
Esempio n. 29
0
            }
        } else {
            cmsCore::addSessionMessage($_LANG['AD_ADDING_ERROR_TEXT'] . cmsCore::uploadError(), 'error');
            cmsCore::redirectBack();
        }
    } elseif ($opt == 'submit') {
        cmsCore::addSessionMessage($_LANG['AD_ADDING_ERROR_TEXT'], 'error');
        cmsCore::redirectBack();
    }
    if ($opt == 'update') {
        $sql = "UPDATE cms_banners\n                SET position = '{$position}',\n                    title = '{$title}',\n                    published = '{$published}',\n                    maxhits = '{$maxhits}',\n                    maxuser = '******',\n                    typeimg = '{$typeimg}',\n                    link = '{$link}'\n                WHERE id = '{$item_id}'";
        $inDB->query($sql);
        if (!isset($_SESSION['editlist']) || @sizeof($_SESSION['editlist']) == 0) {
            cmsCore::redirect('?view=components&do=config&opt=list&id=' . $id);
        } else {
            cmsCore::redirect('?view=components&do=config&opt=edit&id=' . $id);
        }
    }
}
if ($opt == 'delete') {
    $item_id = cmsCore::request('item_id', 'int', 0);
    $fileurl = $inDB->get_field('cms_banners', "id = '{$item_id}'", 'fileurl');
    if (!$fileurl) {
        cmsCore::error404();
    }
    @unlink($uploaddir . $fileurl);
    $inDB->query("DELETE FROM cms_banners WHERE id = '{$item_id}'");
    $inDB->query("DELETE FROM cms_banner_hits WHERE banner_id = '{$item_id}'");
    cmsCore::redirectBack();
}
if ($opt == 'list') {
Esempio n. 30
0
function files()
{
    $inDB = cmsDatabase::getInstance();
    global $_LANG;
    $do = cmsCore::getInstance()->do;
    //============================================================================//
    // Скачивание
    if ($do == 'view') {
        $fileurl = cmsCore::request('fileurl', 'str', '');
        if (!$fileurl) {
            cmsCore::error404();
        }
        $fileurl = mb_strpos($fileurl, '-') === 0 ? htmlspecialchars_decode(base64_decode(ltrim($fileurl, '-'))) : $fileurl;
        if (mb_strstr($fileurl, '..')) {
            cmsCore::error404();
        }
        if (mb_strstr($fileurl, 'http:/')) {
            if (!mb_strstr($fileurl, 'http://')) {
                $fileurl = str_replace('http:/', 'http://', $fileurl);
            }
        }
        $downloads = cmsCore::fileDownloadCount($fileurl);
        if ($downloads == 0) {
            $sql = "INSERT INTO cms_downloads (fileurl, hits) VALUES ('{$fileurl}', '1')";
            $inDB->query($sql);
        } else {
            $sql = "UPDATE cms_downloads SET hits = hits + 1 WHERE fileurl = '{$fileurl}'";
            $inDB->query($sql);
        }
        if (mb_strstr($fileurl, 'http:/')) {
            cmsCore::redirect($fileurl);
        }
        if (file_exists(PATH . $fileurl)) {
            header('Content-Disposition: attachment; filename=' . basename($fileurl) . "\n");
            header('Content-Type: application/x-force-download; name="' . $fileurl . '"' . "\n");
            header('Location:' . $fileurl);
            cmsCore::halt();
        } else {
            cmsCore::halt($_LANG['FILE_NOT_FOUND']);
        }
    }
    //============================================================================//
    if ($do == 'redirect') {
        $url = str_replace(array('--q--', ' '), array('?', '+'), cmsCore::request('url', 'str', ''));
        if (!$url) {
            cmsCore::error404();
        }
        $url = mb_strpos($url, '-') === 0 ? htmlspecialchars_decode(base64_decode(ltrim($url, '-'))) : $url;
        if (mb_strstr($url, '..')) {
            cmsCore::error404();
        }
        if (mb_strstr($url, 'http:/')) {
            if (!mb_strstr($url, 'http://')) {
                $url = str_replace('http:/', 'http://', $url);
            }
        }
        if (mb_strstr($url, 'https:/')) {
            if (!mb_strstr($url, 'https://')) {
                $url = str_replace('https:/', 'https://', $url);
            }
        }
        // кириллические домены
        $url_host = parse_url($url, PHP_URL_HOST);
        if (preg_match('/^[а-яё]+/iu', $url_host)) {
            cmsCore::loadClass('idna_convert');
            $IDN = new idna_convert();
            $host = $IDN->encode($url_host);
            $url = str_ireplace($url_host, $host, $url);
        }
        cmsCore::redirect($url);
    }
    //============================================================================//
}