Beispiel #1
0
function admin_ip_admin_init($args = array())
{
    // проверяем сегменты URL
    // получаем из опций секретный сегмент
    // если это секретный, то сбрасываем ip
    // получаем список разрешенных IP из опций
    // получаем текущий IP юзера
    // если его нет в разрешенных, то die('no');
    global $MSO;
    $options_key = 'plugin_admin_ip';
    $options = mso_get_option($options_key, 'plugins', array());
    if (!isset($options['secret'])) {
        $options['secret'] = '';
    }
    if (!isset($options['ip'])) {
        $options['ip'] = '';
    }
    if ($options['secret'] and mso_segment(3) == $options['secret']) {
        // сброс ip
        // http://localhost/codeigniter/admin/plugin_admin_ip/secret_to_reset - secret_to_reset
        $options['ip'] = '';
        mso_add_option($options_key, $options, 'plugins');
        mso_redirect('admin/plugin_admin_ip');
        // редирект на страницу плагина
    }
    if ($options['ip']) {
        // указаны IP
        $ips = explode("\n", $options['ip']);
        $curr_ip = $MSO->data['session']['ip_address'];
        $ok = false;
        // признак, что доступ разрешен
        foreach ($ips as $ip) {
            if (trim($ip) == $curr_ip) {
                $ok = true;
                break;
            }
        }
        if (!$ok) {
            die('Access denied');
        }
        // рубим
    }
    if (!mso_check_allow('admin_ip_admin_page')) {
        return $args;
        // 'Доступ запрещен';
    }
    $this_plugin_url = 'plugin_admin_ip';
    // url и hook
    # добавляем свой пункт в меню админки
    # первый параметр - группа в меню
    # второй - это действие/адрес в url - http://сайт/admin/demo
    #			можно использовать добавочный, например demo/edit = http://сайт/admin/demo/edit
    # Третий - название ссылки
    mso_admin_menu_add('plugins', $this_plugin_url, 'Admin IP');
    # прописываем для указаного admin_url_ + $this_plugin_url - (он будет в url)
    # связанную функцию именно она будет вызываться, когда
    # будет идти обращение по адресу http://сайт/admin/_null
    mso_admin_url_hook($this_plugin_url, 'admin_ip_admin_page');
    return $args;
}
Beispiel #2
0
            $act = false;
        }
        if ($act) {
            $out = t('Выполнено:') . ' ';
            foreach ($post['f_check_submit'] as $f_name => $val) {
                if ($act == 'activate') {
                    mso_plugin_activate($f_name);
                } elseif ($act == 'deactivate') {
                    mso_plugin_deactivate($f_name);
                } elseif ($act == 'uninstall') {
                    mso_plugin_uninstall($f_name);
                }
                # унинстал
                $out .= ' • ' . $f_name;
            }
            mso_redirect('admin/plugins');
        } else {
            echo '<div class="error">' . t('Ошибка обновления') . '</div>';
        }
    } else {
        echo '<div class="error">' . t('Отметьте необходимые плагины') . '</div>';
    }
}
?>
	<h1><?php 
echo t('Плагины');
?>
</h1>
	<p class="info"><?php 
