Пример #1
0
function login_form_widget($num = 1)
{
    $out = '';
    $widget = 'login_form_widget_' . $num;
    // имя для опций = виджет + номер
    $options = mso_get_option($widget, 'plugins', array());
    // получаем опции
    if (is_login()) {
        $out = '<p><strong>' . t('Привет,') . ' ' . getinfo('users_nik') . '!</strong><br>
				[<a href="' . getinfo('siteurl') . 'admin">' . t('управление') . '</a>]
				[<a href="' . getinfo('siteurl') . 'logout' . '">' . t('выйти') . '</a>] 
				</p>';
    } elseif ($comuser = is_login_comuser()) {
        if (!$comuser['comusers_nik']) {
            $cun = t('Привет!');
        } else {
            $cun = t('Привет,') . ' ' . $comuser['comusers_nik'] . '!';
        }
        $out = '<p><strong>' . $cun . '</strong><br>
				[<a href="' . getinfo('siteurl') . 'users/' . $comuser['comusers_id'] . '">' . t('своя страница') . '</a>]
				[<a href="' . getinfo('siteurl') . 'logout' . '">' . t('выйти') . '</a>] 
				</p>';
    } else {
        $after_form = isset($options['after_form']) ? $options['after_form'] : '';
        $out = mso_login_form(array('login' => t('Логин (email):') . ' ', 'password' => t('Пароль:') . ' ', 'submit' => '', 'form_end' => $after_form), getinfo('siteurl') . mso_current_url(), false);
    }
    if ($out) {
        if (isset($options['header']) and $options['header']) {
            $out = mso_get_val('widget_header_start', '<h2 class="box"><span>') . $options['header'] . mso_get_val('widget_header_end', '</span></h2>') . $out;
        }
    }
    return $out;
}
Пример #2
0
function captcha_go($args = array())
{
    global $MSO;
    echo '
		<div class="captcha"><label for="comments_captha">' . tf('Введите нижние символы') . '</label>
		<input type="text" name="comments_captha" id="comments_captha" value="" maxlength="4" class="comments_captha"> <img src="' . create_captha_img(mso_md5($MSO->data['session']['session_id'] . mso_current_url())) . '" alt="" title="' . tf('Защита от спама: введите только нижние символы') . '"> <span>' . t('(обязательно)') . '</span><br><br></div>
		';
}
Пример #3
0
function captcha_go($args = array())
{
    global $MSO;
    # сама картинка формируется в img.php
    # в ней мы передаем сессию, текущую страницу и время (против кэширования)
    echo '
			<div class="captcha"><label for="comments_captha">' . tf('Введите нижние символы') . '</label>
			<input type="text" name="comments_captha" id="comments_captha" value="" maxlength="4" class="comments_captha"> <img src="' . getinfo('plugins_url') . 'captcha/img.php?image=' . $MSO->data['session']['session_id'] . '&amp;page=' . mso_slug(mso_current_url()) . '&amp;code=' . time() . '" alt="" title="' . tf('Защита от спама: введите только нижние символы') . '"> <span>' . t('(обязательно)') . '</span><br><br></div>
		';
}
Пример #4
0
function favorites_widget_custom($options = array(), $num = 1)
{
    $out = '';
    $siteurl = getinfo('siteurl');
    // адрес сайта
    $current_url = mso_current_url();
    // текущая страница относительно сайта
    if (!isset($options['header'])) {
        $options['header'] = '';
    }
    if (isset($options['favorites'])) {
        $favorites = explode("\n", $options['favorites']);
        // разбиваем по строкам
        foreach ($favorites as $row) {
            $ar = explode('|', $row);
            // разбиваем по |
            // всего должно быть 2 элемента
            if (isset($ar[0]) and trim($ar[0])) {
                $href = '//' . trim($ar[0]) . '//';
                // адрес
                // удалим ведущий и конечные слэши, если есть
                $href = trim(str_replace('/', ' ', $href));
                $href = str_replace(' ', '/', $href);
                if (isset($ar[1]) and trim($ar[1])) {
                    $title = trim($ar[1]);
                    // название
                    if ($href == $current_url) {
                        $class = ' class="current-page" ';
                    } else {
                        $class = '';
                    }
                    $out .= NR . '<li' . $class . '><a href="' . $siteurl . $href . '" title="' . $title . '">' . $title . '</a></li>';
                }
            }
        }
    }
    if ($out) {
        $out = $options['header'] . NR . '<ul class="is_link favorites">' . $out . NR . '</ul>' . NR;
    }
    return $out;
}
Пример #5
0
function internal_links_custom($text = '')
{
    static $a_link;
    // здесь хранится обработанный массив ссылок - чтобы не обрабатывать несколько раз
    global $_internal_links;
    $options = mso_get_option('plugin_internal_links', 'plugins', array());
    // только на page
    if (!isset($options['only_page_type'])) {
        $options['only_page_type'] = true;
    }
    if ($options['only_page_type'] and !is_type('page')) {
        return $text;
    }
    // не указаны ссылки
    if (!isset($options['links'])) {
        return $text;
    }
    if (!trim($options['links'])) {
        return $text;
    }
    if (!isset($options['default_class'])) {
        $options['default_class'] = '';
    }
    if (!isset($options['max_count'])) {
        $options['max_count'] = 1;
    } else {
        $options['max_count'] = (int) $options['max_count'];
    }
    if ($options['max_count'] === 0) {
        $options['max_count'] = -1;
    }
    // замена для preg_replace
    $links = explode("\n", str_replace("\r", '', trim($options['links'])));
    // все ссылки в массив
    if (!isset($a_link) or !$a_link) {
        $a_link = array();
        foreach ($links as $key => $link) {
            $l1 = explode('|', $link);
            if (isset($l1[0]) and isset($l1[1])) {
                $a_link[$key]['word'] = trim($l1[0]);
                $a_link[$key]['link'] = trim($l1[1]);
                if (strpos($a_link[$key]['link'], 'http://') === false) {
                    $a_link[$key]['link'] = getinfo('siteurl') . $a_link[$key]['link'];
                }
                if (isset($l1[2]) and trim($l1[2])) {
                    $a_link[$key]['class'] = trim($l1[2]);
                } else {
                    $a_link[$key]['class'] = trim($options['default_class']);
                }
            }
        }
    }
    $current_url = getinfo('siteurl') . mso_current_url(false);
    $limit = $options['max_count'];
    foreach ($a_link as $key) {
        $word = $key['word'];
        $link = $key['link'];
        if ($link == $current_url) {
            continue;
        }
        // ссылка на себя
        if (mb_stripos($text, $word, 0, 'UTF8') === false) {
            continue;
        }
        // нет вхождения
        if ($key['class']) {
            $class = ' class="' . $key['class'] . '"';
        } else {
            $class = '';
        }
        $regexp = '/(?!(?:[^<\\[]+[>\\]]|[^>\\]]+<\\/a>))(' . preg_quote($word, '/') . ')/usUi';
        $replace = "<a href=\"" . $link . "\"" . $class . ">\$0</a>";
        $text = preg_replace($regexp, $replace, $text, $limit);
    }
    // pr($text,1);
    return $text;
}
Пример #6
0
<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
/**
 * MaxSite CMS
 * (c) http://max-3000.com/
 */