echo t('Плагины расширяют стандартные возможности сайта. Здесь вы можете включить или отключить плагины. Если вы деинсталируете плагин, то это удаляет его настройки, что позволяет избежать «замусоривания» базы данных.');
?>
Beispiel #3
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;
}
Beispiel #4
0
        echo '<h2 class="bor-solid-b bor-gray400 mar20-b mar20-t i-rss">' . t('Новости MaxSite CMS') . '</h2>';
        foreach ($rss as $item) {
            // title link category description date_timestamp pubdate
            // if (!isset($item['category'])) $item['category'] = '-';
            echo '<h5><a href="' . $item['link'] . '">' . $item['title'] . '</a> - ' . date('d.m.Y', $item['date_timestamp']) . '</h5>';
            echo '<p>' . $item['description'] . '</p>';
            echo '<hr class="dotted mar0-t">';
        }
    }
}
if (mso_check_allow('admin_home')) {
    $show_clear_cache = true;
    if ($post = mso_check_post(array('f_session_id', 'f_submit_clear_cache'))) {
        mso_checkreferer();
        $show_clear_cache = false;
        mso_flush_cache();
        // сбросим кэш
        // echo '<p>' . t('Кэш удален') . '</p><br>';
        mso_redirect('admin/home');
    }
    if ($show_clear_cache) {
        echo '<form method="post">' . mso_form_session('f_session_id');
        if ($show_clear_cache) {
            echo '<p><button type="submit" name="f_submit_clear_cache" class="button i-stack-overflow">' . t('Сбросить кэш системы') . '</button></p>';
        }
        echo '</form>';
    }
}
//if (mso_check_allow('admin_home'))
mso_hook('admin_home');
# end of file
Beispiel #5
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;
}
Beispiel #6
0
     $data['page_date_publish'] = $page_date_publish;
 }
 require_once getinfo('common_dir') . 'functions-edit.php';
 // функции редактирования
 $result = mso_new_page($data);
 // pr($result);
 if (isset($result['result']) and $result['result']) {
     if (isset($result['result'][0])) {
         $url = '<a href="' . mso_get_permalink_page($result['result'][0]) . '" target="_blank">' . t('Посмотреть запись') . '</a> | ' . '<a href="' . $MSO->config['site_admin_url'] . 'page_edit/' . $result['result'][0] . '">' . t('Изменить') . '</a>';
     } else {
         $url = '';
     }
     echo '<div class="update">' . t('Запись добавлена!') . ' ' . $url . '</div>';
     // . $result['description'];
     if ($url and isset($post['f_return'])) {
         mso_redirect($MSO->config['site_admin_url'] . 'page_edit/' . $result['result'][0], true);
     }
     # остальное на дефолт
     $f_content = '';
     $f_header = '';
     $f_tags = '';
     $f_slug = '';
     $f_status = '1';
     $f_page_type = '1';
     $f_cat = array();
     $f_password = '';
     $f_comment_allow = '1';
     $f_ping_allow = '1';
     $f_feed_allow = '1';
     $f_page_parent = '';
     $page_menu_order = '0';
Beispiel #7
0
function forms_content_callback($matches)
{
    $text = $matches[1];
    $text = str_replace("\r", "", $text);
    $text = str_replace('&nbsp;', ' ', $text);
    $text = str_replace("\t", ' ', $text);
    $text = str_replace('<br />', "<br>", $text);
    $text = str_replace('<br>', "\n", $text);
    $text = str_replace("\n\n", "\n", $text);
    $text = str_replace('     ', ' ', $text);
    $text = str_replace('    ', ' ', $text);
    $text = str_replace('   ', ' ', $text);
    $text = str_replace('  ', ' ', $text);
    $text = str_replace("\n ", "\n", $text);
    $text = str_replace("\n\n", "\n", $text);
    $text = trim($text);
    $out = '';
    // убиваем исходный текст формы
    //$r = preg_match_all('!\[email=(.*?)\]|\[redirect=(.*?)\]\[subject=(.*?)\]|\[field\](.*?)\[\/field\]|\[ushka=(.*?)\]!is', $text, $all);
    // на какой email отправляем
    $r = preg_match_all('!\\[email=(.*?)\\]!is', $text, $all);
    if ($r) {
        $email = trim(implode(' ', $all[1]));
    } else {
        $email = mso_get_option('admin_email', 'general', '*****@*****.**');
    }
    // тема письма
    $r = preg_match_all('!\\[subject=(.*?)\\]!is', $text, $all);
    if ($r) {
        $subject = trim(implode(' ', $all[1]));
    } else {
        $subject = tf('Обратная связь');
    }
    // куда редиректить после отправки
    $r = preg_match_all('!\\[redirect=(.*?)\\]!is', $text, $all);
    if ($r) {
        $redirect = trim(implode(' ', $all[1]));
    } else {
        $redirect = '';
    }
    // eirf к форме
    $r = preg_match_all('!\\[ushka=(.*?)\\]!is', $text, $all);
    if ($r) {
        $ushka = trim(implode(' ', $all[1]));
    } else {
        $ushka = '';
    }
    // отправить копию на ваш email
    $r = preg_match_all('!\\[nocopy\\]!is', $text, $all);
    if ($r) {
        $forms_subscribe = false;
    } else {
        $forms_subscribe = true;
    }
    // кнопка Сброс формы
    $r = preg_match_all('!\\[noreset\\]!is', $text, $all);
    if ($r) {
        $reset = false;
    } else {
        $reset = true;
    }
    // pr($all);
    // поля формы
    $r = preg_match_all('!\\[field\\](.*?)\\[\\/field\\]!is', $text, $all);
    $f = array();
    // массив для полей
    if ($r) {
        $fields = $all[1];
        /* 
        pr($fields);
        pr($email);
        pr($redirect);
        pr($subject);
        pr($ushka);
        */
        if ($subject) {
            // поле тема письма делаем в виде обязательнного поля select.
            // формируем массив для формы
            $subject_f['require'] = 1;
            //$subject_f['type'] = 'select';
            $subject_f['type'] = mb_strpos($subject, '#') === false ? 'text' : 'select';
            // если это одиночное поле, но при этом текст сабжа начинается
            // с _ то ставим тип hidden
            if ($subject_f['type'] == 'text' and mb_strpos($subject, '_') === 0) {
                $subject = mb_substr($subject . ' ', 1, -1, 'UTF-8');
                $subject_f['type'] = 'hidden';
            }
            $subject_f['description'] = tf('Тема письма');
            //$subject_f['tip'] = t('Выберите тему письма');
            $subject_f['values'] = $subject;
            $subject_f['value'] = $subject;
            $subject_f['default'] = '';
            // преобразования, чтобы сделать ключ для поля
            $f1['subject'] = $subject_f;
            // у поля тема будет ключ subject
            foreach ($f as $key => $val) {
                $f1[$key] = $val;
            }
            $f = $f1;
        }
        $i = 0;
        foreach ($fields as $val) {
            $val = trim($val);
            if (!$val) {
                continue;
            }
            $val = str_replace(' = ', '=', $val);
            $val = str_replace('= ', '=', $val);
            $val = str_replace(' =', '=', $val);
            $val = explode("\n", $val);
            // разделим на строки
            $ar_val = array();
            foreach ($val as $pole) {
                $pole = preg_replace('!=!', '_VAL_', $pole, 1);
                $ar_val = explode('_VAL_', $pole);
                // строки разделены = type = select
                if (isset($ar_val[0]) and isset($ar_val[1])) {
                    $f[$i][$ar_val[0]] = $ar_val[1];
                }
            }
            $i++;
        }
        if (!$f) {
            return '';
        }
        // нет полей - выходим
        // теперь по-идее у нас есть вся необходимая информация по полям и по форме
        // смотрим есть ли POST. Если есть, то проверяем введенные поля и если они корректные,
        // то выполняем отправку почты, выводим сообщение и редиректимся
        // если POST нет, то выводим обычную форму
        // pr($f);
        if ($_POST) {
            $_POST = mso_clean_post(array('forms_antispam1' => 'integer', 'forms_antispam2' => 'integer', 'forms_antispam' => 'integer', 'forms_name' => 'base', 'forms_email' => 'email', 'forms_session' => 'base'));
        }
        if ($post = mso_check_post(array('forms_session', 'forms_antispam1', 'forms_antispam2', 'forms_antispam', 'forms_name', 'forms_email', 'forms_submit'))) {
            mso_checkreferer();
            $out .= '<div class="forms-post">';
            // верный email?
            if (!($ok = mso_valid_email($post['forms_email']))) {
                $out .= '<div class="message error small">' . tf('Неверный email!') . '</div>';
            }
            // антиспам
            if ($ok) {
                $antispam1s = (int) $post['forms_antispam1'];
                $antispam2s = (int) $post['forms_antispam2'];
                $antispam3s = (int) $post['forms_antispam'];
                if ($antispam1s / 984 + $antispam2s / 765 != $antispam3s) {
                    // неверный код
                    $ok = false;
                    $out .= '<div class="message error small">' . tf('Неверная сумма антиспама') . '</div>';
                }
            }
            if ($ok) {
                foreach ($f as $key => $val) {
                    if ($ok and isset($val['require']) and $val['require'] == 1) {
                        if (!isset($post['forms_fields'][$key]) or !$post['forms_fields'][$key]) {
                            $ok = false;
                            $out .= '<div class="message error small">' . tf('Заполните все необходимые поля!') . '</div>';
                        }
                    }
                    if (!$ok) {
                        break;
                    }
                }
            }
            // всё ок
            if ($ok) {
                //pr($post);
                // pr($f);
                // pr($redirect);
                // pr($email);
                // pr($subject);
                // формируем письмо и отправляем его
                if (!mso_valid_email($email)) {
                    $email = mso_get_option('admin_email', 'general', '*****@*****.**');
                }
                // куда приходят письма
                $message = t('Имя: ') . $post['forms_name'] . "\n";
                $message .= t('Email: ') . $post['forms_email'] . "\n";
                foreach ($post['forms_fields'] as $key => $val) {
                    //pr($key);
                    if ($key === 'subject' and $val) {
                        $subject = $val;
                        //pr($subject);
                        continue;
                    }
                    $message .= $f[$key]['description'] . ': ' . $val . "\n\n";
                }
                if ($_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_REFERER'] and $_SERVER['HTTP_USER_AGENT']) {
                    $message .= "\n" . tf('IP-адрес: ') . $_SERVER['REMOTE_ADDR'] . "\n";
                    $message .= tf('Отправлено со страницы: ') . $_SERVER['HTTP_REFERER'] . "\n";
                    $message .= tf('Браузер: ') . $_SERVER['HTTP_USER_AGENT'] . "\n";
                }
                // pr($message);
                $form_hide = mso_mail($email, $subject, $message, $post['forms_email']);
                if ($forms_subscribe and isset($post['forms_subscribe'])) {
                    mso_mail($post['forms_email'], tf('Вами отправлено сообщение:') . ' ' . $subject, $message);
                }
                $out .= '<div class="message ok small">' . tf('Ваше сообщение отправлено!') . '</div><p>' . str_replace("\n", '<br>', htmlspecialchars($subject . "\n" . $message)) . '</p>';
                if ($redirect) {
                    mso_redirect($redirect, true);
                }
            } else {
                $out .= forms_show_form($f, $ushka, $forms_subscribe, $reset, $subject);
            }
            $out .= '</div>';
            $out .= mso_load_jquery('jquery.scrollto.js');
            $out .= '<script>$(document).ready(function(){$.scrollTo("div.forms-post", 500);})</script>';
        } else {
            $out .= forms_show_form($f, $ushka, $forms_subscribe, $reset, $subject);
        }
    }
    return $out;
}
Beispiel #8
0
function fbauth_init($arg = array())
{
    if (mso_segment(1) == 'maxsite-fbauth') {
        if (!function_exists('curl_init')) {
            die('Не найдено PHP-расширение CURL');
        }
        if (!function_exists('json_decode')) {
            die('Не найдено PHP-расширение JSON');
        }
        $options = mso_get_option('plugin_fbauth', 'plugins', array());
        if (!isset($options['app_id']) or !$options['app_id']) {
            die(t('Не задан app_id'));
        }
        if (!isset($options['app_secret']) or !$options['app_secret']) {
            die(t('Не задан app_secret'));
        }
        $app_id = $options['app_id'];
        $app_secret = $options['app_secret'];
        $my_url = getinfo('site_url') . 'maxsite-fbauth';
        $code = isset($_REQUEST["code"]) ? $_REQUEST["code"] : null;
        if (!isset($code)) {
            $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . '&scope=email,user_website';
            mso_redirect($dialog_url, true);
        }
        $token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
        $access_token = fbauth_request($token_url);
        $graph_url = "https://graph.facebook.com/me?" . $access_token;
        $user0 = fbauth_request($graph_url);
        if (strpos($user0, '400 Bad Request') !== false) {
            die(t('Ошибка авторизации (400 Bad Request)'));
        } else {
            $user = json_decode($user0);
            if (isset($user->email) and mso_valid_email($user->email)) {
                require_once getinfo('common_dir') . 'comments.php';
                mso_comuser_auth(array('email' => $user->email, 'comusers_nik' => $user->name));
                // echo("Hello " . $user->name);
            } else {
                // ошибочный или отстутсвующий email
                die(t('Не удалось авторизоваться с помощью Facebook. Возможно это связано с тем, что в ответ на запрос сервис не возвратил ваш e-mail'));
            }
            die;
        }
    }
    return $arg;
}
Beispiel #9
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() - 31500000;
        $value = '';
        //_pr($url);
        // mso_add_to_cookie('mso_edit_form_comuser', '', $expire);
        //mso_add_to_cookie($name_cookies, $value, $expire, getinfo('siteurl') . mso_current_url()); // в куку для всего сайта
        mso_add_to_cookie($name_cookies, $value, $expire, $url);
        // в куку для всего сайта
    } elseif ($url) {
        mso_redirect($url, true);
    } else {
        mso_redirect(getinfo('site_url'), true);
    }
}
Beispiel #10
0
function mso_comuser_lost($args = array())
{
    global $MSO;
    if (!isset($args['css_ok'])) {
        $args['css_ok'] = 'comment-ok';
    }
    if (!isset($args['css_error'])) {
        $args['css_error'] = 'comment-error';
    }
    // если нет опции password_recovery, значит восстанавливаем с учетом номера комюзера во втором сегмента адреса
    // если опция есть, значит восстанавливаем без учета id комюзера
    if (!isset($args['password_recovery'])) {
        $password_recovery = false;
    } else {
        $password_recovery = true;
    }
    # id комюзера, который в сессии - какой комюзер
    # если комюзер залогинен, то будет $id_session
    # если нет, то залогиненности нет
    if (isset($MSO->data['session']['comuser']) and $MSO->data['session']['comuser']) {
        $id_session = $MSO->data['session']['comuser']['comusers_id'];
    } else {
        $id_session = false;
    }
    if ($post = mso_check_post(array('f_session_id', 'f_submit', 'f_comusers_email'))) {
        # защита рефера
        mso_checkreferer();
        # защита сессии - если не нужно закомментировать строчку!
        if ($MSO->data['session']['session_id'] != $post['f_session_id']) {
            mso_redirect();
        }
        if (!$password_recovery) {
            // получаем номер юзера id из f_submit[]
            $id = (int) mso_array_get_key($post['f_submit']);
            if (!$id) {
                return '<div class="' . $args['css_error'] . '">' . tf('Ошибочный номер пользователя') . '!</div>';
            }
            # проверяем id в сессии с сабмитом
            if ($id_session and $id != $id_session) {
                return '<div class="' . $args['css_error'] . '">' . tf('Ошибочный номер пользователя2') . '</div>';
            }
        }
        $comusers_email = trim($post['f_comusers_email']);
        if (!$comusers_email) {
            return '<div class="' . $args['css_error'] . '">' . tf('Нужно указать email') . '</div>';
        }
        if (!mso_valid_email($comusers_email)) {
            return '<div class="' . $args['css_error'] . '">' . tf('Ошибочный email') . '</div>';
        }
        $CI =& get_instance();
        // проверим есть ли вообще такой юзер
        $CI->db->select('comusers_id');
        if (!$password_recovery) {
            $CI->db->where('comusers_id', $id);
        }
        // если явно указан id, то ищем по нему
        $CI->db->where('comusers_email', $comusers_email);
        $query = $CI->db->get('comusers');
        if ($query->num_rows() == 0) {
            // нет такого комментатора
            return '<div class="' . $args['css_error'] . '">' . tf('Неверный email или номер пользователя') . '!</div>';
        }
        if ($password_recovery) {
            // получим id этого комюзера
            $res = $query->result_array();
            $id = $res[0]['comusers_id'];
        }
        $comusers_new_password = trim($post['f_comusers_password']);
        $comusers_activate_key = trim($post['f_comusers_activate_key']);
        if ($comusers_email and !$comusers_activate_key and !$comusers_new_password) {
            // проверим есть ли активация
            $CI->db->select('comusers_id, comusers_activate_key');
            $CI->db->where('comusers_id', $id);
            $CI->db->where('comusers_activate_string=comusers_activate_key', '', false);
            $CI->db->where('comusers_email', $comusers_email);
            $CI->db->limit(1);
            $query = $CI->db->get('comusers');
            if ($query->num_rows() > 0) {
                $comuser = $query->result_array();
                // данные комюзера
                mso_email_message_new_comuser($id, array('comusers_email' => $comusers_email, 'comusers_activate_key' => $comuser[0]['comusers_activate_key']));
                return '<div class="' . $args['css_ok'] . '">' . tf('Код активации отправлен на ваш email') . '!</div>';
            } else {
                return '<div class="' . $args['css_error'] . '">' . tf('Данный email не зарегистрирован или не активирован') . '</div>';
            }
        } elseif ($comusers_email and $comusers_new_password and !$comusers_activate_key) {
            return '<div class="' . $args['css_error'] . '">' . tf('Для установки нового пароля нужно заполнить все поля!') . '</div>';
        } elseif ($comusers_email and !$comusers_new_password and $comusers_activate_key) {
            // указан email и код активации, но не указан новый пароль
            return '<div class="' . $args['css_error'] . '">' . tf('Для установки нового пароля нужно заполнить все поля!') . '</div>';
        }
        // если указано поле активации и новый пароль, то сверяем код активации с базой + email + id и если все верно,
        // то обновляем пароль
        // если же поле активации не указано, то высылаем его на указанный email
        $CI->db->select('comusers_id');
        $CI->db->where('comusers_id', $id);
        $CI->db->where('comusers_activate_key', $comusers_activate_key);
        $CI->db->where('comusers_activate_string', $comusers_activate_key);
        $CI->db->where('comusers_email', $comusers_email);
        $CI->db->limit(1);
        $query = $CI->db->get('comusers');
        if ($query->num_rows() > 0) {
            $CI->db->where('comusers_id', $id);
            $CI->db->where('comusers_email', $comusers_email);
            $res = $CI->db->update('comusers', array('comusers_password' => mso_md5($comusers_new_password))) ? '1' : '0';
            $CI->db->cache_delete_all();
            if ($res) {
                // сразу логиним и редиректим на страницу комюзера
                $data = array('email' => $comusers_email, 'password' => $comusers_new_password, 'redirect' => getinfo('siteurl') . 'users/' . $id, 'allow_create_new_comuser' => false);
                mso_comuser_auth($data);
                exit;
                // return '<div class="' . $args['css_ok']. '">'. t('Новый пароль установлен!'). '</div>';
            } else {
                return '<div class="' . $args['css_error'] . '">' . tf('Ошибка БД при смене пароля...') . '</div>';
            }
        } else {
            return '<div class="' . $args['css_error'] . '">' . tf('Данные указаны неверно!') . '</div>';
        }
    }
}
Beispiel #11
0
 function _view_i($type = 'home', $vievers = 'index')
 {
     global $MSO;
     $data = array('type' => $type);
     $MSO->data = array_merge($this->data_def, $data);
     // если главная страница то проверим в сессии служебный массив _add_to_cookie
     // если он есть, то внесем из него все данные в куки
     //	[_add_to_cookie] => Array
     //	(
     //		[namecooke] => Array
     //			(
     //				[value] => ru
     //				[expire] => 1221749019
     //			)
     //	)
     //	[_add_to_cookie_redirect] => http://max-3000.com/page/about
     if ($type == 'home' and isset($this->session->userdata['_add_to_cookie'])) {
         foreach ($this->session->userdata['_add_to_cookie'] as $key => $val) {
             if (isset($val['value']) and isset($val['expire'])) {
                 setcookie($key, $val['value'], $val['expire']);
                 // записали в куку
             }
         }
         $this->session->unset_userdata('_add_to_cookie');
         // удаляем добавленное
         mso_flush_cache();
         // редирект на главную страницу
         if (isset($this->session->userdata['_add_to_cookie_redirect'])) {
             $r = $this->session->userdata['_add_to_cookie_redirect'];
             if (is_bool($r) or is_numeric($r)) {
                 // === true or $r === false) // логическая переменная
                 mso_redirect(getinfo('siteurl'), true);
             } else {
                 mso_redirect($r, true);
             }
             // редирект по указанному адресу
         } else {
             mso_redirect(getinfo('siteurl'), true);
         }
         // редирект на главную
         exit;
     }
     if (function_exists('mso_autoload_plugins')) {
         mso_autoload_plugins();
     }
     mso_hook('init');
     $this->load->view($vievers, $MSO->data);
 }