header('Content-type: text/html; charset=utf-8');
header('Content-Type: application/rss+xml');
$cache_key = mso_md5('feed_' . mso_current_url());
$k = mso_get_cache($cache_key);
if ($k) {
    return print $k;
}
// да есть в кэше
ob_start();
require_once getinfo('common_dir') . 'page.php';
// основные функции страниц
require_once getinfo('common_dir') . 'category.php';
// функции рубрик
$this->load->helper('xml');
$time_zone = getinfo('time_zone');
// 2.00 -> 200
$time_zone_server = date('O') / 100;
// +0100 -> 1.00
$time_zone = $time_zone + $time_zone_server;
// 3
$time_zone = number_format($time_zone, 2, '.', '');
// 3.00
Пример #7
0
function last_pages_widget_custom($arg = array(), $num = 1)
{
    if (!isset($arg['count'])) {
        $arg['count'] = 7;
    }
    if (!isset($arg['page_type'])) {
        $arg['page_type'] = 'blog';
    }
    if (!isset($arg['sort'])) {
        $arg['sort'] = 'page_date_publish';
    }
    if (!isset($arg['sort_order'])) {
        $arg['sort_order'] = 'desc';
    }
    if (!isset($arg['date_format'])) {
        $arg['date_format'] = 'd/m/Y';
    }
    if (!isset($arg['format'])) {
        $arg['format'] = '%TITLE%';
    }
    if (!isset($arg['comments_format'])) {
        $arg['comments_format'] = t(' - комментариев: ') . '%COUNT%';
    }
    if (!isset($arg['exclude_cat'])) {
        $arg['exclude_cat'] = '';
    }
    if (!isset($arg['include_cat'])) {
        $arg['include_cat'] = '';
    }
    if (!isset($arg['img_prev'])) {
        $arg['img_prev'] = '';
    }
    if (!isset($arg['img_prev_def'])) {
        $arg['img_prev_def'] = '';
    }
    if (!isset($arg['img_prev_attr'])) {
        $arg['img_prev_attr'] = 'class="left"';
    }
    if (!isset($arg['max_words'])) {
        $arg['max_words'] = 20;
    }
    if (!isset($arg['text_posle'])) {
        $arg['text_posle'] = '';
    }
    if (!isset($arg['header'])) {
        $arg['header'] = mso_get_val('widget_header_start', '<h2 class="box"><span>') . t('Последние записи') . mso_get_val('widget_header_end', '</span></h2>');
    }
    if (!isset($arg['block_start'])) {
        $arg['block_start'] = '<div class="last-pages"><ul class="is_link">';
    }
    if (!isset($arg['block_end'])) {
        $arg['block_end'] = '</ul></div>';
    }
    $cache_key = 'last_pages_widget' . serialize($arg) . $num;
    $k = mso_get_cache($cache_key);
    if ($k) {
        $current_url = getinfo('siteurl') . mso_current_url();
        // текущий урл
        $k = str_replace('<a href="' . $current_url . '">', '<a href="' . $current_url . '" class="current_url">', $k);
        return $k;
    }
    $arg['exclude_cat'] = mso_explode($arg['exclude_cat']);
    // рубрики из строки в массив
    $arg['include_cat'] = mso_explode($arg['include_cat']);
    // рубрики из строки в массив
    $CI =& get_instance();
    if (strpos($arg['format'], '%TEXT%') === false and strpos($arg['format'], '%TEXT_CUT%') === false and strpos($arg['format'], '%TEXT_PREV%') === false) {
        $CI->db->select('page.page_id, page_type_name, page_type_name AS page_content, page_slug, page_title, page_date_publish, page_status, COUNT(comments_id) AS page_count_comments', false);
    } else {
        $CI->db->select('page.page_id, page.page_content, page_type_name, page_slug, page_title, page_date_publish, page_status, COUNT(comments_id) AS page_count_comments');
    }
    $CI->db->from('page');
    $CI->db->where('page_status', 'publish');
    //$CI->db->where('page_date_publish <', date('Y-m-d H:i:s'));
    $time_zone = getinfo('time_zone');
    if ($time_zone < 10 and $time_zone > 0) {
        $time_zone = '0' . $time_zone;
    } elseif ($time_zone > -10 and $time_zone < 0) {
        $time_zone = '0' . $time_zone;
        $time_zone = str_replace('0-', '-0', $time_zone);
    } else {
        $time_zone = '00.00';
    }
    $time_zone = str_replace('.', ':', $time_zone);
    // $CI->db->where('page_date_publish < ', 'NOW()', false);
    $CI->db->where('page_date_publish < ', 'DATE_ADD(NOW(), INTERVAL "' . $time_zone . '" HOUR_MINUTE)', false);
    if ($arg['page_type']) {
        $CI->db->where('page_type_name', $arg['page_type']);
    }
    $CI->db->join('page_type', 'page_type.page_type_id = page.page_type_id');
    $CI->db->join('comments', 'comments.comments_page_id = page.page_id AND comments_approved = 1', 'left');
    if ($arg['exclude_cat']) {
        $CI->db->join('cat2obj', 'cat2obj.page_id = page.page_id', 'left');
        $CI->db->where_not_in('cat2obj.category_id', $arg['exclude_cat']);
    }
    if ($arg['include_cat']) {
        $CI->db->join('cat2obj', 'cat2obj.page_id = page.page_id', 'left');
        $CI->db->where_in('cat2obj.category_id', $arg['include_cat']);
    }
    $CI->db->order_by($arg['sort'], $arg['sort_order']);
    $CI->db->group_by('page.page_id');
    $CI->db->group_by('comments_page_id');
    $CI->db->limit($arg['count']);
    $query = $CI->db->get();
    if ($query->num_rows() > 0) {
        $pages = $query->result_array();
        require_once getinfo('common_dir') . 'category.php';
        require_once getinfo('common_dir') . 'meta.php';
        $all_cat = mso_cat_array_single();
        // все рубрики
        $out = '';
        foreach ($pages as $key => $page) {
            // метаполе превьюшки
            if (strpos($arg['format'], '%IMG_PREV%') !== false) {
                if ($img_prev = mso_get_meta($arg['img_prev'], 'page', $page['page_id'])) {
                    if (isset($img_prev[0]['meta_value']) and $img_prev[0]['meta_value']) {
                        $img_prev = '<img src="' . $img_prev[0]['meta_value'] . '" alt="" ' . $arg['img_prev_attr'] . '> ';
                    } else {
                        $img_prev = '<img src="' . $arg['img_prev_def'] . '" alt="" ' . $arg['img_prev_attr'] . '> ';
                    }
                } else {
                    if ($arg['img_prev_def']) {
                        $img_prev = '<img src="' . $arg['img_prev_def'] . '" alt="" ' . $arg['img_prev_attr'] . '> ';
                    } else {
                        $img_prev = '';
                    }
                }
            } else {
                $img_prev = '';
            }
            $out .= $arg['format'];
            $out = str_replace('%TITLE%', mso_page_title(mso_slug($page['page_slug']), $page['page_title'], '', '', true, false), $out);
            $out = str_replace('%URL%', getinfo('site_url') . 'page/' . mso_slug($page['page_slug']), $out);
            $out = str_replace('%DATE%', mso_page_date($page['page_date_publish'], $arg['date_format'], '', '', false), $out);
            if ($page['page_count_comments']) {
                $comments_format = str_replace('%COUNT%', $page['page_count_comments'], $arg['comments_format']);
            } else {
                $comments_format = '';
            }
            $out = str_replace('%COMMENTS%', $comments_format, $out);
            $page_content = $page['page_content'];
            $page_content = mso_hook('content', $page_content);
            $page_content = mso_hook('content_auto_tag', $page_content);
            $page_content = mso_hook('content_balance_tags', $page_content);
            $page_content = mso_hook('content_out', $page_content);
            $out = str_replace('%TEXT%', mso_balance_tags(mso_auto_tag(mso_hook('content_complete', $page['page_content']))), $out);
            if (strpos($arg['format'], '%TEXT_PREV%') !== false) {
                $page_content = $page['page_content'];
                $page_content = mso_hook('content', $page_content);
                $page_content = mso_hook('content_auto_tag', $page_content);
                $page_content = mso_hook('content_complete', $page_content);
                $page_content = mso_str_word(strip_tags($page_content), $arg['max_words']) . ' ...';
                $out = str_replace('%TEXT_PREV%', $page_content, $out);
            }
            # если есть cut, то обрабатываем и его
            $page_content = str_replace('[xcut', '[cut', $page_content);
            if (preg_match('/\\[cut(.*?)?\\]/', $page_content, $matches)) {
                $page_content = explode($matches[0], $page_content, 2);
                $page_content = $page_content[0];
                $page_content = mso_hook('content_complete', $page_content);
            }
            $out = str_replace('%TEXT_CUT%', mso_balance_tags(mso_auto_tag($page_content)), $out);
            $out = str_replace('%IMG_PREV%', $img_prev, $out);
            if (is_type_slug('page', mso_slug($page['page_slug']))) {
                $out = str_replace('<li>', '<li class="current_url_page">', $out);
            }
            if (isset($arg['include_cat'][0]) and is_page_cat($arg['include_cat'][0])) {
                $out = str_replace('<li>', '<li class="current_url_cat">', $out);
            }
            if (isset($arg['include_cat'][0]) and is_type_slug('category', $all_cat[$arg['include_cat'][0]]['category_slug']) and in_array($page['page_id'], $all_cat[$arg['include_cat'][0]]['pages'])) {
                $out = str_replace('<li>', '<li class="current_url_allcat">', $out);
            }
        }
        $out = $arg['header'] . $arg['block_start'] . NR . $out . $arg['block_end'];
        $out = str_replace('</li>', '<div class="clearfix"></div></li>', $out);
        $out .= $arg['text_posle'];
        mso_add_cache($cache_key, $out);
        // сразу в кэш добавим
        // отметим текущую рубрику. Поскольку у нас к кэше должен быть весь список и не делать кэш для каждого url
        // то мы просто перед отдачей заменяем текущий url на url с li.current_url
        $current_url = getinfo('siteurl') . mso_current_url();
        // текущий урл
        $out = str_replace('<a href="' . $current_url . '">', '<a href="' . $current_url . '" class="current_url">', $out);
        return $out;
    }
}
Пример #8
0
function redirect_custom_page_404($args = false)
{
    // это почти аналог redirect_init с той разницей, что
    // хук срабатывает только при page_404
    // получаем опции
    // в опциях all - строки с редиректами
    // загоняем их в массив
    // смотрим текущий url
    // если он есть в редиректах, то редиректимся
    $options = mso_get_option('redirect', 'plugins', array());
    if (!isset($options['all404'])) {
        return $args;
    }
    // нет опций
    $all = explode("\n", $options['all404']);
    // разобъем по строкам
    if (!$all) {
        return $args;
    }
    // пустой массив
    // текущий адрес
    $current_url = mso_current_url(true);
    foreach ($all as $row) {
        $urls = explode('|', $row);
        //  адрес | редирект | 301, 302
        $urls = array_map('trim', $urls);
        if (isset($urls[0]) && isset($urls[1]) && $urls[0] && $urls[1]) {
            //проверяем, используются ли шаблоны в $urls[0]
            if (preg_match("/\\(.*\\)+/", $urls[0])) {
                $patern = preg_replace("![\\-\\?]+!", '\\\\$0', $urls[0]);
                if (preg_match("!" . $patern . "!i", $current_url, $match)) {
                    $urls[0] = $match[0];
                    $cn = count($match);
                    for ($i = 1; $i < $cn; $i++) {
                        $urls[1] = str_replace('$' . $i, $match[$i], $urls[1]);
                    }
                }
            }
            //
            if ($current_url != $urls[0]) {
                continue;
            }
            // адреса разные
            // совпали, делаем редирект
            if (isset($urls[2])) {
                mso_redirect($urls[1], true, $urls[2]);
            } else {
                mso_redirect($urls[1], true);
            }
        }
    }
    return $args;
}
Пример #9
0
} else {
    // тут форма, если не было post
    echo '<div class="mso-guestbook"><form method="post">' . mso_form_session('f_session_id');
    foreach ($options['fields_arr'] as $key => $val) {
        echo '<p><label><span>' . t($val) . '</span>';
        if ($key != 'text') {
            echo '<input name="f_fields_guestbook[' . $key . ']" type="text"></label></p>';
        } else {
            echo '<textarea name="f_fields_guestbook[' . $key . ']" rows="10"></textarea></label></p>';
        }
    }
    // капча из плагина капчи
    if (!function_exists('create_captha_img')) {
        require_once getinfo('plugins_dir') . 'captcha/index.php';
    }
    $captcha = '<img src="' . create_captha_img(mso_md5($MSO->data['session']['session_id'] . mso_current_url())) . '" title="' . t('Защита от спама: введите только нижние символы') . '">';
    echo '<p><label><span>' . t('Нижние символы:') . $captcha . '</span>
		<input type="text" name="f_guestbook_captha" value="" maxlength="4" required></label></p>';
    echo '<p><button type="submit" class="i submit" name="f_submit_guestbook">' . t('Отправить') . '</button></p>';
    echo '</form></div>';
}
// тут последние отзывы с пагинацией
// нам нужна все поля таблицы
// вначале определим общее количество записей
$pag = array();
// пагинация
$pag['limit'] = $options['limit'];
// записей на страницу
$pag['type'] = '';
// тип
$CI->db->select('guestbook_id');
Пример #10
0
" title="<?php 
echo t('Вернуться к сайту');
?>
"><?php 
echo getinfo('name_site');
?>
</a></p>
	<p id="cms_name"><span>M</span>ax<span>S</span>ite CMS</p>
	<p id="entry"><?php 
echo t('Для входа в админ-панель введите логин и пароль');
?>
</p>

<?php 
if (!is_login()) {
    $redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : getinfo('siteurl') . mso_current_url();
    mso_remove_hook('login_form_auth');
    # удалим все хуки для авторизации
    mso_login_form(array('login' => t('Логин'), 'password' => t('Пароль'), 'submit' => '', 'submit_value' => t('Войти'), 'form_end' => '<br clear="all">'), $redirect_url);
}
?>

	<p id="cms">&copy; <a href="http://max-3000.com/" target="_blank" title="<?php 
echo t('Система управления сайтом MaxSite CMS');
?>
">MaxSite CMS</a>, 2008&ndash;<?php 
echo date('Y');
?>
</p>
</div>
</body>
Пример #11
0
function maxsite_auth_custom($args = array())
{
    if (mso_segment(1) == 'maxsite-auth-form') {
        // здесь формируется форма для отправки запроса
        // данные отправляются POST
        // посетитель должен указать только адрес своего сайта
        // в hidden указываем нужные данные
        $redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : getinfo('siteurl');
        echo '<html><head>
		<title>Авторизация</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		</head><body>
			<form method="post" action="' . getinfo('site_url') . 'maxsite-auth-form-post">
				<input type="hidden" name="redirect_url" value="' . urlencode($redirect_url) . '">
				Укажите адрес сайта (с http://): <input type="text" name="url" value="" size="80">
				<button type="submit">' . tf('Перейти к сайту') . '</button>
			</form>
		</body></html>';
        die;
        // Форма ОК
    } elseif (mso_segment(1) == 'maxsite-auth-form-post') {
        // здесь происходит приём указанного адреса сайта и редирект на него с нужными данными
        if ($post = mso_check_post(array('redirect_url', 'url'))) {
            $url = mb_strtolower($post['url']);
            $url = trim(str_replace('/', ' ', $url));
            $url = trim(str_replace('  ', ' ', $url));
            $url = trim(str_replace(' ', '/', $url));
            $url = str_replace('http:/', 'http://', $url);
            $url = $url . '/maxsite-auth-receive/' . base64_encode(getinfo('siteurl') . '##' . urldecode($post['redirect_url']) . '##' . substr(mso_md5(getinfo('siteurl')), 1, 5));
            mso_redirect($url, true);
        } else {
            mso_redirect('maxsite-auth-form');
        }
        // ошибочная форма - возвращаемся
    } elseif (mso_segment(1) == 'maxsite-auth-receive') {
        // принимаем входящие данные от другого сайта
        // здесь запрос на авторизацию
        // нужно проверить все входящие данные
        // проверить is_login
        // и сформировать форму с отправкой на входящий_сайт/maxsite-auth-reply
        if (!is_login()) {
            echo '<html><head>
		<title>Авторизация</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		</head><body>
			<div class="loginform">' . tf('Для авторизации необходимо войти на сайт') . '<br>';
            mso_login_form(array('login' => tf('Логин:') . ' ', 'password' => tf('Пароль:') . ' ', 'submit' => ''), getinfo('siteurl') . mso_current_url());
            echo '</div></body></html>';
            die;
            // выходим ОК
        } else {
            //проверяем разрешения группы
            if (!mso_check_allow('maxsite_auth_edit')) {
                die(tf('Доступ к авторизации запрещен'));
            }
            $options = mso_get_option('plugin_maxsite_auth', 'plugins', array());
            if (!isset($options['email']) or !$options['email']) {
                die(tf('Не задан ответный email'));
            }
            if (!isset($options['password']) or !$options['password']) {
                die(tf('Не задан ответный пароль'));
            }
            // смотрятся входные get-данные (расшифровка из base64) адрес-сайт1
            $data64 = mso_segment(2);
            if (!$data64) {
                die(tf('Нет данных'));
            }
            // отладка
            //	echo (getinfo('siteurl') . '##'. 'page/about' . '##' . substr(mso_md5(getinfo('siteurl')), 1, 5));
            //	echo '<br>'. base64_encode((getinfo('siteurl') . '##'. 'page/about' . '##' . substr(mso_md5(getinfo('siteurl')), 1, 5)));
            //	echo '<br>';
            // распаковываем данные
            $data = @base64_decode($data64);
            if (!$data) {
                die(tf('Ошибочные данные'));
            }
            //	адрес-сайт1##адрес текущей страницы1##открытый ключ
            $data = explode('##', $data);
            // обработаем предварительно массив
            $data_1 = array();
            foreach ($data as $element) {
                if ($d = trim($element)) {
                    $data_1[] = $d;
                }
            }
            // должно быть 3 элемента
            if (count($data_1) != 3) {
                die(tf('Неверное количество данных'));
            }
            // pr($data_1);
            $data_siteurl = $data_1[0];
            $data_redirect = $data_1[1];
            $data_key = $data_1[2];
            // все проверки пройдены
            // выводим форму с кнопкой Разрешить
            // данные для ответа
            //	- адрес исходный
            //	- адрес ответ - текущий
            //	- адрес текущей страницы1 - редирект
            //	- открытый ключ сайта2
            //	- зашифрованный «email##пароль» на основе открытых ключей сайт1 и сайт2
            $CI =& get_instance();
            $CI->load->library('encrypt');
            // подключим библиотеку для шифрования
            // ключ строится по этому алгоритму
            // он должен быть фиксированным для одного сайта
            $my_key = substr(mso_md5(getinfo('siteurl')), 1, 5);
            // шифруем на основе двух ключей
            $my_email_pass = $CI->encrypt->encode($options['email'] . '##' . $options['password'], $data_key . $my_key);
            $data = getinfo('siteurl') . '##' . $data_siteurl . '##' . $data_redirect . '##' . $my_key . '##' . $my_email_pass;
            // pr($data);
            // pr($CI->encrypt->decode($my_email_pass, $data_key . $my_key));
            echo '<html><head>
		<title>Авторизация</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		</head><body>
			<form method="post" action="' . $data_siteurl . 'maxsite-auth-reply">
				<input type="hidden" name="data" value="' . base64_encode($data) . '">
				<button type="submit">' . tf('Подтвердить авторизацию') . '</button>
			</form>
			</body></html>';
            die;
            // выход ОК
        }
    } elseif (mso_segment(1) == 'maxsite-auth-reply') {
        // принимаем данные для авторизации от другого сайта
        // должен быть email и пароль
        // проверяем входящие данные
        // проверяем существаание такого комюзера
        // если его нет, то выполняем авторизацию
        // после выполняем автологин
        // и редиректимся на указанную страницу
        // pr($_POST);
        if ($post = mso_check_post(array('data'))) {
            // проверим referer
            if (!isset($_SERVER['HTTP_REFERER'])) {
                die(t('Ошибочный referer-сайт'));
            }
            $data = @base64_decode($post['data']);
            if (!$data) {
                die(t('Ошибочные данные'));
            }
            // ошибка распаковки
            // pr($data);
            $data = explode('##', $data);
            // обработаем предварительно массив
            $data_1 = array();
            foreach ($data as $element) {
                if ($d = trim($element)) {
                    $data_1[] = $d;
                }
            }
            // должно быть 5 элементов
            if (count($data_1) != 5) {
                die(t('Неверное количество данных'));
            }
            /*
            			$data = getinfo('siteurl') . '##'
            					. $data_siteurl . '##'
            					. $data_redirect . '##'
            					. $my_key . '##'
            					. $my_email_pass;
            */
            // pr($data_1);
            $data_siteurl = $data_1[0];
            // сайт где была сделана авторизация = реферер
            $my_siteurl = $data_1[1];
            // сайт с которого был отправлен запрос на авторизацию - должен быть равен текущему
            $data_redirect = $data_1[2];
            // конечная страница
            $data_key = $data_1[3];
            // открытый ключ сайта-авторизатора
            $data_email_pass = $data_1[4];
            // email и пароль
            if (strpos($_SERVER['HTTP_REFERER'], $data_siteurl) === false) {
                die(t('Ошибочный referer-сайт'));
            }
            if ($my_siteurl != getinfo('siteurl')) {
                die(t('Ошибочный исходный сайт'));
            }
            $CI =& get_instance();
            $CI->load->library('encrypt');
            // подключим библиотеку для шифрования
            // ключ строится по этому алгоритму
            // он должен быть фиксированным для одного сайта
            $my_key = substr(mso_md5(getinfo('siteurl')), 1, 5);
            // шифруем на основе двух ключей
            $my_email_pass = $CI->encrypt->decode($data_email_pass, $my_key . $data_key);
            //_pr($my_email_pass);
            $email_pass = explode('##', $my_email_pass);
            if (count($email_pass) != 2) {
                die(tf('Неверные данные email-пароль'));
            }
            $email = $email_pass[0];
            // email
            $pass = $email_pass[1];
            // пароль
            if (!mso_valid_email($email)) {
                die(t('Неверный email'));
            }
            if (strlen($pass) < 6) {
                die(tf('Короткий пароль'));
            }
            // pr($email . ' ' . $pass);
            require_once getinfo('common_dir') . 'comments.php';
            mso_comuser_auth(array('email' => $email, 'password' => $pass));
            die;
            // выход ОК
        } else {
            die('Ошибочные данные');
        }
        // нет POST
    } else {
        return $args;
    }
}
Пример #12
0
function pagination_go($r = array())
{
    global $MSO;
    $r_orig = $r;
    if (!$r) {
        return $r;
    }
    if (!isset($r['maxcount'])) {
        return $r;
    }
    if (!isset($r['limit'])) {
        return $r;
    }
    // нужно указать сколько записей выводить
    if (!isset($r['type'])) {
        $r['type'] = false;
    }
    // можно задать свой тип
    if (!isset($r['next_url'])) {
        $r['next_url'] = 'next';
    }
    $options = mso_get_option('plugin_pagination', 'plugins', array());
    // получаем опции
    if (!isset($r['range'])) {
        $r['range'] = isset($options['range']) ? (int) $options['range'] : 3;
    }
    if (!isset($r['sep'])) {
        $r['sep'] = isset($options['sep']) ? $options['sep'] : ' ';
    }
    if (!isset($r['sep2'])) {
        $r['sep2'] = isset($options['sep2']) ? $options['sep2'] : ' ';
    }
    if (!isset($r['format'])) {
        // $r['format'] =
        $r['format'][] = isset($options['format_first']) ? $options['format_first'] : '&lt;&lt;';
        $r['format'][] = isset($options['format_prev']) ? $options['format_prev'] : '&lt;';
        $r['format'][] = isset($options['format_next']) ? $options['format_next'] : '&gt;';
        $r['format'][] = isset($options['format_last']) ? $options['format_last'] : '&gt;&gt;';
    }
    # текущая пагинация вычисляется по адресу url
    # должно быть /next/6 - номер страницы
    $current_paged = mso_current_paged($r['next_url']);
    if ($current_paged > $r['maxcount']) {
        $current_paged = $r['maxcount'];
    }
    if ($r['type'] !== false) {
        $type = $r['type'];
    } else {
        $type = $MSO->data['type'];
    }
    // текущий адрес
    $cur_url = mso_current_url(true);
    // в текущем адресе нужно исключить пагинацию next
    if (preg_match("!/" . $r['next_url'] . "/!is", $cur_url, $matches, PREG_OFFSET_CAPTURE)) {
        $cur_url = substr($cur_url, 0, $matches[0][1]);
    }
    if ($type == 'home' and $current_paged == 1) {
        $cur_url = $cur_url . 'home';
    }
    // pr($cur_url);
    if ($type == 'home') {
        $home_url = getinfo('site_url');
    } else {
        $home_url = $cur_url;
    }
    $out = _pagination($r['maxcount'], $current_paged, $cur_url . '/' . $r['next_url'] . '/', $r['range'], $cur_url, '', $r['sep'], $home_url, $r['sep2']);
    if ($out) {
        $out = str_replace(array('%FIRST%', '%PREV%', '%NEXT%', '%LAST%'), $r['format'], $out);
        echo '<div class="pagination"><nav>' . $out . '</nav></div>';
    }
    return $r_orig;
}
Пример #13
0
function _mso_logout()
{
    $ci =& get_instance();
    $ci->session->sess_destroy();
    $url = (isset($_SERVER['HTTP_REFERER']) and $_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    // проверяем, чтобы url был текущего сайта
    $pos = strpos($url, getinfo('site_url'));
    if ($pos === false or $pos > 0) {
        $url = '';
    }
    // чужой, сбрасываем переход
    // сразу же удаляем куку комюзера
    $comuser = mso_get_cookie('maxsite_comuser', false);
    if ($comuser) {
        $name_cookies = 'maxsite_comuser';
        $expire = time() - 60 * 60 * 24 * 365;
        // 365 дней
        $value = '';
        // mso_add_to_cookie('mso_edit_form_comuser', '', $expire);
        mso_add_to_cookie($name_cookies, $value, $expire, getinfo('siteurl') . mso_current_url());
        // в куку для всего сайта
    } elseif ($url) {
        mso_redirect($url, true);
    } else {
        mso_redirect(getinfo('site_url'), true);
    }
}
Пример #14
0
function loginza_auth_page_comment_form($args = array())
{
    $options = mso_get_option('plugin_loginza_auth', 'plugins', array());
    // получаем опции
    if (!isset($options['widget_type'])) {
        $options['widget_type'] = 1;
    }
    $widget_type = $options['widget_type'];
    if (!isset($options['auth_title']) or empty($options['auth_title'])) {
        $options['auth_title'] = 'Loginza';
    }
    $auth_title = $options['auth_title'];
    if (!isset($options['providers_set'])) {
        $options['providers_set'] = 'google, yandex, facebook, twitter, loginza, myopenid, webmoney, openid';
    }
    $providers_set = $options['providers_set'];
    $curpage = getinfo('siteurl') . mso_current_url();
    $current_url = getinfo('siteurl') . 'maxsite-loginza-auth?' . $curpage;
    $auth_url = "https://loginza.ru/api/widget?token_url=" . urlencode($current_url . '#comments');
    if (!empty($providers_set)) {
        $providers_set = str_replace(' ', '', $providers_set);
        $auth_url .= '&amp;providers_set=' . $providers_set;
    } else {
        // пока что так
        $auth_url .= '&amp;providers_set=' . 'google,yandex,facebook,twitter,loginza,myopenid,webmoney,openid';
    }
    if ($widget_type == 0) {
        echo '<span><a rel="nofollow" href="' . $auth_url . '" class="loginza loginza_auth">';
        echo '<img src="http://loginza.ru/img/sign_in_button_gray.gif" alt="Войти через loginza"/></a></span>';
    } else {
        echo '<script src="http://s1.loginza.ru/js/widget.js"></script>';
        echo '<span><a rel="nofollow" href="' . $auth_url . '" class="loginza_auth">' . $auth_title . '</a></span>';
    }
    return $args;
}
Пример #15
0
function addzakl_content_end($args = array())
{
    global $page;
    $options = mso_get_option('plugin_addzakl', 'plugins', array());
    $def_options = array('size' => 16, 'text-do' => '', 'text-posle' => '', 'twitter' => 1, 'facebook' => 1, 'vkontakte' => 1, 'odnoklassniki' => 1, 'mail-ru' => 1, 'yaru' => 1, 'rutvit' => 1, 'myspace' => 1, 'technorati' => 1, 'digg' => 1, 'friendfeed' => 1, 'pikabu' => 1, 'blogger' => 1, 'liveinternet' => 1, 'livejournal' => 1, 'memori' => 1, 'google-bookmarks' => 1, 'bobrdobr' => 1, 'mister-wong' => 1, 'yahoo-bookmarks' => 1, 'yandex' => 1, 'delicious' => 1, 'gplusone' => 1);
    $options = array_merge($def_options, $options);
    $size = (int) $options['size'];
    // размер икнонок
    $sep = ' ';
    # разделитель мужду кнопками - можно указать свой
    # ширина и высота картинок
    $width_height = ' width="' . $size . '" height="' . $size . '"';
    if ($size == 16) {
        // если размер 16, то каталог /images/
        $path = getinfo('plugins_url') . 'addzakl/images/';
    } else {
        // каталог /imagesXX/
        $path = getinfo('plugins_url') . 'addzakl/images' . $size . '/';
    }
    # путь к картинкам
    $post_title = urlencode(stripslashes($page['page_title'] . ' - ' . mso_get_option('name_site', 'general')));
    $post_link = getinfo('siteurl') . mso_current_url();
    $out = '';
    if ($options['twitter']) {
        $img_src = 'twitter.png';
        $link = '<a rel="nofollow" href="http://twitter.com/home/?status=' . urlencode(stripslashes(mb_substr($page['page_title'], 0, 139 - mb_strlen($post_link, 'UTF8'), 'UTF8') . ' ' . $post_link)) . '">';
        $out .= $link . '<img title="Добавить в Twitter" alt="twitter.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['facebook']) {
        $img_src = 'facebook.png';
        $link = '<a rel="nofollow" href="http://www.facebook.com/sharer.php?u=' . $post_link . '">';
        $out .= $sep . $link . '<img title="Поделиться в Facebook" alt="facebook.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['vkontakte']) {
        $img_src = 'vkontakte.png';
        $link = '<a rel="nofollow" href="http://vkontakte.ru/share.php?url=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Поделиться В Контакте" alt="vkontakte.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['odnoklassniki']) {
        $img_src = 'odnoklassniki.png';
        $link = '<a rel="nofollow" href="http://www.odnoklassniki.ru/dk?st.cmd=addShare&amp;st._surl=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Добавить в Одноклассники" alt="odnoklassniki.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['mail-ru']) {
        $img_src = 'mail-ru.png';
        $link = '<a rel="nofollow" href="http://connect.mail.ru/share?url=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Поделиться в Моем Мире@Mail.Ru" alt="mail.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['yaru']) {
        $img_src = 'yaru.png';
        $link = '<a rel="nofollow" href="http://my.ya.ru/posts_add_link.xml?URL=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Поделиться в Я.ру" alt="ya.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['rutvit']) {
        $img_src = 'rutvit.png';
        $link = '<a rel="nofollow" href="http://rutvit.ru/tools/widgets/share/popup?url=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Добавить в РуТвит" alt="rutvit.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['myspace']) {
        $img_src = 'myspace.png';
        $link = '<a rel="nofollow" href="http://www.myspace.com/Modules/PostTo/Pages/?u=' . $post_link . '&amp;t=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Добавить в MySpace" alt="myspace.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    /*
    if ($options['buzz'])
    {
    	$img_src = 'buzz.png';
    	$link = '<a rel="nofollow" href="http://www.google.com/buzz/post?message=' . $post_link . '&amp;url=' . $post_title . '&amp;srcURL=' . getinfo('siteurl') . '">';
    	$out .= $sep . $link . '<img title="Добавить в Google Buzz" alt="Google Buzz" src="' . $path . $img_src  . '"' . $width_height . '></a>';		
    }
    */
    if ($options['technorati']) {
        $img_src = 'technorati.png';
        $link = '<a rel="nofollow" href="http://www.technorati.com/faves?add=' . $post_link . '">';
        $out .= $sep . $link . '<img title="Добавить в Technorati" alt="technorati.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['digg']) {
        $img_src = 'digg.png';
        $link = '<a rel="nofollow" href="http://digg.com/submit?url=' . $post_link . '">';
        $out .= $sep . $link . '<img title="Добавить в Digg" alt="digg.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['friendfeed']) {
        $img_src = 'friendfeed.png';
        $link = '<a rel="nofollow" href="http://www.friendfeed.com/share?title=' . $post_link . '">';
        $out .= $sep . $link . '<img title="Добавить в FriendFeed" alt="friendfeed.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['pikabu']) {
        $img_src = 'pikabu.png';
        $link = '<a rel="nofollow" href="http://pikabu.ru/add_story.php?story_url=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Добавить в Pikabu" alt="pikabu.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['blogger']) {
        $img_src = 'blogger.png';
        $link = '<a rel="nofollow" href="http://www.blogger.com/blog_this.pyra?t&amp;u=' . $post_link . '&amp;n=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Опубликовать в Blogger.com" alt="blogger.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['liveinternet']) {
        $img_src = 'liveinternet.png';
        $link = '<a rel="nofollow" href="http://www.liveinternet.ru/journal_post.php?action=n_add&amp;cnurl=' . $post_link . '&amp;cntitle=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Опубликовать в LiveInternet" alt="liveinternet.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['livejournal']) {
        $img_src = 'livejournal.png';
        $link = '<a rel="nofollow" href="http://www.livejournal.com/update.bml?event=' . $post_link . '&amp;subject=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Опубликовать в LiveJournal" alt="livejournal.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['memori']) {
        $img_src = 'memori.png';
        $link = '<a rel="nofollow" href="http://memori.ru/link/">';
        $out .= $sep . $link . '<img title="Сохранить закладку в Memori.ru" alt="memori.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['google-bookmarks']) {
        $img_src = 'google-bookmarks.png';
        $link = '<a rel="nofollow" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Сохранить закладку в Google" alt="google.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['bobrdobr']) {
        $img_src = 'bobrdobr.png';
        $link = '<a rel="nofollow" href="http://bobrdobr.ru/addext.html?url=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Забобрить" alt="bobrdobr.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['mister-wong']) {
        $img_src = 'mister-wong.png';
        $link = '<a rel="nofollow" href="http://www.mister-wong.ru/index.php?action=addurl&amp;bm_url=' . $post_link . '&amp;bm_description=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Сохранить закладку в Мистер Вонг" alt="mister-wong.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['yahoo-bookmarks']) {
        $img_src = 'yahoo-bookmarks.png';
        $link = '<a rel="nofollow" href="http://bookmarks.yahoo.com/toolbar/savebm?u=' . $post_link . '&amp;t=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Добавить в Yahoo! Закладки" alt="yahoo.com" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['yandex']) {
        $img_src = 'yandex.png';
        $link = '<a rel="nofollow" href="http://zakladki.yandex.ru/newlink.xml?url=' . $post_link . '&amp;name=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Добавить в Яндекс.Закладки" alt="yandex.ru" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['delicious']) {
        $img_src = 'delicious.png';
        $link = '<a rel="nofollow" href="http://del.icio.us/post?url=' . $post_link . '&amp;title=' . $post_title . '">';
        $out .= $sep . $link . '<img title="Сохранить закладку в Delicious" alt="del.icio.us" src="' . $path . $img_src . '"' . $width_height . '></a>';
    }
    if ($options['gplusone']) {
        // гугл +1 gplusone
        if ($size == 16) {
            $sg = 'small';
        } else {
            $sg = 'standard';
        }
        $out .= $sep . '
		<script src="https://apis.google.com/js/plusone.js"></script>
		<div class="g-plusone" data-size="' . $sg . '" data-count="true"></div>
		<script> gapi.plusone.render("g-plusone", {"size": "' . $sg . '", "count": "true"}); </script>
		';
    }
    /*$img_src = 'linkstore.gif';
    	$link = '<a rel="nofollow" href="http://www.linkstore.ru/servlet/LinkStore?a=add&amp;url=' . $post_link . '&amp;title=' . $post_title .  '">';
    	$out .= $sep . $link . '<img title="linkstore.ru" alt="linkstore.ru" src="' . $path . $img_src  . '"' . $width_height . '></a>';
    	
    	$img_src = 'news2-ru.gif';
    	$link = '<a rel="nofollow" href="http://news2.ru/add_story.php?url=' . $post_link . '">';
    	$out .= $sep . $link . '<img title="news2.ru" alt="news2.ru" src="' . $path . $img_src  . '"' . $width_height . '></a>';
    
    	$img_src = 'rumark.gif';
    	$link = '<a rel="nofollow" href="http://rumarkz.ru/bookmarks/?action=add&amp;popup=1&amp;address=' . $post_link . '&amp;title=' . $post_title .  '">';
    	$out .= $sep . $link . '<img title="rumarkz.ru" alt="rumarkz.ru" src="' . $path . $img_src  . '"' . $width_height . '></a>';
    	
    	$img_src = 'moemesto.gif';
    	$link = '<a rel="nofollow" href="http://moemesto.ru/post.php?url=' . $post_link . '&amp;title=' . $post_title .  '">';
    	$out .= $sep . $link . '<img title="moemesto.ru" alt="moemesto.ru" src="' . $path . $img_src  . '"' . $width_height . '></a>';*/
    if ($out) {
        echo NR . '<div class="addzakl">' . $options['text-do'] . $out . $options['text-posle'] . '</div>' . NR;
    }
    return $args;
}
Пример #16
0
function mso_create_list($a = array(), $options = array(), $child = false)
{
    if (!$a) {
        return '';
    }
    if (!isset($options['class_ul'])) {
        $options['class_ul'] = '';
    }
    // класс UL
    if (!isset($options['class_ul_style'])) {
        $options['class_ul_style'] = '';
    }
    // свой стиль для UL
    if (!isset($options['class_child'])) {
        $options['class_child'] = 'child';
    }
    // класс для ребенка
    if (!isset($options['class_child_style'])) {
        $options['class_child_style'] = '';
    }
    // свой стиль для ребенка
    if (!isset($options['class_current'])) {
        $options['class_current'] = 'current-page';
    }
    // класс li текущей страницы
    if (!isset($options['class_current_style'])) {
        $options['class_current_style'] = '';
    }
    // стиль li текущей страницы
    if (!isset($options['class_li'])) {
        $options['class_li'] = '';
    }
    // класс LI
    if (!isset($options['class_li_style'])) {
        $options['class_li_style'] = '';
    }
    // стиль LI
    if (!isset($options['format'])) {
        $options['format'] = '[LINK][TITLE][/LINK]';
    }
    // формат ссылки
    if (!isset($options['format_current'])) {
        $options['format_current'] = '<span>[TITLE]</span>';
    }
    // формат для текущей
    if (!isset($options['title'])) {
        $options['title'] = 'page_title';
    }
    // имя ключа для титула
    if (!isset($options['link'])) {
        $options['link'] = 'page_slug';
    }
    // имя ключа для слага
    if (!isset($options['descr'])) {
        $options['descr'] = 'category_desc';
    }
    // имя ключа для описания
    if (!isset($options['id'])) {
        $options['id'] = 'page_id';
    }
    // имя ключа для id
    if (!isset($options['slug'])) {
        $options['slug'] = 'page_slug';
    }
    // имя ключа для slug
    if (!isset($options['menu_order'])) {
        $options['menu_order'] = 'page_menu_order';
    }
    // имя ключа для menu_order
    if (!isset($options['id_parent'])) {
        $options['id_parent'] = 'page_id_parent';
    }
    // имя ключа для id_parent
    if (!isset($options['count'])) {
        $options['count'] = 'count';
    }
    // имя ключа для количества элементов
    if (!isset($options['prefix'])) {
        $options['prefix'] = 'page/';
    }
    // префикс для ссылки
    if (!isset($options['current_id'])) {
        $options['current_id'] = true;
    }
    // текущая страница отмечается по page_id - иначе по текущему url
    if (!isset($options['childs'])) {
        $options['childs'] = 'childs';
    }
    // поле для массива детей
    // если true, то главная рабрика выводится без ссылки в <span>
    if (!isset($options['group_header_no_link'])) {
        $options['group_header_no_link'] = false;
    }
    # функция, которая сработает на [FUNCTION]
    # эта функция получает в качестве параметра текущий массив $elem
    if (!isset($options['function'])) {
        $options['function'] = false;
    }
    if (!isset($options['nofollow']) or !$options['nofollow']) {
        $options['nofollow'] = '';
    } else {
        $options['nofollow'] = ' rel="nofollow"';
    }
    $class_child = $class_child_style = $class_ul = $class_ul_style = '';
    $class_current = $class_current_style = $class_li = $class_li_style = '';
    // [LEVEL] - заменяется на level-текущий уровень вложенности
    if ($options['class_child']) {
        $class_child = ' class="' . $options['class_child'] . ' [LEVEL]"';
    }
    static $level = 0;
    $class_child = str_replace('[LEVEL]', 'level' . $level, $class_child);
    if ($options['class_child_style']) {
        $class_child_style = ' style="' . $options['class_child_style'] . '"';
    }
    if ($options['class_ul']) {
        $class_ul = ' class="' . $options['class_ul'] . '"';
    }
    if ($options['class_ul_style']) {
        $class_ul_style = ' style="' . $options['class_ul_style'] . '"';
    }
    if ($options['class_current']) {
        $class_current = ' class="' . $options['class_current'] . '"';
    }
    if ($options['class_current_style']) {
        $class_current_style = ' style="' . $options['class_current_style'] . '"';
    }
    if ($options['class_li']) {
        $class_li = ' class="' . $options['class_li'] . ' group"';
    } else {
        $class_li = ' class="group"';
    }
    if ($options['class_li_style']) {
        $class_li_style = ' style="' . $options['class_li_style'] . '"';
    }
    if ($child) {
        $out = NR . '	<ul' . $class_child . $class_child_style . '>';
    } else {
        $out = NR . '<ul' . $class_ul . $class_ul_style . '>';
    }
    $current_url = getinfo('siteurl') . mso_current_url();
    // текущий урл
    // из текущего адресу нужно убрать пагинацию
    $current_url = str_replace('/next/' . mso_current_paged(), '', $current_url);
    foreach ($a as $elem) {
        $title = $elem[$options['title']];
        $elem_slug = mso_strip($elem[$options['link']]);
        // slug элемента
        $url = getinfo('siteurl') . $options['prefix'] . $elem_slug;
        // если это page, то нужно проверить вхождение этой записи в элемент рубрики
        // если есть, то ставим css-класс curent-page-cat
        $curent_page_cat_class = is_page_cat($elem_slug, false, false) ? ' class="curent-page-cat"' : '';
        $link = '<a' . $options['nofollow'] . ' href="' . $url . '" title="' . htmlspecialchars($title) . '"' . $curent_page_cat_class . '>';
        if (isset($elem[$options['descr']])) {
            $descr = $elem[$options['descr']];
        } else {
            $descr = '';
        }
        if (isset($elem[$options['count']])) {
            $count = $elem[$options['count']];
        } else {
            $count = '';
        }
        if (isset($elem[$options['id']])) {
            $id = $elem[$options['id']];
        } else {
            $id = '';
        }
        if (isset($elem[$options['slug']])) {
            $slug = $elem[$options['slug']];
        } else {
            $slug = '';
        }
        if (isset($elem[$options['menu_order']])) {
            $menu_order = $elem[$options['menu_order']];
        } else {
            $menu_order = '';
        }
        if (isset($elem[$options['id_parent']])) {
            $id_parent = $elem[$options['id_parent']];
        } else {
            $id_parent = '';
        }
        $cur = false;
        if ($options['current_id']) {
            if (isset($elem['current'])) {
                $e = $options['format_current'];
                $cur = true;
            } else {
                $e = $options['format'];
            }
        } else {
            if ($url == $current_url) {
                $e = $options['format_current'];
                $cur = true;
            } else {
                $e = $options['format'];
            }
        }
        $e = str_replace('[LINK]', $link, $e);
        $e = str_replace('[/LINK]', '</a>', $e);
        $e = str_replace('[TITLE]', $title, $e);
        $e = str_replace('[TITLE_HTML]', htmlspecialchars($title), $e);
        $e = str_replace('[DESCR]', $descr, $e);
        $e = str_replace('[DESCR_HTML]', htmlspecialchars($descr), $e);
        $e = str_replace('[ID]', $id, $e);
        $e = str_replace('[SLUG]', $slug, $e);
        $e = str_replace('[SLUG_HTML]', htmlspecialchars($slug), $e);
        $e = str_replace('[MENU_ORDER]', $menu_order, $e);
        $e = str_replace('[ID_PARENT]', $id_parent, $e);
        $e = str_replace('[COUNT]', $count, $e);
        $e = str_replace('[URL]', $url, $e);
        if ($options['function'] and function_exists($options['function'])) {
            $function = $options['function']($elem);
            $e = str_replace('[FUNCTION]', $function, $e);
        } else {
            $e = str_replace('[FUNCTION]', '', $e);
        }
        if (isset($elem[$options['childs']])) {
            if ($cur) {
                $out .= NR . '<li' . $class_current . $class_current_style . '>' . $e;
            } else {
                if ($options['group_header_no_link']) {
                    $out .= NR . '<li' . $class_li . $class_li_style . '><span class="group_header">' . $title . '</span>';
                } else {
                    $out .= NR . '<li' . $class_li . $class_li_style . '>' . $e;
                }
            }
            ++$level;
            $out .= mso_create_list($elem[$options['childs']], $options, true);
            --$level;
            $out .= NR . '</li>';
        } else {
            if ($child) {
                $out .= NR . '	';
            } else {
                $out .= NR;
            }
            // если нет детей, то уберем класс group
            $class_li_1 = str_replace('group', '', $class_li);
            if ($cur) {
                $out .= '<li' . $class_current . $class_current_style . '>' . $e . '</li>';
            } else {
                $out .= '<li' . $class_li_1 . $class_li_style . '>' . $e . '</li>';
            }
        }
    }
    if ($child) {
        $out .= NR . '	</ul>' . NR;
    } else {
        $out .= NR . '</ul>' . NR;
    }
    $out = str_replace('<li class="">', '<li>', $out);
    return $out;
}
Пример #17
0
	<title>Install MaxSite CMS</title>
	<meta name="generator" content="MaxSite CMS">
	<link rel="stylesheet" href="<?php 
echo $MSO->data['url_css'];
?>
" type="text/css" media="screen">
</head>
<body>
<div id="container">



<?php 
if ($step == 1) {
    echo '<h1>' . t('Добро пожаловать в программу установки <a href="http://max-3000.com/">MaxSite CMS</a>', 'install') . '</h1>';
    if (mso_current_url() == 'install/1' or mso_current_url() == '') {
        echo '<p>' . t('На первом шаге программа проверит верно ли у вас настроены ЧПУ («человекопонятный урл» - веб-адреса, удобные для восприятия человеком).', 'install') . '</p>';
        echo '<p>' . t('При отстутствии ошибок вам будет предложено указать начальные данные.', 'install') . '</p>';
        echo '<p><a href="' . getinfo('site_url') . 'install/2">' . t('Перейти к установке', 'install') . '</a>';
        echo ' | <a target="_blank" href="' . getinfo('site_url') . t('install-ru.txt', 'install') . '">' . t('Инструкция по установке', 'install') . '</a></p>';
    } else {
        echo '<p class="error">' . t('Ошибка! Неверно настроены ЧПУ!', 'install') . '</p>';
        echo '<p>' . t('Данная ошибка означает, что у вас неверно настроен файл <strong>.htaccess</strong>. Прочтите', 'install') . '<a href="' . getinfo('site_url') . t('install-ru.txt', 'install') . '">' . t('инструкцию', 'install') . '</a>' . t('по установке.', 'install') . '</p>';
        echo '<p>' . t('После изменений вы можете', 'install') . ' <a href="' . getinfo('site_url') . 'install/2">' . t('попробовать снова', 'install') . '</a>.</p>';
        echo '<hr><p>' . t('Техническая информация о вашем сервере.', 'install') . '</p>';
        echo '<ul>';
        echo '<li><strong>SERVER_SOFTWARE:</strong> ' . $_SERVER['SERVER_SOFTWARE'] . '</li>';
        echo '<li><strong>REQUEST_METHOD:</strong> ' . $_SERVER['REQUEST_METHOD'] . '</li>';
        echo '</ul>';
    }
}
Пример #18
0
function tweetmeme_com_content($text = '')
{
    global $page;
    if (!is_type('page') and !is_type('home')) {
        return $text;
    }
    // если запись не опубликована, не отображаем блок
    if (is_type('page') and isset($page['page_status']) and $page['page_status'] != 'publish') {
        return $text;
    }
    $options = mso_get_option('plugin_tweetmeme_com', 'plugins', array());
    // получаем опции
    // отображать только на одиночной странице
    if (!isset($options['show_only_page'])) {
        $options['show_only_page'] = 0;
    }
    if ($options['show_only_page'] and !is_type('page')) {
        return $text;
    }
    if (is_type('page') and isset($options['page_type']) and $options['page_type']) {
        $p_type_name = mso_explode($options['page_type'], false);
        // нет у указанных типах страниц
        if (!in_array($page['page_type_name'], $p_type_name)) {
            return $text;
        }
    }
    // стиль выравнивания
    if (!isset($options['style'])) {
        $options['style'] = '';
    }
    if (!isset($options['align'])) {
        $options['align'] = 'right';
    }
    if ($options['style']) {
        $style = ' style="' . $options['style'] . '"';
    } else {
        if ($options['align'] == 'left') {
            $style = ' style="float: left; margin-right: 10px;"';
        } elseif ($options['align'] == 'right') {
            $style = ' style="float: right; margin-left: 10px; width: "';
        } else {
            $style = '';
        }
    }
    if (!isset($options['twitter_orig'])) {
        $options['twitter_orig'] = false;
    }
    // если использовать вывод с tweetmeme.com
    if (!$options['twitter_orig']) {
        if (!isset($options['tweetmeme_style'])) {
            $options['tweetmeme_style'] = 'none';
        }
        if (is_type('home')) {
            $js1 = 'tweetmeme_url = \'' . getinfo('site_url') . 'page/' . $page['page_slug'] . '\';';
        } else {
            $js1 = 'tweetmeme_url = \'' . mso_current_url(true) . '\';';
        }
        if ($options['tweetmeme_style'] == 'compact') {
            $js2 = 'tweetmeme_style = \'compact\';';
        } else {
            $js2 = '';
        }
        if ($js1 or $js2) {
            $js = '<script>' . $js1 . $js2 . '</script>';
        } else {
            $js = '';
        }
        // $text = '<span style="display: none"><![CDATA[<noindex>]]></span><div class="tweetmeme_com"' . $style . '>' . $js . '<script src="' . getinfo('plugins_url'). 'tweetmeme_com/button.js"></script></div><span style="display: none"><![CDATA[</noindex>]]></span>' . $text;
        $text = '<div class="tweetmeme_com"' . $style . '>' . $js . '<script src="http://tweetmeme.com/i/scripts/button.js"></script></div>' . $text;
    } else {
        // блок выводится с оригинального twitter.com
        if (is_type('home')) {
            $url = getinfo('site_url') . 'page/' . $page['page_slug'];
        } else {
            $url = mso_current_url(true);
        }
        if (!isset($options['twitter_data-count'])) {
            $options['twitter_data-count'] = 'vertical';
        }
        $options['twitter_data-count'] = ' data-count="' . $options['twitter_data-count'] . '" ';
        if (!isset($options['twitter_data-via'])) {
            $options['twitter_data-via'] = '';
        }
        if ($options['twitter_data-via']) {
            $options['twitter_data-via'] = ' data-via="' . $options['twitter_data-via'] . '" ';
        }
        $text = '<div class="tweetmeme_com"' . $style . '>' . '<a rel="nofollow" href="http://twitter.com/share" class="twitter-share-button" data-url="' . $url . '"' . $options['twitter_data-count'] . ' data-text="' . $page['page_title'] . '" ' . $options['twitter_data-via'] . '>Tweet</a>
		<script src="http://platform.twitter.com/widgets.js"></script>' . '</div>' . $text;
    }
    return $text;
}
Пример #19
0
/**
*  значение указаного сегмента (относительно главной страницы)
*  
*  @param $segment номер сегмента
*  
*  @return string
*  
*  Пример: http://сайт/news/2014/10/22
*  mso_segment(1) -> news
*  mso_segment(2) -> 2014
*  mso_segment(3) -> 10
*  mso_segment(4) -> 22
*/
function mso_segment($segment)
{
    $url = mso_current_url(true, false, true);
    // есть ли сегмент?
    if (isset($url[$segment - 1])) {
        $s = urldecode($url[$segment - 1]);
    } else {
        $s = false;
    }
    // нет сегмента
    return $s;
}
Пример #20
0
function mso_cat_ul($li_format = '%NAME%', $show_empty = true, $checked_id = array(), $selected_id = array(), $ul_class = 'category', $type_page = 'blog', $type = 'page', $order = 'category_menu_order', $asc = 'asc', $custom_array = false, $include = array(), $exclude = array())
{
    // спасибо за помощь http://tedbeer.net/wp/
    // $include = array('3');
    // $exclude = array('3');
    // возможно, что этот список уже сформирован, поэтому посмотрим в кэше
    $cache_key = mso_md5('mso_cat_ul' . $li_format . $show_empty . implode(' ', $checked_id) . implode(' ', $selected_id) . $ul_class . $type_page . $type . $order . $asc . implode(' ', $include) . implode(' ', $exclude));
    $k = mso_get_cache($cache_key);
    if ($k) {
        // находим текущий url (код повтояет внизу)
        $current_url = getinfo('siteurl') . mso_current_url();
        // текущий урл
        $out = str_replace('<a href="' . $current_url . '">', '<a href="' . $current_url . '" class="current_url">', $k);
        $pattern = '|<li class="(.*?)">(.*?)(<a href="' . $current_url . '")|ui';
        $out = preg_replace($pattern, '<li class="$1 current_url">$2$3', $out);
        return $out;
    }
    # получим все рубрики в виде одномерного массива
    if ($custom_array) {
        $all = $custom_array;
    } else {
        $all = mso_cat_array_single('page', $order, $asc, $type_page);
    }
    $top = array();
    foreach ($all as $item) {
        $parentId = $item['category_id_parent'];
        $id = $item['category_id'];
        if ($parentId && isset($all[$parentId])) {
            if (!isset($all[$parentId]['children'])) {
                $all[$parentId]['children'] = array($id);
            } else {
                $all[$parentId]['children'][] = $id;
            }
        } else {
            $top[] = $id;
        }
    }
    // непосредственно формирование списка
    $out = _mso_cat_ul_glue($top, $all, $li_format, $checked_id, $selected_id, $show_empty, $include, $exclude);
    # $out = str_replace("\n{*}</li>", "</li>", $out);
    if ($ul_class) {
        $out = '<ul class="' . $ul_class . '">' . "\n" . $out . "\n" . '</ul>';
    } else {
        $out = '<ul>' . "\n" . $out . "\n" . '</ul>';
    }
    mso_add_cache($cache_key, $out);
    // сразу в кэш добавим
    // отметим текущую рубрику. Поскольку у нас к кэше должен быть весь список и не делать кэш для каждого url
    // то мы просто перед отдачей заменяем текущий url на url с li.current_url
    $current_url = getinfo('siteurl') . mso_current_url();
    // текущий урл
    $out = str_replace('<a href="' . $current_url . '">', '<a href="' . $current_url . '" class="current_url">', $out);
    $pattern = '|<li class="(.*?)">(.*?)(<a href="' . $current_url . '")|ui';
    $out = preg_replace($pattern, '<li class="$1 current_url">$2$3', $out);
    return $out;
}
Пример #21
0
function range_url_init($arg = array())
{
    global $MSO;
    $options = mso_get_option('plugin_range_url', 'plugins', array());
    // главное зеркало сайта
    if (isset($options['siteurl_enable']) and $options['siteurl_enable'] and isset($options['siteurl']) and $options['siteurl']) {
        if ($MSO->config['site_url'] != $options['siteurl']) {
            mso_redirect($options['siteurl'] . mso_current_url(), true, 301);
        }
    }
    $current_url = mso_current_url();
    // текущий адрес
    if ($current_url === '') {
        return $arg;
    }
    // главная
    // отдельно правило для главной
    // если это home, но без next, то 301-редиректим на главную
    if (mso_segment(1) == 'home' and mso_segment(2) != 'next') {
        mso_redirect('', false, 301);
    }
    if (!isset($options['templates'])) {
        $options['templates'] = '';
    }
    $templates = explode("\n", trim($options['templates']));
    // разобъем по строкам
    if (!isset($options['page_404_redirect'])) {
        $options['page_404_redirect'] = 0;
    }
    if (!isset($options['page_404_header'])) {
        $options['page_404_header'] = 1;
    }
    if (!isset($options['default-templates'])) {
        $options['default-templates'] = true;
    }
    if ($options['default-templates']) {
        // в шаблоны добавим дефолтные адреса
        array_push($templates, '(page_404)', '(contact)', '(logout)', '(login)', '(password-recovery)', '(loginform)', '(loginform)(*)', '(require-maxsite)', '(require-maxsite)(*)', '(ajax)', '(ajax)(*)', '(remote)', '(sitemap)', '(sitemap)(next)(*)', '(sitemap)(cat)', '(sitemap)(cat)(next)(*)', '(home)(next)(*)', '(category)(*)', '(category)(*)(next)(*)', '(page)(*)', '(page)(*)(next)(*)', '(tag)(*)', '(tag)(*)(next)(*)', '(archive)', '(archive)(*)', '(archive)(*)(next)(*)', '(archive)(*)(*)', '(archive)(*)(*)(next)(*)', '(archive)(*)(*)(*)', '(archive)(*)(*)(*)(next)(*)', '(author)(*)', '(author)(*)(next)(*)', '(users)', '(users)(*)', '(users)(*)(edit)', '(users)(*)(lost)', '(search)(*)', '(search)(*)(next)(*)', '(comments)', '(comments)(*)', '(comments)(*)(next)(*)', '(dc)(*)', '(guestbook)', '(guestbook)(next)(*)', '(gallery)', '(gallery)(*)');
    }
    $templates = mso_hook('range_url', $templates);
    // можно добавить свои шаблоны url
    if (!isset($options['min-count-segment'])) {
        $options['min-count-segment'] = 1;
    }
    // минимальное количество сегментов
    $options['min-count-segment'] = (int) $options['min-count-segment'];
    if (count(explode('/', $current_url)) <= $options['min-count-segment']) {
        return $arg;
    }
    // адрес имеет менее N сегментов
    $allow = false;
    // результат
    foreach ($templates as $template) {
        $template = trim($template);
        if (!$template) {
            continue;
        }
        $reg = str_replace('(*)', '(.[^/]*)', $template);
        $reg = '~' . str_replace(')(', '){1}/(', $reg) . '\\z~siu';
        //pr($current_url);
        //pr($reg);
        if (preg_match($reg, $current_url)) {
            $allow = true;
            break;
        }
    }
    // pr($allow);
    if (!$allow) {
        if ($options['page_404_header']) {
            @header('HTTP/1.0 404 Not Found');
        }
        if ($options['page_404_redirect']) {
            mso_redirect('page_404');
        } else {
            $MSO->data['type'] = 'page_404';
        }
    }
    return $arg;
}
Пример #22
0
function mso_get_new_comment($args = array())
{
    global $MSO;
    $args = mso_hook('mso_get_new_comment_args', $args);
    if ($post = mso_check_post(array('comments_session', 'comments_submit', 'comments_page_id', 'comments_content'))) {
        // mso_checkreferer(); // если нужно проверять на реферер
        $CI =& get_instance();
        // заголовок страницы
        if (!isset($args['page_title'])) {
            $args['page_title'] = '';
        }
        // стили
        if (!isset($args['css_ok'])) {
            $args['css_ok'] = 'comment-ok';
        }
        if (!isset($args['css_error'])) {
            $args['css_error'] = 'comment-error';
        }
        // разрешенные тэги
        if (!isset($args['tags'])) {
            $args['tags'] = '<p><blockquote><br><span><strong><strong><em><i><b><u><s><pre><code>';
        }
        // обрабатывать текст на xss-атаку
        if (!isset($args['xss_clean'])) {
            $args['xss_clean'] = true;
        }
        // если найдена xss-атака, то не публиковать комментарий
        if (!isset($args['xss_clean_die'])) {
            $args['xss_clean_die'] = false;
        }
        // запрещенные слова как имя автора
        if (!isset($args['noword'])) {
            $args['noword'] = array('.com', '.ru', '.net', '.org', '.info', '.ua', '.su', '.name', '/', 'www.', 'http', ':', '-', '"', '«', '»', '%', '<', '>', '&', '*', '+', '\'');
        }
        mso_hook('add_new_comment');
        if (!mso_checksession($post['comments_session'])) {
            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка сессии! Обновите страницу') . '</div>';
        }
        if (!$post['comments_page_id']) {
            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка!') . '</div>';
        }
        $comments_page_id = $post['comments_page_id'];
        $id = (int) $comments_page_id;
        if ((string) $comments_page_id != (string) $id) {
            $id = false;
        }
        // $comments_page_id не число
        if (!$id) {
            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка!') . '</div>';
        }
        // капчу проверим
        // если этот хук возвращает false, значит капча неверная
        if (!mso_hook('comments_new_captcha', true)) {
            // если определен хук на неверную капчу, отдаем его
            if (mso_hook_present('comments_new_captcha_error')) {
                return mso_hook('comments_new_captcha_error');
            } else {
                return '<div class="' . $args['css_error'] . '">' . tf('Ошибка! Неверно введены нижние символы!') . '</div>';
            }
        }
        // вычищаем от запрещенных тэгов
        if ($args['tags']) {
            $t = $post['comments_content'];
            $t = strip_tags($t, $args['tags']);
            // оставим только разрешенные тэги
            $post['comments_content'] = $t;
            // сохраним как текст комментария
        }
        // если указано рубить коммент при обнаруженной xss-атаке
        if ($args['xss_clean_die'] and mso_xss_clean($post['comments_content'], true, false) === true) {
            return '<div class="' . $args['css_error'] . '">' . tf('Обнаружена XSS-атака!') . '</div>';
        }
        if (!trim($post['comments_content'])) {
            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка, нет текста!') . '</div>';
        }
        // возможно есть текст, но только из одних html - не пускаем
        if (!trim(strip_tags(trim($post['comments_content'])))) {
            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка, нет полезного текста!') . '</div>';
        }
        // вычищаем текст от xss
        if ($args['xss_clean']) {
            $post['comments_content'] = mso_xss_clean($post['comments_content']);
            // проставим pre исправление ошибки CodeIgniter
            $post['comments_content'] = str_replace('&lt;/pre>', '</pre>', $post['comments_content']);
        }
        $comments_author_ip = $_SERVER['REMOTE_ADDR'];
        $comments_date = date('Y-m-d H:i:s');
        $comments_content = mso_hook('new_comments_content', $post['comments_content']);
        // есть дли родитель у комментария
        $comments_parent_id = isset($post['comments_parent_id']) ? $post['comments_parent_id'] : '0';
        // провека на спам - проверим через хук new_comments_check_spam
        $comments_check_spam = mso_hook('new_comments_check_spam', array('comments_content' => $comments_content, 'comments_date' => $comments_date, 'comments_author_ip' => $comments_author_ip, 'comments_page_id' => $comments_page_id, 'comments_server' => $_SERVER, 'comments_parent_id' => $comments_parent_id, 'comments_author' => isset($post['comments_author']) ? $post['comments_author'] : false, 'comments_email' => isset($post['comments_email']) ? $post['comments_email'] : false, 'comusers_email' => isset($post['comusers_email']) ? $post['comusers_email'] : false, 'comments_user_id' => isset($post['comments_user_id']) ? $post['comments_user_id'] : false, 'comments_comusers_nik' => isset($post['comments_comusers_nik']) ? $post['comments_comusers_nik'] : false, 'comments_comusers_url' => isset($post['comments_comusers_url']) ? $post['comments_comusers_url'] : false), false);
        // если есть спам, то возвращается что-то отличное от comments_content
        // если спама нет, то должно вернуться false
        // если есть подозрения, то возвращается массив с moderation (comments_approved)
        // если есть параметр check_spam=true, значит определен спам и он вообще не пускается
        // сообщение для вывода в парметре 'message'
        // разрешение антиспама moderation
        // -1 - не определено, 0 - можно разрешить, 1 - отдать на модерацию
        $moderation = -1;
        if ($comments_check_spam) {
            if (isset($comments_check_spam['check_spam']) and $comments_check_spam['check_spam'] == true) {
                if (isset($comments_check_spam['message']) and $comments_check_spam['message']) {
                    return '<div class="' . $args['css_error'] . '">' . $comments_check_spam['message'] . '</div>';
                } else {
                    return '<div class="' . $args['css_error'] . '">' . tf('Ваш комментарий определен как спам и удален.') . '</div>';
                }
            } else {
                // спам не определен, но возможно стоит moderation - принудительная модерация
                if (isset($comments_check_spam['moderation'])) {
                    $moderation = $comments_check_spam['moderation'];
                }
            }
        }
        // проверим есть ли уже такой комментарий
        // проверка по ip и тексту
        $CI->db->select('comments_id');
        $CI->db->where(array('comments_page_id' => $comments_page_id, 'comments_author_ip' => $comments_author_ip, 'comments_content' => $comments_content));
        $query = $CI->db->get('comments');
        if ($query->num_rows()) {
            return '<div class="' . $args['css_error'] . '">' . tf('Похоже, вы уже отправили этот комментарий...') . '</div>';
        }
        if (is_login()) {
            $comments_users_id = $MSO->data['session']['users_id'];
            $ins_data = array('comments_users_id' => $comments_users_id, 'comments_page_id' => $comments_page_id, 'comments_author_ip' => $comments_author_ip, 'comments_date' => $comments_date, 'comments_content' => $comments_content, 'comments_parent_id' => $comments_parent_id, 'comments_approved' => 1);
            $res = $CI->db->insert('comments', $ins_data) ? '1' : '0';
            if ($res) {
                $id_comment_new = $CI->db->insert_id();
                mso_email_message_new_comment($id_comment_new, $ins_data, $args['page_title']);
                mso_flush_cache();
                $CI->db->cache_delete_all();
                mso_hook('new_comment');
                mso_redirect(mso_current_url() . '#comment-' . $id_comment_new);
            } else {
                return '<div class="' . $args['css_error'] . '">' . tf('Ошибка добавления комментария') . '</div>';
            }
        } else {
            if (isset($post['comments_reg'])) {
                if ($post['comments_reg'] == 'reg') {
                    // проверим есть ли разршение на комментарии от комюзеров
                    // для случаев подделки post-запроса
                    if (!mso_get_option('allow_comment_comusers', 'general', '1')) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Error allow_comment_comusers') . '</div>';
                    }
                    if (!isset($post['comments_email']) or !$post['comments_email']) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Нужно указать Email') . '</div>';
                    }
                    if (!isset($post['comments_password']) or !$post['comments_password']) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Нужно указать пароль') . '</div>';
                    }
                    $comments_email = mso_strip($post['comments_email']);
                    $comments_password = mso_strip($post['comments_password']);
                    if (!mso_valid_email($comments_email)) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Ошибочный Email') . '</div>';
                    }
                    // проверим время последнего комментария чтобы не очень часто
                    if (!mso_last_activity_comment()) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Слишком частые комментарии. Попробуйте позже.') . '</div>';
                    }
                    // вначале нужно зарегистрировать comюзера - получить его id и только после этого добавить сам коммент
                    // но вначале есть смысл проверить есть ли такой ком-пользователь
                    $comusers_id = false;
                    $CI->db->select('comusers_id, comusers_password');
                    $CI->db->where('comusers_email', $comments_email);
                    $query = $CI->db->get('comusers');
                    if ($query->num_rows()) {
                        $row = $query->row_array(1);
                        // пароль не нужно шифровать mso_md5
                        if (isset($post['comments_password_md']) and $post['comments_password_md']) {
                            if ($row['comusers_password'] != $comments_password) {
                                // пароль неверный
                                return '<div class="' . $args['css_error'] . '">' . tf('Неверный пароль') . '</div>';
                            }
                        } else {
                            if ($row['comusers_password'] != mso_md5($comments_password)) {
                                // пароль неверный
                                return '<div class="' . $args['css_error'] . '">' . tf('Неверный пароль') . '</div>';
                            }
                        }
                        $comusers_id = $row['comusers_id'];
                        // получаем номер комюзера
                    } else {
                        // такого комюзера нет
                        $ins_data = array('comusers_email' => $comments_email, 'comusers_password' => mso_md5($comments_password));
                        // генерируем случайный ключ активации
                        $ins_data['comusers_activate_key'] = mso_md5(rand());
                        $ins_data['comusers_date_registr'] = date('Y-m-d H:i:s');
                        $ins_data['comusers_last_visit'] = date('Y-m-d H:i:s');
                        $ins_data['comusers_ip_register'] = $_SERVER['REMOTE_ADDR'];
                        $ins_data['comusers_notify'] = '1';
                        // сразу включаем подписку на уведомления
                        // если сразу отправлен адрес ссайта
                        if (isset($post['comments_comusers_url']) and $post['comments_comusers_url']) {
                            $comusers_url = htmlspecialchars(mso_xss_clean(strip_tags($post['comments_comusers_url'])));
                            if (strpos($comusers_url, 'http://') === false) {
                                $comusers_url = 'http://' . $comusers_url;
                            }
                            if ($comusers_url) {
                                $ins_data['comusers_url'] = $comusers_url;
                            }
                        }
                        // если сразу отправлен ник
                        if (isset($post['comments_comusers_nik']) and $post['comments_comusers_nik']) {
                            $ins_data['comusers_nik'] = htmlspecialchars(mso_xss_clean(strip_tags($post['comments_comusers_nik'])));
                        }
                        // Автоматическая активация новых комюзеров
                        // если активация стоит автоматом, то сразу её и прописываем
                        if (mso_get_option('comusers_activate_auto', 'general', '0')) {
                            $ins_data['comusers_activate_string'] = $ins_data['comusers_activate_key'];
                        }
                        $res = $CI->db->insert('comusers', $ins_data) ? '1' : '0';
                        if ($res) {
                            // сохраним в сессии время отправления комментария - используется в mso_last_activity_comment
                            $CI->session->set_userdata('last_activity_comment', time());
                            $comusers_id = $CI->db->insert_id();
                            // номер добавленной записи
                            // нужно добавить опцию в мета «новые комментарии, где я участвую» subscribe_my_comments
                            // вначале грохаем если есть такой ключ
                            $CI->db->where('meta_table', 'comusers');
                            $CI->db->where('meta_id_obj', $comusers_id);
                            $CI->db->where('meta_key', 'subscribe_my_comments');
                            $CI->db->delete('meta');
                            // теперь добавляем как новый
                            $ins_data2 = array('meta_table' => 'comusers', 'meta_id_obj' => $comusers_id, 'meta_key' => 'subscribe_my_comments', 'meta_value' => '1');
                            $CI->db->insert('meta', $ins_data2);
                            // почему CodeIgniter не может так?
                            // INSERT INTO table SET column = 1, id=1 ON DUPLICATE KEY UPDATE column = 2
                            // отправляем ему уведомление с кодом активации
                            mso_email_message_new_comuser($comusers_id, $ins_data, mso_get_option('comusers_activate_auto', 'general', '0'));
                            mso_flush_cache();
                            $CI->db->cache_delete_all();
                        } else {
                            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка регистрации') . '</div>';
                        }
                    }
                    if ($comusers_id) {
                        // Модерация комюзеров 1 - модерировать
                        $comments_com_approved = mso_get_option('new_comment_comuser_moderate', 'general', 1);
                        // если включена модерация комюзеров
                        // и включена опция только первого комментария
                        // то получаем кол-во комментариев комюзера
                        if ($comments_com_approved and mso_get_option('new_comment_comuser_moderate_first_comment', 'general', 0)) {
                            $all_comusers = mso_comuser_update_count_comment();
                            // список комюзер => колво комментов
                            // есть такой комюзер и у него более 1 комментария
                            if (isset($all_comusers[$comusers_id]) and $all_comusers[$comusers_id] > 0) {
                                $comments_com_approved = 0;
                            }
                            // разрешаем публикацию
                        }
                        // но у нас в базе хранится значение наоборот - 1 разрешить 0 - запретить
                        $comments_com_approved = !$comments_com_approved;
                        if ($moderation == 1) {
                            $comments_com_approved = 0;
                        }
                        // антиспам определил, что нужно премодерировать
                        if ($comments_com_approved == 1) {
                            $comments_com_approved = mso_hook('new_comments_check_spam_comusers', array('comments_page_id' => $comments_page_id, 'comments_comusers_id' => $comusers_id, 'comments_com_approved' => $comments_com_approved), 1);
                        }
                        // комюзер добавлен или есть
                        // теперь сам коммент
                        $ins_data = array('comments_page_id' => $comments_page_id, 'comments_comusers_id' => $comusers_id, 'comments_author_ip' => $comments_author_ip, 'comments_date' => $comments_date, 'comments_content' => $comments_content, 'comments_approved' => $comments_com_approved, 'comments_parent_id' => $comments_parent_id);
                        // проверим время последнего комментария чтобы не очень часто
                        if (!mso_last_activity_comment()) {
                            return '<div class="' . $args['css_error'] . '">' . tf('Слишком частые комментарии. Попробуйте позже.') . '</div>';
                        }
                        $res = $CI->db->insert('comments', $ins_data) ? '1' : '0';
                        if ($res) {
                            // сохраним в сессии время отправления комментария - используется в mso_last_activity_comment
                            $CI->session->set_userdata('last_activity_comment', time());
                            $id_comment_new = $CI->db->insert_id();
                            // посколько у нас идет редирект, то данные об отправленном комменте
                            // сохраняем в сессии номер комментария
                            if (isset($MSO->data['session'])) {
                                $CI->session->set_userdata(array('comments' => array($id_comment_new)));
                            }
                            mso_email_message_new_comment($id_comment_new, $ins_data, $args['page_title']);
                            mso_flush_cache();
                            $CI->db->cache_delete_all();
                            mso_hook('new_comment');
                            # если комюзер не залогинен, то сразу логиним его
                            $CI->db->select('comusers_id, comusers_password, comusers_email, 
									comusers_nik, comusers_url, comusers_avatar_url, comusers_last_visit');
                            $CI->db->where('comusers_email', $comments_email);
                            $CI->db->where('comusers_password', mso_md5($comments_password));
                            $query = $CI->db->get('comusers');
                            if ($query->num_rows()) {
                                $comuser_info = $query->row_array(1);
                                // вся инфа о комюзере
                                // сразу же обновим поле последнего входа
                                $CI->db->where('comusers_id', $comuser_info['comusers_id']);
                                $CI->db->update('comusers', array('comusers_last_visit' => date('Y-m-d H:i:s')));
                                $expire = time() + 60 * 60 * 24 * 30;
                                // 30 дней = 2592000 секунд
                                $name_cookies = 'maxsite_comuser';
                                $value = serialize($comuser_info);
                                # ставим куку и редиректимся автоматом
                                mso_add_to_cookie($name_cookies, $value, $expire, mso_current_url(true) . '#comment-' . $id_comment_new);
                                exit;
                            }
                            mso_redirect(mso_current_url() . '#comment-' . $id_comment_new);
                        } else {
                            return '<div class="' . $args['css_error'] . '">' . tf('Ошибка добавления комментария') . '</div>';
                        }
                    }
                } elseif ($post['comments_reg'] == 'noreg') {
                    // комментарий от анонима
                    // проверим есть ли разрешение на комментарии от анонимов
                    // для случаев подделки post-запроса
                    if (!mso_get_option('allow_comment_anonim', 'general', '1')) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Error allow_comment_anonim') . '</div>';
                    }
                    // проверим время последнего комментария чтобы не очень часто
                    if (!mso_last_activity_comment()) {
                        return '<div class="' . $args['css_error'] . '">' . tf('Слишком частые комментарии. Попробуйте позже.') . '</div>';
                    }
                    if (isset($post['comments_author'])) {
                        $comments_author_name = mso_strip($post['comments_author']);
                        $comments_author_name = str_replace($args['noword'], '', $comments_author_name);
                        $comments_author_name = htmlspecialchars(trim($comments_author_name));
                        if (!$comments_author_name) {
                            $comments_author_name = tf('Аноним');
                        }
                    } else {
                        $comments_author_name = 'Аноним';
                    }
                    // можно ли публиковать без модерации?
                    $comments_approved = mso_get_option('new_comment_anonim_moderate', 'general', 1);
                    // но у нас в базе хранится значение наоборот - 1 разрешить 0 - запретить
                    $comments_approved = !$comments_approved;
                    if ($moderation == 1) {
                        $comments_approved = 0;
                    }
                    // антиспам определил, что нужно премодерировать
                    $ins_data = array('comments_page_id' => $comments_page_id, 'comments_author_name' => $comments_author_name, 'comments_author_ip' => $comments_author_ip, 'comments_date' => $comments_date, 'comments_content' => $comments_content, 'comments_approved' => $comments_approved, 'comments_parent_id' => $comments_parent_id);
                    $res = $CI->db->insert('comments', $ins_data) ? '1' : '0';
                    if ($res) {
                        $id_comment_new = $CI->db->insert_id();
                        // сохраним в сессии время отправления комментария - используется в mso_last_activity_comment
                        $CI->session->set_userdata('last_activity_comment', time());
                        // посколько у нас идет редирект, то данные об отправленном комменте
                        // сохраняем в сессии номер комментария
                        if (isset($MSO->data['session'])) {
                            $CI->session->set_userdata(array('comments' => array($id_comment_new)));
                        }
                        mso_email_message_new_comment($id_comment_new, $ins_data, $args['page_title']);
                        mso_flush_cache();
                        $CI->db->cache_delete_all();
                        mso_hook('new_comment');
                        mso_redirect(mso_current_url() . '#comment-' . $id_comment_new);
                    } else {
                        return '<div class="' . $args['css_error'] . '">' . tf('Ошибка добавления комментария') . '</div>';
                    }
                }
            }
        }
    }
}
Пример #23
0
function mso_auth($text_login = '******', $OPTIONS = true)
{
    // дефолтные опции
    $def_options = array('username' => 'admin', 'password' => 'admin', 'logout_link' => 'logout', 'login_link' => 'login', 'login_form' => CURRENT_PAGE_DIR . 'auth/auth-login-form.php', 'text_error' => 'Ошибочные данные');
    // если $OPTIONS === true, то загружаем из auth/auth-options.php текущей page
    if ($OPTIONS === true) {
        $OPTIONS = mso_load_options(CURRENT_PAGE_DIR . 'auth/auth-options.php');
    }
    // объединяем с переданными
    $OPTIONS = array_merge($def_options, $OPTIONS);
    // все редиректы на эту же страницу без ?-get
    $url_redirect = mso_current_url(false, true, true);
    // признак отображения формы
    $show_form = false;
    // вход
    if (mso_url_request(false, $OPTIONS['login_link'])) {
        // если есть post, то проверяем данные
        if ($_POST and isset($_POST['flogin_user']) and isset($_POST['flogin_password']) and isset($_POST['flogin_submit'])) {
            // сравниваем логин и пароль
            if (strcmp($_POST['flogin_user'], $OPTIONS['username']) == 0 and strcmp($_POST['flogin_password'], $OPTIONS['password']) == 0) {
                // равно
                if (!isset($_SESSION)) {
                    session_start();
                }
                $_SESSION['username'] = $OPTIONS['username'];
                $_SESSION['password'] = $OPTIONS['password'];
                // все ок!
                header('Location:' . $url_redirect);
            } else {
                // не равно
                echo $OPTIONS['text_error'];
                // ошибочные данные
                $show_form = true;
            }
        } else {
            // нет post
            // если уже есть залогиненость, то редиректим
            if (mso_is_auth($OPTIONS)) {
                header('Location:' . $url_redirect);
            }
            $show_form = true;
            // выводим форму
        }
    } elseif (mso_url_request(false, $OPTIONS['logout_link'])) {
        if (!isset($_SESSION)) {
            session_start();
        }
        if (isset($_SESSION['username'])) {
            unset($_SESSION['username']);
        }
        if (isset($_SESSION['password'])) {
            unset($_SESSION['password']);
        }
        header('Location:' . $url_redirect);
    }
    if ($show_form) {
        if (file_exists($OPTIONS['login_form'])) {
            require $OPTIONS['login_form'];
        } else {
            mso_auth_form();
        }
    }
    // если нет авторизации, то выводим сслыку на ВХОД
    if (strpos($_SERVER['REQUEST_URI'], '?') === FALSE) {
        if (!mso_is_auth($OPTIONS)) {
            echo $text_login;
        }
    }
    if (mso_is_auth($OPTIONS)) {
        return $OPTIONS;
    } else {
        return false;
    }
}
Пример #24
0
    }
} else {
    // тут форма, если не было post
    echo '<div class="guestbook_form"><form action="" method="post">' . mso_form_session('f_session_id');
    echo '<table style="width: 100%;">';
    foreach ($options['fields_arr'] as $key => $val) {
        echo '<tr><td style="vertical-align: top; text-align: right;" class="td1"><strong>' . t($val) . '</strong> </td><td class="td2">';
        if ($key != 'text') {
            echo '<input name="f_fields_guestbook[' . $key . ']" type="text" style="width: 99%;"></td></tr>';
        } else {
            echo '<textarea name="f_fields_guestbook[' . $key . ']" style="width: 99%; height: 100px;"></textarea></td></tr>';
        }
    }
    // капча из плагина капчи
    echo '<tr><td style="vertical-align: top; text-align: right;" class="td1"><strong>' . t('Введите нижние символы') . ' </td>
			<td style="text-align: left;" class="td2"><input type="text" name="f_guestbook_captha" value="" maxlength="4"> <img src="' . getinfo('plugins_url') . 'captcha/img.php?image=' . $session['session_id'] . '&page=' . mso_slug(mso_current_url()) . '&code=' . time() . '" title="' . t('Защита от спама: введите только нижние символы') . '" align="absmiddle"></td></tr>';
    echo '<tr><td class="td1">&nbsp;</td><td style="vertical-align: top; text-align: left;" class="td2"><input type="submit" class="submit" name="f_submit_guestbook" value="' . t('Отправить') . '"></td></tr>';
    echo '</table></form></div>';
}
// тут последние отзывы с пагинацией
// нам нужна все поля таблицы
// вначале определим общее количество записей
$pag = array();
// пагинация
$pag['limit'] = $options['limit'];
// записей на страницу
$pag['type'] = '';
// тип
$CI->db->select('guestbook_id');
$CI->db->from('guestbook');
$CI->db->where('guestbook_approved', '1');
Пример #25
0
function mso_view_ini($all = false)
{
    if (!$all) {
        return '';
    }
    //pr($all);
    $CI =& get_instance();
    $CI->load->library('table');
    $tmpl = array('table_open' => '<table class="page "><colgroup style="width: 25%;">', 'row_alt_start' => '<tr class="alt">', 'cell_alt_start' => '<td class="alt">');
    $CI->table->clear();
    // очистим, если были старые данные
    $CI->table->set_template($tmpl);
    // шаблон таблицы
    // заголовки
    //$CI->table->set_heading(t('Настройка'), t('Значение'));
    $table = '';
    $out = '';
    $nav = '';
    // блок навигации
    // сформируем массив всех опций - ключей
    $k_where = array();
    foreach ($all as $k => $v) {
        if (isset($v['options_key']) and $v['options_key']) {
            $k_where[] = $v['options_key'];
        }
    }
    // делаем одним запросов выборку всех опций по этим ключам
    $CI->db->where_in('options_key', $k_where);
    $query = $CI->db->get('options');
    if ($query->num_rows() > 0) {
        // есть запись
        $all_options = $query->result_array();
    } else {
        $all_options = array();
    }
    //pr($all_options);
    //pr($all);
    foreach ($all as $key => $row) {
        if (isset($row['options_key'])) {
            $options_key = stripslashes(trim($row['options_key']));
        } else {
            continue;
        }
        if (!isset($row['options_type'])) {
            $options_type = 'general';
        } else {
            $options_type = stripslashes(trim($row['options_type']));
        }
        if (!isset($row['type'])) {
            if ($options_key !== 'none') {
                $type = 'textfield';
            } else {
                $type = 'none';
            }
        } else {
            $type = stripslashes(trim($row['type']));
        }
        if (!isset($row['values'])) {
            $value = '';
        } else {
            $values = _mso_ini_check_php(stripslashes(htmlspecialchars(trim($row['values']))));
        }
        if (!isset($row['description'])) {
            $description = '';
        } else {
            $description = _mso_ini_check_php(stripslashes(trim(t($row['description']))));
        }
        if (!isset($row['delimer'])) {
            $delimer = '<br>';
        } else {
            $delimer = stripslashes($row['delimer']);
        }
        if (!isset($row['default'])) {
            $default = '';
        } else {
            $default = _mso_ini_check_php(stripslashes(htmlspecialchars(trim($row['default']))));
        }
        // получаем текущее значение опции из массива $all_options
        $options_present = false;
        $value = t($default);
        // нет значения, поэтому берем дефолт
        foreach ($all_options as $v) {
            if ($v['options_type'] == $options_type and $v['options_key'] == $options_key) {
                $value = htmlspecialchars($v['options_value']);
                $options_present = true;
                // признак, что опция есть в базе
                break;
            }
        }
        $f = NR;
        // тип none не создает поля - фиктивная опция
        if ($options_key != 'none') {
            $name_f = 'f_options[' . $options_key . '_m_s_o_' . $options_type . ']';
        } else {
            $name_f = '';
        }
        if ($type == 'textfield') {
            $value = str_replace('_QUOT_', '&quot;', $value);
            // в этом типе может быть свой type для input
            if (!isset($row['textfield_type'])) {
                $textfield_type = 'text';
            } else {
                $textfield_type = stripslashes($row['textfield_type']);
            }
            $f .= '<input type="' . $textfield_type . '" name="' . $name_f . '" value="' . $value . '">' . NR;
        } elseif ($type == 'color') {
            $f .= mso_load_jquery('jscolor.js', getinfo('common_url') . 'jquery/jscolor/');
            $f .= '<input type="text" name="' . $name_f . '" value="' . $value . '" class="color">' . NR;
        } elseif ($type == 'textarea') {
            $value = str_replace('_NR_', "\n", $value);
            $value = str_replace('_QUOT_', '&quot;', $value);
            if (!isset($row['rows'])) {
                $rr = 7;
            } else {
                $rr = (int) $row['rows'];
            }
            $f .= '<textarea rows="' . $rr . '" name="' . $name_f . '">' . $value . '</textarea>' . NR;
        } elseif ($type == 'checkbox') {
            if ($value) {
                $checked = 'checked="checked"';
            } else {
                $checked = '';
            }
            $f .= '<label><input type="checkbox" name="' . $name_f . '" ' . $checked . '> ' . t($key) . '</label>' . NR;
            $f .= '<input type="hidden" name="f_all_checkbox[' . $options_key . '_m_s_o_' . $options_type . ']">' . NR;
        } elseif ($type == 'multicheckbox') {
            $mr = $value;
            // отмеченные пункты - массив в виде стандартного option
            if ($mr) {
                // служебные замены
                $mr = str_replace('&amp;', '&', $mr);
                $mr = str_replace('&quot;', '"', $mr);
                if (preg_match('|_serialize_|A', $mr)) {
                    $mr = preg_replace('|_serialize_|A', '', $mr, 1);
                    $mr = @unserialize($mr);
                }
                if (!is_array($mr)) {
                    $mr = array($mr);
                }
            } else {
                $mr = array();
            }
            // $mr теперь массив!
            $values = explode('#', $values);
            if ($values) {
                foreach ($values as $val) {
                    $ar = explode('||', $val);
                    if (isset($ar[0])) {
                        $mr1 = trim($ar[0]);
                    }
                    // ключ чекбокса
                    if (isset($ar[1])) {
                        $mr2 = trim($ar[1]);
                    } else {
                        $mr2 = $mr1;
                    }
                    if (in_array($mr1, $mr)) {
                        $checked = 'checked="checked"';
                    } else {
                        $checked = '';
                    }
                    //для каждого чекбокса свой ключ!
                    $mkey = $options_key . '_' . mso_slug($mr1) . '_m_s_o_' . $options_type;
                    $name_f1 = 'f_options[' . $mkey . ']';
                    $f .= '<label><input type="checkbox" name="' . $name_f . '[]" value="' . $mr1 . '" ' . $checked . '> ' . t($mr2) . '</label>' . $delimer . NR;
                }
                $f .= '<input type="hidden" name="f_all_checkbox[' . $options_key . '_m_s_o_' . $options_type . ']">' . NR;
            }
        } elseif ($type == 'radio') {
            $values = explode('#', $values);
            // все значения разделены #
            if ($values) {
                foreach ($values as $val) {
                    $ar = explode('||', $val);
                    if (isset($ar[0])) {
                        $mr1 = trim($ar[0]);
                    }
                    // ключ
                    if (isset($ar[1])) {
                        $mr2 = trim($ar[1]);
                    } else {
                        $mr2 = $mr1;
                    }
                    if ($value == trim($mr1)) {
                        $checked = 'checked="checked"';
                    } else {
                        $checked = '';
                    }
                    // преобразование в html
                    $mr2 = str_replace('_QUOT_', '"', $mr2);
                    $mr2 = str_replace('&lt;', '<', $mr2);
                    $mr2 = str_replace('&gt;', '>', $mr2);
                    $f .= '<label><input type="radio" name="' . $name_f . '" value="' . $mr1 . '" ' . $checked . '> ' . t($mr2) . '</label>' . $delimer . NR;
                }
            }
        } elseif ($type == 'select') {
            $values = explode('#', $values);
            // все значения разделены #
            if ($values) {
                $f .= '<select name="' . $name_f . '">';
                foreach ($values as $val) {
                    // $val может быть с || val - текст
                    $val = trim($val);
                    $val_t = $val;
                    $ar = explode('||', $val);
                    if (isset($ar[0])) {
                        $val = trim($ar[0]);
                    }
                    if (isset($ar[1])) {
                        $val_t = trim($ar[1]);
                    }
                    if ($value == $val) {
                        $checked = 'selected="selected"';
                    } else {
                        $checked = '';
                    }
                    $f .= NR . '<option value="' . $val . '" ' . $checked . '>' . t($val_t) . '</option>';
                }
                $f .= NR . '</select>' . NR;
            }
        }
        if ($description) {
            $f .= '<p><em>' . t($description) . '</em></p>';
        }
        if ($options_key != 'none') {
            if (!$options_present) {
                $key = '<span title="' . $options_key . ' (' . $row['options_type'] . ')" class="mso-alert">* ' . t($key) . '</span>';
            } else {
                $key = '<strong title="' . $options_key . ' (' . $row['options_type'] . ')">' . t($key) . '</strong>';
            }
        } else {
            $key = '';
        }
        // если есть новая секция, то выводим пустую инфо-строчку
        if (isset($row['section'])) {
            if ($CI->table->rows) {
                $table .= $CI->table->generate();
            }
            $CI->table->clear();
            // очистим, если были старые данные
            $tmpl['table_open'] = NR . '<table class="page page-responsive section_' . mso_slug($row['section']) . '"><colgroup style="width: 25%;">';
            $CI->table->set_template($tmpl);
            // шаблон таблицы
            if (isset($row['section_description'])) {
                $CI->table->add_row(array('class' => 'section', 'colspan' => 2, 'data' => '<a id="a-' . mso_slug($row['section']) . '"></a><h2 class="section">' . t($row['section']) . '</h2><p>' . t($row['section_description']) . '</p>'));
            } else {
                $CI->table->add_row(array('class' => 'section', 'colspan' => 2, 'data' => '<a id="a-' . mso_slug($row['section']) . '"></a><div class="section"><h2>' . t($row['section']) . '</h2></div>'));
            }
            $nav .= '<a href="#a-' . mso_slug($row['section']) . '" id="' . mso_slug($row['section']) . '">' . t($row['section']) . '</a>    ';
        }
        if ($key) {
            $CI->table->add_row($key, $f);
        }
    }
    if ($CI->table->rows) {
        $table .= $CI->table->generate();
    }
    // последняя генерация
    $out .= '<form action="' . mso_current_url(true) . '" method="post">' . mso_form_session('f_session_id');
    $out .= '<a id="atop"></a><input type="hidden" value="1" name="f_ini">';
    // доп. поле - индикатор, что это ini-форма
    if ($nav) {
        $out .= '<p class="nav">' . str_replace('    ', '<span class="sep"></span>', trim($nav)) . '</p>';
    }
    $out .= $table;
    // вывод подготовленной таблицы
    $out .= NR . '<a id="abottom"></a><button type="submit" name="f_submit" class="mso-save-ini i-save">' . t('Сохранить') . '</button>';
    $out .= '</form>';
    $out .= mso_load_jquery('jquery.cookie.js') . "\r\n<script>\r\n\t\$(function()\r\n\t{\r\n\t\t\$('table.page').hide();\r\n\r\n\t\tvar NameCookie = 'curSection_" . mso_segment(2) . "',\r\n\t\tcookieIndex = \$.cookie(NameCookie);\r\n\r\n\t\tif (cookieIndex != null && \$('table').is('.section_'+cookieIndex)) // есть кука и есть соответсвующая ей таблица\r\n\t\t{\r\n\t\t\t\$('table.section_'+cookieIndex).show();\r\n\t\t\t\$('#'+cookieIndex).addClass('current');\r\n\t\t}\r\n\t\telse // если нет куки или соответвующей таблицы\r\n\t\t{\r\n\t\t\t\$('table.page:first').show(); // показывем только первую таблицу\r\n\t\t\t\$('p.nav a:first').addClass('current'); // к первому пункту навигации добавляем класс\r\n\t\t}\r\n\r\n\t\t\$('p.nav a').click(function(){\r\n\t\t\tvar id = \$(this).attr('id');\r\n\t\t\t\$('table.page').hide();\r\n\r\n\t\t\t\$(this).addClass('current').siblings().removeClass(); // добавляем класс на кликнутый пункт, а у всех соседних удаляем\r\n\t\t\t\$('table.section_'+id).show();\r\n\t\t\t\$.cookie(NameCookie, id, {expires: 30, path: '/'});\r\n\t\t\treturn false;\r\n\t\t});\r\n\t});\r\n</script>";
    return $out;
}
Пример #26
0
    } else {
        $registration = '';
        $reg_text = t('Вход');
    }
    // возможен вход через соцсеть
    $hook_login_form_auth = mso_hook_present('login_form_auth') ? '<span class="login-form-auth-title">' . tf('Вход через:') . ' </span>' . mso_hook('login_form_auth') : '';
    if ($hook_login_form_auth) {
        $hook_login_form_auth = trim(str_replace('[end]', '     ', $hook_login_form_auth));
        $hook_login_form_auth = '<p class="login-form-auth">' . str_replace('     ', ', ', $hook_login_form_auth) . '</p>';
    } else {
        $hook_login_form_auth = '';
    }
    $out = '
			
	<a href="#" data-dropdown="#dropdown-1" class="dropdown">' . $reg_text . '</a>

	<div id="dropdown-1" class="dropdown-menu has-tip anchor-right">
	<ul><li>
		<form method="post" action="' . $MSO->config['site_url'] . 'login" name="flogin">
			<input type="hidden" value="' . $MSO->config['site_url'] . mso_current_url() . '" name="flogin_redirect">
			<input type="hidden" value="' . $MSO->data['session']['session_id'] . '" name="flogin_session_id">
			
			<p class="user"><input type="text" value="" name="flogin_user" placeholder="' . t('email/логин') . '"></p>
			<p class="password"><input type="password" value="" name="flogin_password" placeholder="' . t('пароль') . '"></p>
			<p class="submit"><button type="submit" name="flogin_submit">Вход</button>' . $registration . '</p>' . $hook_login_form_auth . '
		</form>
	</li></ul>
	</div>';
}
echo $out;
# end file