Beispiel #12
0
         $CI->db->where('comments_id', $id);
         $query = $CI->db->get();
         if ($query->num_rows() > 0) {
             $row = $query->row_array();
             mso_email_message_new_comment_subscribe(array('id' => $id, 'comments_approved' => (int) $post['f_comments_approved'], 'comments_content' => $post['f_comments_content'], 'comments_page_id' => $row['comments_page_id'], 'page_title' => $row['page_title']));
         }
     }
 } elseif ($post = mso_check_post(array('f_session_id', 'f_submit_delete'))) {
     // удалить комментарий
     mso_checkreferer();
     $CI->db->where_in('comments_id', $id);
     if ($CI->db->delete('comments')) {
         mso_flush_cache();
         // синхронизация количества комментариев у комюзеров
         mso_comuser_update_count_comment();
         mso_redirect('admin/comments');
     } else {
         echo '<div class="error">' . t('Ошибка удаления') . '</div>';
     }
 }
 # вывод данных комментария
 $CI->db->select('comments.*, users.users_nik, users.users_id, comusers.comusers_nik, page.page_title, page.page_slug, page.page_id');
 $CI->db->from('comments');
 $CI->db->join('users', 'users.users_id = comments.comments_users_id', 'left');
 $CI->db->join('comusers', 'comusers.comusers_id = comments.comments_comusers_id', 'left');
 $CI->db->join('page', 'page.page_id = comments.comments_page_id', 'left');
 $CI->db->where('comments_id', $id);
 $query = $CI->db->get();
 // если есть данные, то выводим
 if ($query->num_rows() > 0) {
     $row = $query->row_array();
Beispiel #13
0
function down_count_init($args = array())
{
    # опции плагина
    $options = mso_get_option('plugin_down_count', 'plugins', array());
    if (!isset($options['prefix'])) {
        $options['prefix'] = 'dc';
    }
    if (mso_segment(1) == $options['prefix'] and mso_segment(2)) {
        if (!isset($options['referer'])) {
            $options['referer'] = 1;
        }
        // запретить скачку с чужих сайтов
        if ($options['referer']) {
            // если нет реферера, то рубим
            if (!isset($_SERVER['HTTP_REFERER'])) {
                //
                die(sprintf('<b><font color="red">' . t('Данная ссылка доступна только со <a href="%s">страниц сайта</a>') . '</font></b>', getinfo('siteurl')));
            }
            // проверяем реферер - откуда пришел
            $p = parse_url($_SERVER['HTTP_REFERER']);
            if (isset($p['host'])) {
                $p = $p['host'];
            } else {
                $p = '';
            }
            if ($p != $_SERVER['HTTP_HOST']) {
                // чужой сайт
                die('<b><font color="red">' . t('Запрещен переход по этой ссылке с чужого сайта') . '</font></b>');
            }
        }
        // это редирект на указанный в сегментах url
        $url = base64_decode(mso_segment(2));
        // декодируем
        // проверяем входящий url
        // в нем может быть закодирована какая-то гадость
        $url_check = mso_xss_clean($url);
        if ($url_check != $url) {
            die('<b><font color="red">Achtung! XSS attack!</font></b>');
        }
        $url = $url_check;
        // получим данные
        $data = down_count_get_data();
        // вноисм изменения
        if (isset($data[$url])) {
            // такой url уже есть
            $data[$url]['count'] = $data[$url]['count'] + 1;
        } else {
            // нет еще
            $data[$url]['count'] = 1;
        }
        // записываем один переход
        // сохраняем в файл
        down_count_save_data($data);
        mso_redirect($url, true);
        exit;
    }
    return $args;
}
Beispiel #14
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;
    }
}
Beispiel #15
0
function loginza_auth_init($arg = array())
{
    if (mso_segment(1) == 'maxsite-loginza-auth') {
        // тут придет token
        if (!empty($_POST['token'])) {
            // token пришел? делаем редрект на страницу авторизации
            $auth_url = "http://loginza.ru/api/authinfo?token=" . $_POST['token'];
            $profile = loginza_auth_request($auth_url);
            $profile = json_decode($profile);
            if (!is_object($profile) || !empty($profile->error_message) || !empty($profile->error_type)) {
                $res_profile = (array) $profile['error_type'];
                die($res_profile['error_type']);
            }
            $curpage = mso_url_get();
            if ($curpage == getinfo('site_url')) {
                $curpage = false;
            }
            $email = (isset($profile->email) and mso_valid_email($profile->email)) ? $profile->email : null;
            $nick = isset($profile->name->full_name) ? $profile->name->full_name : null;
            if (isset($profile->email) and mso_valid_email($profile->email)) {
                require_once getinfo('common_dir') . 'comments.php';
                mso_comuser_auth(array('email' => $email, 'comusers_nik' => $nick, 'redirect' => $curpage));
                mso_redirect(getinfo('site_url'), true, 301);
            } else {
                // ссылка на главную или на предыдущую
                // pr( $profile );
                $txt = t('Не удалось авторизоваться с помощью выбранного сервиса.<br>Возможно это связано с тем, что в ответ на запрос 
				     сервис не возратил Ваш e-mail') . '<br>';
                $txt .= t('Вернуться на') . ' <a href="' . getinfo('site_url') . $curpage . '">' . t('предыдущую страницу') . '</a><br>';
                $txt .= t('Вернуться на') . ' <a href="' . getinfo('site_url') . '">' . t('главную страницу') . '</a><br>';
                die($txt);
            }
            die;
        }
    }
    return $arg;
}
Beispiel #16
0
/**
 * MaxSite CMS
 * (c) http://max-3000.com/
 */
if ($fn = mso_find_ts_file('main/main-start.php')) {
    require $fn;
}
echo NR . '<div class="mso-type-loginform">' . NR;
if (is_login()) {
    if (mso_segment(2) == 'error') {
        mso_redirect('loginform');
    }
    eval(mso_tmpl_ts('type/loginform/units/loginform-user-tmpl.php'));
} elseif ($comuser = is_login_comuser()) {
    if (mso_segment(2) == 'error') {
        mso_redirect('loginform');
    }
    if (!$comuser['comusers_nik']) {
        $hello = t('Привет!');
    } else {
        $hello = t('Привет,') . ' ' . $comuser['comusers_nik'] . '!';
    }
    eval(mso_tmpl_ts('type/loginform/units/loginform-comuser-tmpl.php'));
} else {
    $redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : getinfo('siteurl');
    if (mso_segment(2) == 'error') {
        eval(mso_tmpl_ts('type/loginform/units/loginform-error.php'));
    }
    // если разрешена регистрация, то выведем ссылку
    if (mso_get_option('allow_comment_comusers', 'general', '1')) {
        $reg = '<a href="' . getinfo('siteurl') . 'registration">' . tf('Регистрация') . '</a> | ';
Beispiel #17
0
function admin_home_logout($args = array())
{
    mso_redirect('logout');
}
Beispiel #18
0
}
/**
 * MaxSite CMS
 * (c) http://max-3000.com/
 */
?>

<h1><?php 
echo t('Основные настройки');
?>
</h1>
<p class="info"><?php 
echo t('Здесь вы можете указать основные настройки. Если указанная настройка отмечена «нет в базе», значит нужно ввести её значение и нажать кнопку «Сохранить».');
?>
</p>

<?php 
function _time_zone_current_time()
{
    return '<br>' . t('Время сервера:') . ' <strong>' . date('H:i:s Y-m-d') . '</strong>' . '<br>' . t('С учётом поправки:') . ' <strong>' . mso_date_convert('H:i:s Y-m-d', date('Y-m-d H:i:s')) . '</strong>';
}
$CI =& get_instance();
require_once getinfo('common_dir') . 'inifile.php';
// функции для работы с ini-файлом
// проверяем входящие данные
if (mso_check_post_ini()) {
    mso_redirect('admin/options');
}
$all = mso_get_ini_file($MSO->config['admin_plugins_dir'] . 'admin_options/general.ini');
echo mso_view_ini($all);
// вывод таблицы ini