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'] . '&page=' . mso_slug(mso_current_url()) . '&code=' . time() . '" alt="" title="' . tf('Защита от спама: введите только нижние символы') . '"> <span>' . t('(обязательно)') . '</span><br><br></div> '; }
function global_cache_key($dir = true) { $cache_key = $_SERVER['REQUEST_URI']; $cache_key = str_replace('/', '-', $cache_key); $cache_key = mso_slug(' ' . $cache_key); if ($dir) { $cache_key = 'html/' . $cache_key . '.html'; } else { $cache_key = $cache_key . '.html'; } return $cache_key; }
function admin_menu_menu($args = array()) { global $admin_menu, $MSO; $admin_url = getinfo('site_admin_url'); $nr = "\n"; $out = ''; if (count($MSO->data['uri_segment']) > 1) { $cur_url2 = $MSO->data['uri_segment'][2]; // второй сегмент # текущий урл строится из сегментов от второго до последнего $cur_url = $MSO->data['uri_segment']; $cur_url = array_slice($cur_url, 1); $cur_url = implode('/', $cur_url); if (!$cur_url) { $cur_url = 'home'; } } else { $cur_url = 'home'; $cur_url2 = 'home'; } // если меню не содержит подменю, то не выводим его $admin_menu1 = $admin_menu; foreach ($admin_menu1 as $key => $value) { if (count($admin_menu1[$key]) < 2) { unset($admin_menu1[$key]); } } // pr($admin_menu1); foreach ($admin_menu1 as $key => $value) { $out .= $nr . '<ul class="admin-menu admin-menu-' . ($key ? $key : 'beginning') . '">'; $out .= $nr . '<li class="admin-menu-top"><a href="#" class="admin-menu-section">' . _mso_del_menu_pod($value['']) . '</a>'; if (count($value) > 1) { $out .= $nr . ' <ul class="admin-submenu">'; foreach ($value as $url => $name) { if ($value[''] == $name) { continue; } if ($url == $cur_url or $url == $cur_url2) { $selected = ' class="admin-menu-selected admin-menu-' . mso_slug($url) . '"'; } else { $selected = ' class="admin-menu-' . mso_slug($url) . '"'; } $out .= $nr . ' <li' . $selected . ' title="' . _mso_del_menu_pod($name) . '"><a href="' . $admin_url . $url . '">' . _mso_del_menu_pod($name) . '</a></li>'; } $out .= $nr . ' </ul>'; } $out .= $nr . ' </li>' . $nr . '</ul>' . $nr; } return $out; }
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; } }
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_', '"', $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_', '"', $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('&', '&', $mr); $mr = str_replace('"', '"', $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('<', '<', $mr2); $mr2 = str_replace('>', '>', $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; }
function last_comments_widget_custom($options = array(), $num = 1) { if (!isset($options['count'])) { $options['count'] = 5; } if (!isset($options['words'])) { $options['words'] = 20; } if (!isset($options['maxchars'])) { $options['maxchars'] = 20; } if (!isset($options['header'])) { $options['header'] = ''; } $options['count'] = (int) $options['count']; if ($options['count'] < 1) { $options['count'] = 5; } $options['words'] = (int) $options['words']; if ($options['words'] < 1) { $options['words'] = 20; } $options['maxchars'] = (int) $options['maxchars']; if ($options['maxchars'] < 1) { $options['maxchars'] = 20; } $cache_key = 'last_comments_widget_' . $num . mso_md5(serialize($options)); $k = mso_get_cache($cache_key, true); if ($k) { return $k; } // да есть в кэше require_once getinfo('common_dir') . 'comments.php'; // функции комментариев $comments = mso_get_comments(false, array('limit' => $options['count'], 'order' => 'desc')); $out = ''; if ($comments) { // сгруппируем все комментарии по записям $arr_com_page = array(); $arr_com_page_title = array(); foreach ($comments as $comment) { $arr_com_page[$comment['page_id']][$comment['comments_id']] = $comment; $arr_com_page_title[$comment['page_id']] = $comment['page_title']; } // выводим по странично foreach ($arr_com_page as $key => $comments) { $out .= '<h5>' . $arr_com_page_title[$key] . '</h5>'; $comments = array_reverse($comments); // чтобы комментарии были в привычном порядке сверху вниз $out .= '<ul class="mso-widget-list">'; foreach ($comments as $comment) { extract($comment); if ($comment['comments_users_id']) { $css_style_add = 'last_comment_users ' . ' mso-last-comment-users-' . $comment['comments_users_id']; } elseif ($comment['comments_comusers_id']) { $css_style_add = 'last_comment_comusers ' . ' mso-last-comment-comusers-' . $comment['comments_comusers_id']; } else { $css_style_add = 'last_comment_anonim'; } $out .= '<li class="' . $css_style_add . '"><a href="' . getinfo('siteurl') . 'page/' . mso_slug($page_slug) . '#comment-' . $comments_id . '"><b>'; if ($comments_users_id) { $out .= $users_nik; } elseif ($comments_comusers_id) { if ($comusers_nik) { $out .= $comusers_nik; } else { $out .= t('Комментатор') . ' ' . $comusers_id; } } elseif ($comments_author_name) { $out .= $comments_author_name; } else { $out .= ' ' . t('Аноним'); } $comments_content_1 = strip_tags($comments_content); // удалим тэги $comments_content = mso_str_word($comments_content_1, $options['words']); // ограничение на количество слов // если старый и новый текст после обрезки разные, значит добавим в конце ... if ($comments_content_1 != $comments_content) { $comments_content .= '...'; } // каждое слово нужно проверить на длину и если оно больше maxchars, то добавить пробел в wordwrap $words = explode(' ', $comments_content); foreach ($words as $key => $word) { $words[$key] = mso_wordwrap($word, $options['maxchars'], ' '); } $comments_content = implode(' ', $words); $out .= ' »</b> ' . strip_tags($comments_content) . '</a>'; $out .= '</li>' . NR; } $out .= '</ul>'; } if ($options['header']) { $out = $options['header'] . $out; } } mso_add_cache($cache_key, $out, false, true); // сразу в кэш добавим return trim($out); }
*/ $f_header = $post['f_header']; if (isset($post['f_tags']) and $post['f_tags']) { $f_tags = $post['f_tags']; } else { $f_tags = ''; } if (isset($post['f_menu_order'])) { $page_menu_order = (int) $post['f_menu_order']; } else { $page_menu_order = ''; } if (isset($post['f_slug']) and $post['f_slug']) { $f_slug = $post['f_slug']; } else { $f_slug = mso_slug($f_header); } if (isset($post['f_password']) and $post['f_password']) { $f_password = $post['f_password']; } else { $f_password = ''; } if (isset($post['f_cat'])) { $f_cat = $post['f_cat']; } else { $f_cat = array(); } // все мета $f_options = ''; if (isset($post['f_options'])) { foreach ($post['f_options'] as $key => $val) {
$old_link = ''; } if (!isset($item['wp']['post_name'])) { $slug = mso_slug($item['title']); } else { $slug = urldecode($item['wp']['post_name']); } $slug_new = mso_slug($slug); // если $slug = числу, то нужно его заменить на заголовок $i = (int) $slug; if ((string) $slug != (string) $i) { $i = false; } // slug не число if ($i) { $slug_new = mso_slug($item['title']); } $comment_allow = $item['wp']['comment_status'] == 'open' ? '1' : '0'; if (!isset($item['content'])) { $content = ''; } else { $content = $item['content']; } $content = str_replace(chr(10), "<br>", $content); $content = str_replace(chr(13), "", $content); $content = str_replace('<!--more-->', '[cut]', $content); $post_date = $item['wp']['post_date']; if ($post_date == '0000-00-00 00:00:00') { $post_date = date('Y-m-d H:i:s'); } $data = array('page_id_autor' => $MSO->data['session']['users_id'], 'page_title' => $item['title'], 'page_content' => $content, 'page_status' => $status, 'page_type_id' => $page_type_id, 'page_slug' => $slug_new, 'page_comment_allow' => $comment_allow, 'page_tags' => $tag, 'page_date_publish' => $post_date, 'page_id_cat' => implode(',', $cat1));
if ($f = mso_page_foreach('comments-do')) { require $f; } else { echo '<h1 class="comments">' . tf('Последние комментарии') . '</h1>'; echo '<p class="info"><a href="' . getinfo('siteurl') . 'comments/feed">' . tf('Подписаться по RSS') . '</a>'; echo '<br><a href="' . getinfo('siteurl') . 'users">' . tf('Список комментаторов') . '</a></p>'; } echo '<div class="comments">'; if ($comments) { echo '<ul>'; foreach ($comments as $comment) { if ($f = mso_page_foreach('comments')) { require $f; // подключаем кастомный вывод continue; // следующая итерация } extract($comment); echo '<li><span><a href="' . getinfo('siteurl') . 'page/' . mso_slug($page_slug) . '#comment-' . $comments_id . '" name="comment-' . $comments_id . '">' . $page_title . '</a>'; echo ' | ' . $comments_url; echo '</span><br>' . $comments_date; echo '</span><br>' . $comments_content; echo '</li>'; // pr($comment); } echo '</ul>'; } echo '</div>'; } echo NR . '</div><!-- class="type type_comments" -->' . NR; require getinfo('template_dir') . 'main-end.php';
*/ # подготовка данных $min_search_chars = 2; // минимальное кол-во симоволов при поиске $search = mso_segment(2); $search = mso_strip(strip_tags($search)); $searh_to_text = mb_strtolower($search, 'UTF8'); if ($f = mso_page_foreach('search-head-meta')) { require $f; } else { mso_head_meta('title', $search); } $search_len = true; // поисковая фраза более 2 символов // параметры для получения страниц if (!$search or $search_len = strlen(mso_slug($search)) < $min_search_chars) { $search = tf('Поиск'); $pages = false; // нет страниц $categories = false; // нет рубрик $tags = false; // нет меток } else { $par = array('limit' => 7, 'cut' => false, 'type' => false); // подключаем кастомный вывод, где можно изменить массив параметров $par для своих задач if ($f = mso_page_foreach('search-mso-get-pages')) { require $f; } $pages = mso_get_pages($par, $pagination); // получим все - второй параметр нужен для сформированной пагинации
function mso_get_comuser($id = 0, $args = array()) { global $MSO; if (!$id) { // не указан id, получаем его из сессии if (isset($MSO->data['session']['comuser']) and $MSO->data['session']['comuser']) { $id = $MSO->data['session']['comuser']['comusers_id']; } else { $id = mso_segment(2); } // или сегмент в url } if (!$id) { return array(); } // нет номера, выходим if (!is_numeric($id)) { return array(); } // если id указан не номером, выходим if (!isset($args['limit'])) { $args['limit'] = 20; } if (!isset($args['tags'])) { $args['tags'] = '<p><img><strong><em><i><b><u><s><font><pre><code><blockquote>'; } if (!isset($args['order'])) { $args['order'] = 'comments_date'; } if (!isset($args['asc'])) { $args['asc'] = 'desc'; } $CI =& get_instance(); $CI->db->select('comusers.*, COUNT(comments_comusers_id) as comusers_count_comment_real'); $CI->db->from('comusers'); $CI->db->where('comusers_id', $id); $CI->db->limit(1); // отдавать все комменты, включая и неотмодерированные //$CI->db->where('comments.comments_approved', '1'); $CI->db->join('comments', 'comusers.comusers_id = comments.comments_comusers_id', 'left'); $CI->db->group_by('comments_comusers_id'); $query = $CI->db->get(); if ($query->num_rows() > 0) { $comuser = $query->result_array(); // данные комюзера // pr($comuser); $comuser_count_comment_first = $comuser[0]['comusers_count_comments']; // первоначальное значание колво комментариев // подсоединим к нему [comments] - все его комментарии $CI->db->select('comments.*, page.page_id, page.page_title, page.page_slug'); $CI->db->from('comments'); $CI->db->where('comments_comusers_id', $id); // $CI->db->where('page.page_status', 'publish'); // $CI->db->where('page_date_publish <', date('Y-m-d H:i:s')); $CI->db->where('comments.comments_approved', '1'); $CI->db->join('page', 'page.page_id = comments.comments_page_id'); $CI->db->order_by('comments_date', $args['asc']); if ($args['limit']) { $CI->db->limit($args['limit']); } $query = $CI->db->get(); $comments = array(); // все комменты if ($query->num_rows() > 0) { // нужно обработать тексты комментариев на предмет всяких хуков и лишних тэгов $comments = $query->result_array(); foreach ($comments as $key => $comment) { $comments[$key]['comments_content'] = mso_comments_content($comment['comments_content']); } $comuser[0]['comments'] = $comments; // $comuser[0]['comments'] = $query->result_array(); $comuser[0]['comusers_count_comments'] = count($comments); } else { $comuser[0]['comments'] = array(); } if ($comuser_count_comment_first != count($comments)) { mso_comuser_set_count_comment($id, count($comments)); } // в секцию meta добавим все метаполя данного юзера $CI->db->select('meta_key, meta_value'); $CI->db->from('meta'); $CI->db->where('meta_table', 'comusers'); $CI->db->where('meta_id_obj', $id); $query = $CI->db->get(); if ($query->num_rows() > 0) { // переделаем полученный массив в key = value foreach ($query->result_array() as $val) { $comuser[0]['comusers_meta'][$val['meta_key']] = $val['meta_value']; } } else { $comuser[0]['comusers_meta'] = array(); } // от вских гадостей $comuser[0]['comusers_url'] = mso_xss_clean($comuser[0]['comusers_url']); if ($comuser[0]['comusers_url'] and strpos($comuser[0]['comusers_url'], 'http://') === false) { $comuser[0]['comusers_url'] = 'http://' . $comuser[0]['comusers_url']; } $comuser[0]['comusers_msn'] = mso_xss_clean($comuser[0]['comusers_msn']); // twitter $comuser[0]['comusers_msn'] = mso_slug(str_replace('@', '', $comuser[0]['comusers_msn'])); // подчистка $comuser[0] = mso_clean_post(array('comusers_nik' => 'base', 'comusers_icq' => 'base', 'comusers_jaber' => 'base', 'comusers_skype' => 'base', 'comusers_description' => 'base', 'comusers_msn' => 'base', 'comusers_url' => 'base'), $comuser[0]); // pr($comuser); return $comuser; } else { return array(); } }
function mso_upload($config_library = array(), $field_userfile = 'f_userfile', $r = array()) { $CI =& get_instance(); $CI->load->library('upload', $config_library); $CI->upload->initialize($config_library); // если была отправка файла, то нужно заменить поле имени с русского на что-то другое // это ошибка при копировании на сервере - он не понимает русские буквы if (isset($_FILES[$field_userfile]['name'])) { $f_temp = $_FILES[$field_userfile]['name']; // оставим только точку $f_temp = str_replace('.', '__mso_t__', $f_temp); $f_temp = mso_slug($f_temp); // остальное как обычно mso_slug $f_temp = str_replace('__mso_t__', '.', $f_temp); $ext = str_replace('.', '', strrchr($f_temp, '.')); // расширение файла if ($f_temp == '.' . $ext) { // имя файла состоит только из расширения «.jpg» $f_temp = '1' . $f_temp; } // добавляем к нему единицу $_FILES[$field_userfile]['name'] = $f_temp; } $res = $CI->upload->do_upload($field_userfile); if (!isset($r['message1'])) { $r['message1'] = '<div class="update">' . t('Загрузка выполнена') . '</div>'; } if (!isset($r['message2'])) { $r['message2'] = '<div class="error">' . t('Не удалось перименовать файл в нижний регистр') . '</div>'; } // описание файла if (!isset($r['userfile_title'])) { $r['userfile_title'] = false; } // файл, где хранится описание if (!isset($r['fn_mso_descritions'])) { $r['fn_mso_descritions'] = false; } // нужно ли менять размер if (!isset($r['userfile_resize'])) { $r['userfile_resize'] = true; } if (!isset($r['userfile_resize_size'])) { $r['userfile_resize_size'] = false; } // какой размер // водяной знак if (!isset($r['userfile_water'])) { $r['userfile_water'] = false; } // нужен ли водяной знак if (!isset($r['userfile_water_file'])) { $r['userfile_water_file'] = false; } // файл водяного знака if (!isset($r['water_type'])) { $r['water_type'] = 1; } // тип водяного знака // миниатюры всегда хранятся в подкаталоге mini if (!isset($r['userfile_mini'])) { $r['userfile_mini'] = true; } // делать миниатюру? if (!isset($r['userfile_mini_size'])) { $r['userfile_mini_size'] = false; } // размер миниатюры if (!isset($r['mini_type'])) { $r['mini_type'] = 1; } // тип миниатюры // превьюхи всегда хранятся в подкаталоге _mso_i if (!isset($r['prev_size'])) { $r['prev_size'] = 100; } // размер превьюхи if ($res) { echo $r['message1']; // если это файл картинки, то нужно сразу сделать скриншот маленький в _mso_i 100px, который будет выводиться в // списке файлов $up_data = $CI->upload->data(); // файл нужно поменять к нижнему регистру if ($up_data['file_name'] != strtolower($up_data['file_name'])) { // переименуем один раз if (rename($up_data['full_path'], $up_data['file_path'] . strtolower('__' . $up_data['file_name']))) { // потом второй в уже нужный - это из-за бага винды rename($up_data['file_path'] . strtolower('__' . $up_data['file_name']), $up_data['file_path'] . strtolower($up_data['file_name'])); $up_data['file_name'] = strtolower($up_data['file_name']); $up_data['full_path'] = $up_data['file_path'] . $up_data['file_name']; // echo '<div class="update">' . $up_data['full_path'] . $up_data['file_name'] . '</div>'; } else { echo $r['message2']; } } // если указано описание файла и файл, где это описание хранится if ($r['userfile_title'] and $r['fn_mso_descritions']) { $fn_descr = trim(strip_tags($r['userfile_title'])); // описание файла $fn_descr = str_replace('"', '', $fn_descr); // удалим лишнее $fn_descr = str_replace('\'', '', $fn_descr); if (file_exists($r['fn_mso_descritions'])) { // массив данных: fn => описание ) $mso_descritions = unserialize(read_file($r['fn_mso_descritions'])); // получим из файла все описания } else { $mso_descritions = array(); } $mso_descritions[$up_data['file_name']] = $fn_descr; write_file($r['fn_mso_descritions'], serialize($mso_descritions)); // сохраняем в файл } /* [file_name] => warfare7.jpg [file_type] => image/jpeg [file_path] => D:/xampplite/htdocs/codeigniter/uploads/ [full_path] => D:/xampplite/htdocs/codeigniter/uploads/warfare7.jpg [raw_name] => warfare7 [orig_name] => warfare.jpg [file_ext] => .jpg [file_size] => 52.09 [is_image] => 1 [image_width] => 450 [image_height] => 300 [image_type] => jpeg [image_size_str] => width="450" height="300" */ if ($up_data['is_image']) { $CI->load->library('image_lib'); $CI->image_lib->clear(); # вначале нужно изменить размер # потом делаем миниатюру с указанными размерами # потом делаем такую же миниатюру для _mso_i с размером 100x100 # меняем размер if ($r['userfile_resize'] and $r['userfile_resize_size']) { $size = abs((int) $r['userfile_resize_size']); $up_data['image_width'] >= $up_data['image_height'] ? $max = $up_data['image_width'] : ($max = $up_data['image_height']); if ($size > 1 and $size < $max) { $r_conf = array('image_library' => 'gd2', 'source_image' => $up_data['full_path'], 'new_image' => $up_data['full_path'], 'maintain_ratio' => true, 'width' => $size, 'height' => $size); $CI->image_lib->initialize($r_conf); if (!$CI->image_lib->resize()) { echo '<div class="error">' . t('Уменьшение изображения:') . ' ' . $CI->image_lib->display_errors() . '</div>'; } } } //Меняли или не меняли размер, но теперь проверяем, нужна ли нам ватермарка. if ($r['userfile_water'] and $r['userfile_water_file']) { //todo — проверка, всё ли нам прислали, всё ли на месте. В идеале бы проверить размеры картинки по отношению к ватермарке. if (!file_exists($r['userfile_water_file'])) { echo '<div class="error">' . t('Водяной знак:') . ' ' . t('файл водяного знака не найден! Загрузите его в каталог uploads/') . '</div>'; } else { $water_type = $r['water_type']; // Расположение ватермарка $hor = 'right'; //Инитим дефолтом. $vrt = 'bottom'; //Инитим дефолтом. if ($water_type == 2 or $water_type == 4) { $hor = 'left'; } if ($water_type == 2 or $water_type == 3) { $vrt = 'top'; } if ($water_type == 1) { $hor = 'center'; $vrt = 'middle'; } $r_conf = array('image_library' => 'gd2', 'source_image' => $up_data['full_path'], 'new_image' => $up_data['full_path'], 'wm_type' => 'overlay', 'wm_vrt_alignment' => $vrt, 'wm_hor_alignment' => $hor, 'wm_overlay_path' => $r['userfile_water_file']); $CI->image_lib->initialize($r_conf); if (!$CI->image_lib->watermark()) { echo '<div class="error">' . t('Водяной знак:') . ' ' . $CI->image_lib->display_errors() . '</div>'; } } } # делаем миниатюру mso_upload_mini($up_data, $r); # превьюшка mso_upload_prev($up_data, $r); } return true; } else { $er = $CI->upload->display_errors(); echo '<div class="error">' . t('Ошибка загрузки файла.') . $er . '</div>'; return false; } }
function sitemap($arg = '') { if (mso_segment(2) == 'cat') { return sitemap_cat($arg); } global $MSO; // кэш строим по url, потому что у он меняется от пагинации $cache_key = 'sitemap' . serialize($MSO->data['uri_segment']); $k = mso_get_cache($cache_key); if ($k) { return $k; } // да есть в кэше $options = mso_get_option('plugin_sitemap', 'plugins', array()); // получаем опции if (!isset($options['limit'])) { $options['limit'] = 30; } else { $options['limit'] = (int) $options['limit']; } if ($options['limit'] < 2) { $options['limit'] = 30; } $out = ''; // параметры для получения страниц $par = array('limit' => $options['limit'], 'custom_type' => 'home', 'content' => false, 'cat_order' => 'category_id_parent', 'cat_order_asc' => 'asc'); if ($f = mso_page_foreach('sitemap-mso-get-pages')) { require $f; } $pages = mso_get_pages($par, $pagination); // получим все if ($pages) { $out .= '<div class="page_content"><div class="sitemap">' . NR . mso_hook('sitemap_do'); $out .= '<div class="sitemap-link"><a href="' . getinfo('siteurl') . 'sitemap/cat">' . tf('Группировка по рубрикам') . '</a>' . NR . '</div>'; $first = true; foreach ($pages as $page) { $date = mso_date_convert('m/Y', $page['page_date_publish']); if ($first) { $out .= '<h3>' . $date . '</h3>' . NR . '<ul>' . NR; $first = false; } elseif ($date1 != $date) { $out .= '</ul>' . NR . '<h3>' . $date . '</h3>' . NR . '<ul>' . NR; } $slug = mso_slug($page['page_slug']); $out .= '<li>' . mso_date_convert('d', $page['page_date_publish']) . ': <a href="' . getinfo('siteurl') . 'page/' . $slug . '" title="' . htmlspecialchars($page['page_title']) . '">' . htmlspecialchars($page['page_title']) . '</a>'; if ($page['page_categories']) { $out .= ' <span>(' . mso_page_cat_link($page['page_categories'], ' → ', '', '', false) . ')</span>'; } # синонимы ссылок /* . ' (' . '<a href="' . getinfo('siteurl') . $slug . '" title="slug: ' . $slug . '">slug</a>, ' . '<a href="' . getinfo('siteurl') . 'page/' . $page['page_id'] . '" title="page: ' . $page['page_id'] . '">page: ' . $page['page_id'] . '</a>, ' . '<a href="' . getinfo('siteurl') . $page['page_id'] . '" title="id: ' . $page['page_id'] . '">id: ' . $page['page_id'] . '</a>)' */ # /синонимы ссылок $out .= '</li>' . NR; $date1 = $date; } $out .= '</ul>' . NR . mso_hook('sitemap_posle') . '</div></div>' . NR; } $pagination['type'] = ''; ob_start(); mso_hook('pagination', $pagination); $out .= ob_get_contents(); ob_end_clean(); mso_add_cache($cache_key, $out); // сразу в кэш добавим return $out; }
function mso_show_sidebar($sidebar = '1', $block_start = '<div class="widget widget_[NUMW] widget_[SB]_[NUMW] [FN] [FN]_[NUMF]"><div class="w0"><div class="w1">', $block_end = '</div><div class="w2"></div></div></div>', $echo = true) { global $MSO, $page; // чтобы был доступ к параметрам страниц в условиях виджетов static $num_widget = array(); // номер виджета по порядку в одном сайдбаре $widgets = mso_get_option('sidebars-' . $sidebar, 'sidebars', array()); $out = ''; if ($widgets) { foreach ($widgets as $widget) { $usl_res = 1; // предполагаем, что нет условий, то есть всегда true // имя виджета может содержать номер через пробел $arr_w = explode(' ', $widget); // в массив if (sizeof($arr_w) > 1) { $widget = trim($arr_w[0]); // первый - функция $num = trim($arr_w[1]); // второй - номер виджета if (isset($arr_w[2])) { $u = $arr_w; // поскольку у нас разделитель пробел, то нужно до конца все подбить в одну строчку $u[0] = $u[1] = ''; $usl = trim(implode(' ', $u)); // текст условия, is_type('home') or is_type('category') $usl = 'return ( ' . $usl . ' ) ? 1 : 0;'; $usl_res = eval($usl); // выполяем if ($usl_res === false) { $usl_res = 1; } // возможно произошла ошибка } } else { $num = 0; // номер виджета не указан, значит 0 } // номер функции виджета может быть не только числом, но и текстом // если текст, то нужно его преобразовать в slug, чтобы исключить // некоректную замену [NUMF] для стилей $num = mso_slug($num); // двойной - заменим на один - защита id в форме админки $num = str_replace('--', '-', $num); if (function_exists($widget) and $usl_res === 1) { if ($temp = $widget($num)) { if (isset($num_widget[$sidebar]['numw'])) { $numw = ++$num_widget[$sidebar]['numw']; $num_widget[$sidebar]['numw'] = $numw; } else { $numw = $num_widget[$sidebar]['numw'] = 1; } $st = str_replace('[FN]', $widget, $block_start); // название функции виджета $st = str_replace('[NUMF]', $num, $st); // номер функции $st = str_replace('[NUMW]', $numw, $st); // $st = str_replace('[SB]', $sidebar, $st); // номер сайдбара $en = str_replace('[FN]', $widget, $block_end); $en = str_replace('[NUMF]', $num, $en); $en = str_replace('[NUMW]', $numw, $en); $en = str_replace('[SB]', $sidebar, $en); // обрамим содержимое виджета в div.widget-content /* if (stripos($temp, mso_get_val('widget_header_end', '</span></h2>')) !== false) { // есть вхождение заголовка виджета <h2> $temp = str_replace(mso_get_val('widget_header_end', '</span></h2>'), mso_get_val('widget_header_end', '</span></h2>') . '<div class="widget-content">', $temp); $en = '</div>' . $en; } else { $temp = '<div class="widget-content">' . $temp . '</div>'; } */ $out .= $st . $temp . $en; } } } if ($echo) { echo $out; } else { return $out; } } }
<?php // mso_hook('widgets_show_form'); // pr($MSO->sidebars); $error = ''; $all_name_sidebars = array(); // все сайдбары $form = ''; if ($MSO->sidebars) { // есть сайдбары foreach ($MSO->sidebars as $name => $sidebar) { // у сайддара уже может быть определены виджеты - считываем их из опций // потому что мы их будем там хранить // это простой массив с именами виджетов $options = mso_get_option('sidebars-' . mso_slug($name), 'sidebars', array()); $count_rows = count($options) + 1; if ($count_rows < 5) { $count_rows = 5; } $options = implode("\n", $options); // разделим по строкам $form .= '<h2>' . $sidebar['title'] . ':</h2>'; $form .= '<textarea class="admin_sidebars" id="f_sidebars[' . $name . ']" name="f_sidebars[' . $name . ']" rows="' . $count_rows . '">'; $form .= htmlspecialchars($options); $form .= '</textarea>'; $all_name_sidebars[$name] = $sidebar['title']; } } else { $error .= '<div class="error">' . t('Сайдбары не определены. Обычно они регистрируются в файле <b>functions.php</b> вашего шаблона. Например:') . ' <br><b>mso_register_sidebar(\'1\', \'' . t('Первый сайдбар') . '\');</b></div>'; }
$segments .= '/' . $current_sub_dir; } $path = getinfo('uploads_dir') . $current_dir; if (!is_dir($path)) { $path = getinfo('uploads_dir'); $current_dir = ''; $current_sub_dir = ''; } # новый каталог - создаем до того, как отобразить навигацию if ($post = mso_check_post(array('f_session3_id', 'f_cat_name', 'f_newcat_submit'))) { mso_checkreferer(); // возможно указан подкаталог через / $f_cat_name = str_replace('/', '__mso_sub__', $post['f_cat_name']); $f_cat_name = str_replace('.', '', $f_cat_name); // точки не может быть вовсе $f_cat_name = mso_slug($f_cat_name); $f_cat_name = trim(str_replace('__mso_sub__', ' ', $f_cat_name)); // подкаталог может быть только один // делаем через массив — так проще $f_cat_name = explode(' ', $f_cat_name); $f_cat_name = array_slice($f_cat_name, 0, 2); // срез — максимум 2 сегмента // pr($f_cat_name); // базовый каталог должен уже быть создан if (isset($f_cat_name[1]) and $f_cat_name[1] and !is_dir(getinfo('uploads_dir') . $f_cat_name[0])) { echo '<div class="error">' . sprintf(t('Вначале создайте каталог <strong>%s</strong>!'), $f_cat_name[0]) . '</div>'; } else { $f_cat_name = implode('/', $f_cat_name); //_pr($f_cat_name); if (!$f_cat_name) { echo '<div class="error">' . t('Нужно ввести имя каталога') . '</div>';
} } 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"> </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');
function admin_menu_menu($args = array()) { global $admin_menu, $admin_menu_bread, $MSO, $admin_menu_select_option; $admin_url = getinfo('site_admin_url'); $admin_menu_bread = array(); // хлебные крошки $nr = "\n"; $out = ''; $admin_menu_select_option = ''; // <option> для <select> if (count($MSO->data['uri_segment']) > 1) { $cur_url2 = $MSO->data['uri_segment'][2]; // второй сегмент # текущий урл строится из сегментов от второго до последнего $cur_url = $MSO->data['uri_segment']; $cur_url = array_slice($cur_url, 1); $cur_url = implode('/', $cur_url); if (!$cur_url) { $cur_url = 'home'; } } else { $cur_url = 'home'; $cur_url2 = 'home'; } // если меню не содержит подменю, то не выводим его $admin_menu1 = $admin_menu; foreach ($admin_menu1 as $key => $value) { if (count($admin_menu1[$key]) < 2) { unset($admin_menu1[$key]); } } // pr($admin_menu1); foreach ($admin_menu1 as $key => $value) { // обрамляющий ul.admin-menu — выводим в конце цикла, чтобы задать css-классы $out_block_css_class = 'admin-menu admin-menu-' . ($key ? $key : 'beginning'); $out1 = $nr . '<li class="admin-menu-top"><a href="#" class="admin-menu-section admin-menu-section-' . ($key ? $key : 'beginning') . '">' . _mso_del_menu_pod($value['']) . '</a>'; $admin_menu_select_option .= '<optgroup label="' . htmlspecialchars(_mso_del_menu_pod($value[''])) . '">' . NR; if (count($value) > 1) { $out1 .= $nr . '<ul class="admin-submenu">'; foreach ($value as $url => $name) { if ($value[''] == $name) { continue; } $opt_selected = ''; if ($url == $cur_url or $url == $cur_url2) { $selected = ' class="admin-menu-selected admin-menu-' . mso_slug($url) . '"'; $opt_selected = ' selected'; $out_block_css_class .= ' admin-menu-top-selected'; if (!$admin_menu_bread) { $admin_menu_bread[] = _mso_del_menu_pod($value['']); $admin_menu_bread[] = _mso_del_menu_pod($name); } } elseif ($key == 'page' and $cur_url2 == 'page_edit') { $out_block_css_class .= ' admin-menu-top-selected'; $selected = ' class="admin-menu-' . mso_slug($url) . '"'; } else { $selected = ' class="admin-menu-' . mso_slug($url) . '"'; } $out1 .= $nr . ' <li' . $selected . ' title="' . _mso_del_menu_pod($name) . '"><a href="' . $admin_url . $url . '">' . _mso_del_menu_pod($name) . '</a></li>'; $admin_menu_select_option .= '<option value="' . $admin_url . $url . '"' . $opt_selected . '>' . _mso_del_menu_pod($name) . '</option>' . NR; } $out1 .= $nr . ' </ul>'; } $out1 .= $nr . ' </li>'; $out .= $nr . '<ul class="' . $out_block_css_class . '">' . $out1 . '</ul>' . $nr; } return $out; }
function admin_menu_menu($args = array()) { global $admin_menu, $admin_menu_bread, $MSO, $admin_menu_select_option; $admin_url = getinfo('site_admin_url'); $admin_menu_bread = array(); // хлебные крошки $nr = "\n"; $out = ''; $admin_menu_select_option = ''; // <option> для <select> if (count($MSO->data['uri_segment']) > 1) { $cur_url2 = $MSO->data['uri_segment'][2]; // второй сегмент # текущий урл строится из сегментов от второго до последнего $cur_url = $MSO->data['uri_segment']; $cur_url = array_slice($cur_url, 1); $cur_url = implode('/', $cur_url); if (!$cur_url) { $cur_url = 'home'; } } else { $cur_url = 'home'; $cur_url2 = 'home'; } // если меню не содержит подменю, то не выводим его $admin_menu1 = $admin_menu; foreach ($admin_menu1 as $key => $value) { if (count($admin_menu1[$key]) < 2) { unset($admin_menu1[$key]); } } // pr($admin_menu1); foreach ($admin_menu1 as $key => $value) { // обрамляющий ul.admin-menu — выводим в конце цикла, чтобы задать css-классы $out_block_css_class = 'admin-menu admin-menu-' . ($key ? $key : 'beginning'); $out1 = $nr . '<li class="admin-menu-top"><a href="#" class="admin-menu-section admin-menu-section-' . ($key ? $key : 'beginning') . '">' . _mso_del_menu_pod($value['']) . '</a>'; $admin_menu_select_option .= '<optgroup label="' . htmlspecialchars(_mso_del_menu_pod($value[''])) . '">' . NR; if (count($value) > 1) { $out1 .= $nr . '<ul class="admin-submenu">'; foreach ($value as $url => $name) { if ($value[''] == $name) { continue; } $opt_selected = ''; if ($url == $cur_url or $url == $cur_url2) { $selected = ' class="admin-menu-selected admin-menu-' . mso_slug($url) . '"'; $opt_selected = ' selected'; $out_block_css_class .= ' admin-menu-top-selected'; if (!$admin_menu_bread) { $admin_menu_bread[] = _mso_del_menu_pod($value['']); $admin_menu_bread[] = _mso_del_menu_pod($name); } } elseif ($key == 'page' and $cur_url2 == 'page_edit') { $out_block_css_class .= ' admin-menu-top-selected'; $selected = ' class="admin-menu-' . mso_slug($url) . '"'; } else { $selected = ' class="admin-menu-' . mso_slug($url) . '"'; } $out1 .= $nr . ' <li' . $selected . ' title="' . _mso_del_menu_pod($name) . '"><a href="' . $admin_url . $url . '">' . _mso_del_menu_pod($name) . '</a></li>'; $admin_menu_select_option .= '<option value="' . $admin_url . $url . '"' . $opt_selected . '>' . _mso_del_menu_pod($name) . '</option>' . NR; } $out1 .= $nr . '</ul>'; } $out1 .= $nr . ' </li>'; $out .= $nr . '<ul class="' . $out_block_css_class . '">' . $out1 . '</ul>' . $nr; } // пункты в настройки админ-панели в отдельную опцию // добавляется в самый верх в Избранное $admin_menu_favorites = trim(mso_get_option('admin_menu_favorites', 'general')); if ($admin_menu_favorites) { $menu = str_replace("\r", "", $admin_menu_favorites); // если это windows $menu = str_replace("_NR_", "\n", $menu); $menu = str_replace(" ~ ", "\n", $menu); $menu = str_replace("\n\n\n", "\n", $menu); $menu = str_replace("\n\n", "\n", $menu); $menu = explode("\n", trim($menu)); $out_my = '<ul class="admin-menu admin-menu-favorites"><li class="admin-menu-top"><a href="#" class="admin-menu-section admin-menu-section-favorites">' . t('Избранное') . '</a><ul class="admin-submenu">'; $my_admin_menu_select_option = '<optgroup label="' . htmlspecialchars(t('Избранное')) . '">'; foreach ($menu as $elem) { # разобъем строчку по адрес | название $elem = explode('|', trim($elem)); $elem = array_map('trim', $elem); $elem = array_unique($elem); $url = $name = $attr = ''; if (isset($elem[0])) { $url = $elem[0]; } // адрес if (isset($elem[1])) { $name = $elem[1]; } // название if (isset($elem[2]) and $elem[2]) { $attr = ' ' . $elem[2]; } // атрибуты $out_my .= '<li title="' . $name . '"><a href="' . $url . '"' . $attr . '><span>' . $name . '</span></a></li>'; $my_admin_menu_select_option .= '<option value="' . $url . '"' . '>' . $name . '</option>'; } $out_my .= '</ul></li></ul>'; $admin_menu_select_option = $my_admin_menu_select_option . $admin_menu_select_option; $out = $out_my . $out; } return $out; }
function faq_custom_text_callback($matches) { return '<a id="' . mso_slug($matches[1]) . '"></a><h3>' . trim($matches[1]) . '</h3>' . '<div class="faq-text">' . trim($matches[2]) . '<a href="#faq-top" class="to-faq-top">' . t('К списку') . '</a></div>'; }
</copyright> <?php foreach ($pages as $page) { extract($page); ?> <item> <title><![CDATA[<?php echo xml_convert(strip_tags($page_title)); ?> ]]></title> <link><?php echo getinfo('siteurl') . 'page/' . mso_slug($page_slug); ?> </link> <guid><?php echo getinfo('siteurl') . 'page/' . mso_slug($page_slug); ?> </guid> <pubDate><?php echo date('D, d M Y H:i:s ' . $time_zone, strtotime(mso_date_convert('Y-m-d H:i:s', $page_date_publish))); ?> </pubDate> <?php echo mso_page_cat_link($page_categories, ", ", '<category><![CDATA[', ']]></category>' . "\n", false, 'category', false); ?> <description><![CDATA[<?php echo mso_page_content($page_content) . mso_page_comments_link($page_comment_allow, $page_slug, ' ' . tf('Обсудить'), '', '', false); ?> ]]></description> </item> <?php
$form .= '<div class="admin-edit-widgets">'; $form .= '<h2>' . $sidebar['title'] . '</h2>'; foreach ($widgets as $widget) { // удаляем указанные @классы@ $widget = trim(preg_replace('!\\@(.*?)\\@!is', "", $widget)); $widget = str_replace(' ', ' ', $widget); // имя виджета может содержать номер через пробел // проверим это $arr_w = explode(' ', $widget); // в массив if (sizeof($arr_w) > 1) { $widget = trim($arr_w[0]); // первый - функция $num_orig = trim($arr_w[1]); // второй - номер виджета $num = mso_slug($num_orig); $num = str_replace('--', '-', $num); $num_orig = str_replace('_', ' ', $num_orig); // заменим _ на пробел } else { $num = 0; // номер виджета не указан, значит 0 } $func = $widget . '_form'; // функция вывода формы if (function_exists($func)) { $form .= '<div class="admin-edit-widgets-form">'; $d_id = 'd_' . $func . '_' . $num; $a_js = '<a href="#" class="link">'; if ($num) { $form .= '<h3>' . $a_js . $MSO->widgets[$widget] . ' (' . $num_orig . ')</a></h3>';
if (!defined('BASEPATH')) { exit('No direct script access allowed'); } /** * MaxSite CMS * (c) http://max-3000.com/ */ global $MSO; $CI =& get_instance(); $options_key = 'plugin_admin_ip'; if ($post = mso_check_post(array('f_session_id', 'f_submit', 'f_secret_url', 'f_ip'))) { mso_checkreferer(); $options = array(); $options['ip'] = $post['f_ip']; $options['secret'] = mso_slug($post['f_secret_url']); mso_add_option($options_key, $options, 'plugins'); echo '<div class="update">' . t('Обновлено! Обязательно сохраните секретный адрес сейчас!') . '</div>'; } ?> <h1><?php echo t('Admin IP'); ?> </h1> <p class="info"><?php echo t('Вы можете указать IP с которых разрешен доступ в админ-панель. Если пользователь попытается войти в панель управления с другого IP, то ему будет отказано в доступе.'); ?> </p> <p class="info"><?php echo t('На тот случай, если у администратора сменится IP, следует указать секретный адрес (URL), по которому можно очистить список разрешенных IP. Сохраняйте этот секретный адрес в надежном месте. В случае, если вы его забудете у вас не будет другой возможности, кроме как отключить плагин (удалить его файлы) или вручную исправить базу данных.'); ?>
function mso_get_pages($r = array(), &$pag) { global $MSO, $mso_page_current; $CI =& get_instance(); if (!isset($r['limit'])) { $r['limit'] = 7; } else { // проверим входящий лимит - он должен быть числом $r['limit'] = (int) $r['limit']; $r['limit'] = abs($r['limit']); if (!$r['limit']) { $r['limit'] = 7; } // что-то не то, заменяем на дефолт=7 } if (!isset($r['cut'])) { $r['cut'] = tf('Далее'); } // ссылка на [cut] if (!isset($r['xcut'])) { $r['xcut'] = true; } // для тех у кого нет cut, но есть xcut выводить после xcut if (!isset($r['show_cut'])) { $r['show_cut'] = true; } // отображать ссылку «далее» для [cut] ? if (!isset($r['show_xcut'])) { $r['show_xcut'] = true; } // отображать ссылку «далее» для [xcut] ? // приписка к ссылке на страницу полной записи if (!isset($r['a_link_cut'])) { $r['a_link_cut'] = '#cut'; } // удалять ли [cut], если false, то cut не обрабатывается // если false, то $r['cut'] и $r['xcut'] уже не учитываются if (!isset($r['work_cut'])) { $r['work_cut'] = true; } // отдавать все поля из таблиц (только для типов home и page) // если false, то только то, что предопределено if (!isset($r['all_fields'])) { $r['all_fields'] = false; } if (!isset($r['cat_order'])) { $r['cat_order'] = 'category_name'; } // сортировка рубрик if (!isset($r['cat_order_asc'])) { $r['cat_order_asc'] = 'asc'; } // порядок рубрик if (!isset($r['meta_order'])) { $r['meta_order'] = 'meta_value'; } // сортировка meta if (!isset($r['meta_order_asc'])) { $r['meta_order_asc'] = 'asc'; } // порядок meta if (!isset($r['pagination'])) { $r['pagination'] = true; } // использовать пагинацию if (!isset($r['content'])) { $r['content'] = true; } // получать весь текст // если 0, значит все страницы - только для главной // можно указать номера страниц через запятую if (!isset($r['page_id'])) { $r['page_id'] = 0; } // можно указать номера рубрик через запятую if (!isset($r['cat_id'])) { $r['cat_id'] = 0; } // если 0, значит все рубрики - только для главной if (!isset($r['type'])) { $r['type'] = 'blog'; } // если false - то все, иначе blog или static if ($r['page_id']) { $r['type'] = false; } // если указан номер, то тип страницы сбрасываем if (!isset($r['order'])) { $r['order'] = 'page_date_publish'; } // поле сортировки страниц if (!isset($r['order_asc'])) { $r['order_asc'] = 'desc'; } // поле сортировки страниц // если нужно вывести все данные, невзирая на limit, то no_limit=true - пагинация при этом отключается if (!isset($r['no_limit'])) { $r['no_limit'] = false; } if ($r['no_limit']) { $r['pagination'] = false; } // custom_type - аналог is_type - анализ явного указания типа данных if (!isset($r['custom_type'])) { $r['custom_type'] = false; } // кастомная функция - вызывается вместо автоанализа по is_type // эта функция обязательно должна быть подобна _mso_sql_build_home($r, &$pag) и т.п. if (!isset($r['custom_func'])) { $r['custom_func'] = false; } // для функции mso_page_title - передаем тип ссылки для страниц if (!isset($r['link_page_type'])) { $r['link_page_type'] = 'page'; } // для _mso_sql_build_category можно указать массив номеров рубрик // и получить все записи указанных рубрик if (!isset($r['categories'])) { $r['categories'] = array(); } // исключить указанные в массиве записи if (!isset($r['exclude_page_id'])) { $r['exclude_page_id'] = array(); } // произвольный slug - используется там, где вычисляется mso_segment(2) // страница, рубрика, метка, поиск if (!isset($r['slug'])) { $r['slug'] = false; } // если true, то публикуется только те, которые старше текущей даты // если false - то публикуются все // если юзер залогинен, то дата сбрасывается при выводе page if (!isset($r['date_now'])) { $r['date_now'] = true; } // смещение времени в формате ЧЧ:ММ // если нет, то берется из настроек if (!isset($r['time_zone'])) { $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); $r['time_zone'] = $time_zone; } // если указано учитывать время публикации, то выполняем запрос в котором получаем // все записи, которые будущие и которые следует исключить из выборки // сей алгоритм связан с оптимизацией запросов к MySQL и значительным (очень!) ускорением // сложного select без использования NOW() if ($r['date_now']) { $CI->db->select('SQL_BUFFER_RESULT `page_id`', false); $CI->db->where('page_date_publish > ', 'DATE_ADD(NOW(), INTERVAL "' . $r['time_zone'] . '" HOUR_MINUTE)', false); $query = $CI->db->get('page'); if ($query and $query->num_rows() > 0) { $page_id_date_now = $query->result_array(); $r['page_id_date_now'] = array(); foreach ($page_id_date_now as $key => $val) { $r['page_id_date_now'][] = $val['page_id']; } } else { $r['page_id_date_now'] = false; } // нет записей } else { $r['page_id_date_now'] = false; } // не нужно учитывать время // учитывать ли опцию публикация RSS в странице - // если true, то отдаются только те, которые отмечены с этой опцией, false - все if (!isset($r['only_feed'])) { $r['only_feed'] = false; } // стутус страниц - если false, то не учитывается if (!isset($r['page_status'])) { $r['page_status'] = 'publish'; } // можно указать номер автора - получим только его записи if (!isset($r['page_id_autor'])) { $r['page_id_autor'] = false; } // получать ли информацию о рубриках // если false, то возвращает пустые массивы page_categories и page_categories_detail if (!isset($r['get_page_categories'])) { $r['get_page_categories'] = true; } // получать ли информацию о метках и мета страницы // объединены, потому что это один sql-запрос // если false, то возвращает пустые массивы page_tags и page_meta // при этом перестанет работать парсер текста if (!isset($r['get_page_meta_tags'])) { $r['get_page_meta_tags'] = true; } // нужно ли получать данные по количеству комментариев к страницам if (!isset($r['get_page_count_comments'])) { $r['get_page_count_comments'] = true; } // можно указать key и table для получения произвольных выборок мета, например метки // используется только для _mso_sql_build_tag // в качестве meta_value используется $slug if (!isset($r['meta_key'])) { $r['meta_key'] = 'tags'; } if (!isset($r['meta_table'])) { $r['meta_table'] = 'page'; } // сегмент, признак пагинации if (!isset($r['pagination_next_url'])) { $r['pagination_next_url'] = 'next'; } // функция со своим sql, в которой можно добавить свои условия if (!isset($r['function_add_custom_sql'])) { $r['function_add_custom_sql'] = false; } else { if (!function_exists($r['function_add_custom_sql'])) { $r['function_add_custom_sql'] = false; } } // хук, если нужно поменять параметры // $r_restore = $r; $r = mso_hook('mso_get_pages', $r); # для каждого типа страниц строится свой sql-запрос # мы оформляем его в $CI, а здесь только выполняем $CI->db->get(); // если указана кастомная функция, то выполняем r1 if ($r['custom_func'] and function_exists($r['custom_func'])) { $r['custom_func']($r, $pag); } elseif ($r['custom_type']) { $custom_type = $r['custom_type']; if ($custom_type == 'home') { _mso_sql_build_home($r, $pag); } elseif ($custom_type == 'page') { _mso_sql_build_page($r, $pag); } elseif ($custom_type == 'category') { _mso_sql_build_category($r, $pag); } elseif ($custom_type == 'tag') { _mso_sql_build_tag($r, $pag); } elseif ($custom_type == 'archive') { _mso_sql_build_archive($r, $pag); } elseif ($custom_type == 'search') { _mso_sql_build_search($r, $pag); } elseif ($custom_type == 'author') { _mso_sql_build_author($r, $pag); } else { return array(); } } elseif (is_type('home')) { _mso_sql_build_home($r, $pag); } elseif (is_type('page')) { _mso_sql_build_page($r, $pag); } elseif (is_type('category')) { _mso_sql_build_category($r, $pag); } elseif (is_type('tag')) { _mso_sql_build_tag($r, $pag); } elseif (is_type('archive')) { _mso_sql_build_archive($r, $pag); } elseif (is_type('search')) { _mso_sql_build_search($r, $pag); } elseif (is_type('author')) { _mso_sql_build_author($r, $pag); } else { return array(); } // сам запрос и его обработка // $query = $CI->db->get(); // нужно добавить SQL_BUFFER_RESULT // поскольку CodeIgniteryt не позволяет добавлять его явно, придется извращаться $query_sql = str_replace('SELECT ', 'SELECT SQL_BUFFER_RESULT ', $CI->db->_compile_select()); // дурацкое экранирование CodeIgniter - используем свои костыли для запятых в запросе $query_sql = str_replace('_MSO_ZAP_', ',', $query_sql); $query = $CI->db->query($query_sql); $CI->db->_reset_select(); // восстанавливать после запроса??? // $r = mso_hook('mso_get_pages_restore', $r_restore); if ($query and $query->num_rows() > 0) { $pages = $query->result_array(); $MSO->data['pages_is'] = true; // ставим признак, что записи получены if (is_type('page')) { // проверяем статус публикации - если page_status <> publish то смотрим автора и сравниваем с текущим юзером $page_status = $pages[0]['page_status']; // в page - всегда одна запись if ($page_status != 'publish') { if (isset($MSO->data['session']['users_id'])) { // if ( $pages[0]['page_id_autor'] <> $MSO->data['session']['users_id'] ) return array(); if ($pages[0]['page_id_autor'] != $MSO->data['session']['users_id'] && !mso_check_allow('admin_page_edit_other')) { return array(); } else { if ($page_status == 'draft') { $pages[0]['page_title'] .= ' ' . tf('(черновик)'); } // else $pages[0]['page_title'] .= ' (личное)'; } } else { return array(); } // не залогинен } } // массив всех page_id $all_page_id = array(); foreach ($pages as $key => $page) { $all_page_id[] = $page['page_id']; $content = $page['page_content']; $content = mso_hook('content_init', $content); $content = str_replace('<!-- pagebreak -->', '[cut]', $content); // совместимость с TinyMCE $content = str_replace('<!--more-->', '[cut]', $content); // совместимость с Wordpress # если после [cut] пробелы до конца строки, то удалим их $content = preg_replace('|\\[cut\\]\\s*<br|', '[cut]<br', $content); $content = preg_replace('|\\[cut\\](\\ )*<br|', '[cut]<br', $content); $content = preg_replace('|\\[cut\\](\\ )*(\\s)*<br|', '[cut]<br', $content); //$content = mso_hook('content', $content); //$content = mso_hook('content_auto_tag', $content); //$content = mso_hook('content_balance_tags', $content); //$content = mso_hook('content_out', $content); $pages[$key]['page_slug'] = $page['page_slug'] = mso_slug($page['page_slug']); if ($r['work_cut']) { if ($r['xcut']) { // можно использовать [xcut] $content = str_replace('[xcut', '[mso_xcut][cut', $content); } else { $content = str_replace('[xcut', '[cut', $content); } if (preg_match('/\\[cut(.*?)?\\]/', $content, $matches)) { $content = explode($matches[0], $content, 2); $cut = $matches[1]; } else { $content = array($content); $cut = ''; } $output = $content[0]; if (count($content) > 1) { // ссылка на «далее...» if ($r['cut']) { if ($cut) { if (isset($content[1])) { if (strpos($cut, '%wordcount%') !== false) { $cut = str_replace('%wordcount%', mso_wordcount($content[1]), $cut); } } } else { $cut = $r['cut']; } # отображать ссылку? if ($r['show_cut']) { $output .= mso_page_title($page['page_slug'] . $r['a_link_cut'], $cut, '<span class="mso-cut">', '</span>', true, false, $r['link_page_type']); } } else { $output .= '<a id="cut"></a>' . $content[1]; } } if ($r['xcut']) { if (strpos($output, '[mso_xcut]') !== false) { $xcontent = explode('[mso_xcut]', $output); if ($r['cut'] and $cut) { if ($r['show_xcut']) { $cut = mso_page_title($page['page_slug'] . $r['a_link_cut'], $cut, '<span class="mso-cut">', '</span>', true, false, $r['link_page_type']); } else { $cut = ''; } $output = $xcontent[0] . $cut; } else { $output = $xcontent[1]; } } } } else { $output = $content; } // отдаем как есть # хуки на контент $mso_page_current = $page; // глобальная переменная, где хранится текущая обрабатываемая page $output = mso_hook('content_in', $output); $output = mso_hook('content', $output); /* $output = mso_hook('content_auto_tag', $output); $output = mso_hook('content_balance_tags', $output); $output = mso_hook('content_out', $output); $output = mso_hook('content_complete', $output); */ $pages[$key]['page_content'] = $output; $pages[$key]['page_categories'] = array(); $pages[$key]['page_categories_detail'] = array(); $pages[$key]['page_tags'] = array(); $pages[$key]['page_meta'] = array(); } if ($r['get_page_categories']) { // теперь одним запросом получим все рубрики каждой записи $CI->db->select('page_id, category.category_id, category.category_name, category.category_slug, category.category_desc, category.category_id_parent'); $CI->db->where_in('page_id', $all_page_id); $CI->db->order_by('category.' . $r['cat_order'], $r['cat_order_asc']); // сортировка рубрик $CI->db->from('cat2obj'); $CI->db->join('category', 'cat2obj.category_id = category.category_id'); if ($query = $CI->db->get()) { $cat = $query->result_array(); } else { $cat = array(); } // переместим все в массив page_id[] = category_id $page_cat = array(); $page_cat_detail = array(); foreach ($cat as $key => $val) { $page_cat[$val['page_id']][] = $val['category_id']; $page_cat_detail[$val['page_id']][$val['category_id']] = array('category_name' => $val['category_name'], 'category_slug' => $val['category_slug'], 'category_desc' => $val['category_desc'], 'category_id_parent' => $val['category_id_parent'], 'category_id' => $val['category_id']); } } if ($r['get_page_meta_tags']) { // по этому же принципу получаем все метки $CI->db->select('SQL_BUFFER_RESULT `meta_id_obj`, `meta_key`, `meta_value`', false); $CI->db->where(array('meta_table' => 'page')); $CI->db->where_in('meta_id_obj', $all_page_id); $CI->db->order_by($r['meta_order'], $r['meta_order_asc']); // сортировка мета if ($query = $CI->db->get('meta')) { $meta = $query->result_array(); } else { $meta = array(); } // переместим все в массив page_id[] = category_id $page_meta = array(); foreach ($meta as $key => $val) { $page_meta[$val['meta_id_obj']][$val['meta_key']][] = $val['meta_value']; } } // нужно получить колво комментариев к записям if ($r['get_page_count_comments']) { $CI->db->select('SQL_BUFFER_RESULT `comments_page_id`, COUNT(`comments_id`) AS `page_count_comments`', false); $CI->db->where_in('comments_page_id', $all_page_id); $CI->db->where('comments_approved', '1'); $CI->db->group_by('comments_page_id'); $CI->db->from('comments'); $query = $CI->db->get(); $count_comments = $query->result_array(); // переместим все в массив page_count_comments $page_count_comments = array(); foreach ($count_comments as $key => $val) { $page_count_comments[$val['comments_page_id']] = $val['page_count_comments']; } } // получим данные о всех парсерах $parser_all = mso_hook('parser_register', array()); // все зарегистрированные парсеры // добавим в массив pages полученную информацию по меткам и рубрикам foreach ($pages as $key => $val) { // рубрики if ($r['get_page_categories'] and isset($page_cat[$val['page_id']]) and $page_cat[$val['page_id']]) { $pages[$key]['page_categories'] = $page_cat[$val['page_id']]; $pages[$key]['page_categories_detail'] = $page_cat_detail[$val['page_id']]; } // метки отдельно как page_tags if ($r['get_page_meta_tags'] and isset($page_meta[$val['page_id']]['tags']) and $page_meta[$val['page_id']]['tags']) { $pages[$key]['page_tags'] = $page_meta[$val['page_id']]['tags']; } // остальные мета отдельно в page_meta if ($r['get_page_meta_tags'] and isset($page_meta[$val['page_id']]) and $page_meta[$val['page_id']]) { $pages[$key]['page_meta'] = $page_meta[$val['page_id']]; } // колво комментариев if ($r['get_page_count_comments']) { if (isset($page_count_comments[$val['page_id']])) { $pages[$key]['page_count_comments'] = $page_count_comments[$val['page_id']]; } else { $pages[$key]['page_count_comments'] = 0; } // нет комментариев } else { $pages[$key]['page_count_comments'] = 0; } // ставим, что нет комментариев // обработка контента хуками $output = $pages[$key]['page_content']; // обработка парсером if (isset($pages[$key]['page_meta']['parser_content'])) { if ($pages[$key]['page_meta']['parser_content'][0] !== 'none') { $p = $pages[$key]['page_meta']['parser_content'][0]; if (isset($parser_all[$p]['content'])) { $func = $parser_all[$p]['content']; // функция, которую нужно выполнить if (function_exists($func)) { $output = $func($output); } } } } else { // парсер не указан, используем дефолтный // проверим его наличие по функции parser_default_content() // иначе нужно включить плагин if (!function_exists('parser_default_content')) { require_once getinfo('plugins_dir') . 'parser_default/index.php'; } $output = parser_default_content($output); } // pr($output, 1); // старые хуки, больше не используются // $output = mso_hook('content_auto_tag', $output); // $output = mso_hook('content_balance_tags', $output); // $output = mso_hook('content_out', $output); $output = mso_hook('content_complete', $output); $pages[$key]['page_content'] = $output; } } else { $pages = array(); $MSO->data['pages_is'] = false; // ставим признак, что записей нет } return $pages; }
function mso_show_sidebar($sidebar = '1', $block_start = '<div class="[CLASS]mso-widget mso-widget_[NUMW] mso-widget_[SB]_[NUMW] mso-[FN] mso-[FN]_[NUMF]">', $block_end = '</div>', $echo = true) { global $MSO, $page; // чтобы был доступ к параметрам страниц в условиях виджетов static $num_widget = array(); // номер виджета по порядку в одном сайдбаре $widgets = mso_get_option('sidebars-' . $sidebar, 'sidebars', array()); $out = ''; if ($widgets) { foreach ($widgets as $widget) { $usl_res = 1; // предполагаем, что нет условий, то есть всегда true $class = ''; // дополнительный класс виджета // возможно указаны css-классы виджета между @класс1 класс2@ if (preg_match('!\\@(.*?)\\@!is', $widget, $matches)) { $class = trim($matches[1]) . ' '; } // удаляем указанные классы $widget = trim(preg_replace('!\\@(.*?)\\@!is', "", $widget)); // удалим возможные двойные пробелы $widget = str_replace(' ', ' ', $widget); // имя виджета может содержать номер через пробел $arr_w = explode(' ', $widget); // в массив if (sizeof($arr_w) > 1) { $widget = trim($arr_w[0]); // первый - функция $num = trim($arr_w[1]); // второй - номер виджета if (isset($arr_w[2])) { $u = $arr_w; // поскольку у нас разделитель пробел, то нужно до конца все подбить в одну строчку $u[0] = $u[1] = ''; $usl = trim(implode(' ', $u)); // текст условия, is_type('home') or is_type('category') $usl = 'return ( ' . $usl . ' ) ? 1 : 0;'; $usl_res = eval($usl); // выполяем if ($usl_res === false) { $usl_res = 1; } // возможно произошла ошибка } } else { $num = 0; // номер виджета не указан, значит 0 } // номер функции виджета может быть не только числом, но и текстом // если текст, то нужно его преобразовать в slug, чтобы исключить // некоректную замену [NUMF] для стилей $num = mso_slug($num); // двойной - заменим на один - защита id в форме админки $num = str_replace('--', '-', $num); if (function_exists($widget) and $usl_res === 1) { if ($temp = $widget($num)) { if (isset($num_widget[$sidebar]['numw'])) { $numw = ++$num_widget[$sidebar]['numw']; $num_widget[$sidebar]['numw'] = $numw; } else { $numw = $num_widget[$sidebar]['numw'] = 1; } $st = str_replace('[FN]', $widget, $block_start); // название функции виджета $st = str_replace('[NUMF]', $num, $st); // номер функции $st = str_replace('[NUMW]', $numw, $st); // $st = str_replace('[SB]', $sidebar, $st); // номер сайдбара $st = str_replace('[CLASS]', $class, $st); $en = str_replace('[FN]', $widget, $block_end); $en = str_replace('[NUMF]', $num, $en); $en = str_replace('[NUMW]', $numw, $en); $en = str_replace('[SB]', $sidebar, $en); $out .= $st . $temp . $en; } } } if ($echo) { echo $out; } else { return $out; } } }
function mso_edit_page($data) { global $MSO; $CI =& get_instance(); $data = mso_xss_clean_data($data, array('user_login', 'password', 'page_id_autor', 'page_title', 'page_slug', 'page_password', 'page_date_publish', 'page_type_id', 'page_id_parent', 'page_status')); if (isset($data['user_login'])) { $user_login = $data['user_login']; } else { $user_login = $MSO->data['session']['users_login']; } if (isset($data['password'])) { $password = $data['password']; } else { $password = $MSO->data['session']['users_password']; } if (!isset($data['page_id_autor'])) { $data['page_id_autor'] = $MSO->data['session']['users_id']; } # проверка доступа этому пользователю с этим паролем и этим разрешением if (!mso_check_user_password($user_login, $password, 'admin_page_edit')) { return array('result' => 0, 'description' => 'Login/password incorrect'); } # получаем данные пользователя, который отправил запрос $user_data = mso_get_user_data($user_login, $password); $page_id = (int) $data['page_id']; // проверим, чтобы это было число $page_id1 = (int) $page_id; if ((string) $page_id != (string) $page_id1) { $page_id = false; } // ошибочный id if (!$page_id) { return array('result' => 0, 'description' => 'Page ID incorrect'); } // есть ли вообще такая страница? $CI->db->select('page_id'); $CI->db->where(array('page_id' => $page_id)); $query = $CI->db->get('page'); if ($query->num_rows() == 0) { // нет такого return array('result' => 0, 'description' => 'Page ID incorrect'); } $page_title = $data['page_title']; $page_content = $data['page_content']; // короткая ссылка $page_slug = isset($data['page_slug']) ? mso_slug($data['page_slug']) : false; if (!$page_slug) { if ($page_title) { $page_slug = mso_slug($page_title); } else { $page_slug = 'no-title'; } if (!$page_slug) { $page_slug = 'no-title'; } } // $page_slug нужно проверить на существование // если есть, то нужно добавить скажем их кол-во+1 // при этом исключаем саму редактируемую страницу $CI->db->select('page_slug'); $CI->db->where('page_id != ', $page_id); $query = $CI->db->get('page'); // получили все slug if ($query->num_rows() > 0) { $all = array(); // сделаем массив всех слаг foreach ($query->result_array() as $row) { $all[] = $row['page_slug']; } $count = 0; // начальное приращения слага $in = in_array($page_slug, $all); // признак вхождения - while ($in) { $count++; $in = in_array($page_slug . '-' . $count, $all); } if ($count) { $page_slug = $page_slug . '-' . $count; } } $page_password = isset($data['page_password']) ? mso_strip($data['page_password']) : ''; // дата публикации $page_date_publish = isset($data['page_date_publish']) ? $data['page_date_publish'] : false; # дата последней модификации страницы $page_last_modified = date('Y-m-d H:i:s'); $page_type_id = isset($data['page_type_id']) ? $data['page_type_id'] : '1'; $page_id_parent = isset($data['page_id_parent']) ? $data['page_id_parent'] : '0'; $page_status = isset($data['page_status']) ? $data['page_status'] : 'publish'; if ($page_status != 'publish' and $page_status != 'draft' and $page_status != 'private') { $page_status = 'publish'; } // если стоит разрешение admin_page_publish, то статус не меняем // иначе ставим только draft if (!mso_check_allow('admin_page_publish', $user_data['users_id'])) { $page_status = 'draft'; } $page_comment_allow = isset($data['page_comment_allow']) ? (int) $data['page_comment_allow'] : '1'; $page_ping_allow = isset($data['page_ping_allow']) ? (int) $data['page_ping_allow'] : '1'; $page_feed_allow = isset($data['page_feed_allow']) ? (int) $data['page_feed_allow'] : '1'; $page_menu_order = isset($data['page_menu_order']) ? (int) $data['page_menu_order'] : 0; $page_id_autor = isset($data['page_id_autor']) ? (int) $data['page_id_autor'] : 0; // нужно проверить вообще есть ли такой юзер $page_id_autor $CI->db->select('users_id'); $CI->db->from('users'); $CI->db->where(array('users_id' => $page_id_autor)); $query = $CI->db->get(); if (!$query->num_rows()) { // нет $page_id_autor = 0; } if ($page_id_autor != $user_data['users_id']) { if (!mso_check_allow('edit_page_author', $user_data['users_id'], false)) { $page_id_autor = $user_data['users_id']; } } $ins_data = array('page_type_id' => $page_type_id, 'page_id_parent' => $page_id_parent, 'page_id_autor' => $page_id_autor, 'page_title' => $page_title, 'page_content' => $page_content, 'page_status' => $page_status, 'page_slug' => $page_slug, 'page_password' => $page_password, 'page_comment_allow' => $page_comment_allow, 'page_ping_allow' => $page_ping_allow, 'page_feed_allow' => $page_feed_allow, 'page_last_modified' => $page_last_modified, 'page_menu_order' => $page_menu_order); if ($page_date_publish) { $ins_data['page_date_publish'] = $page_date_publish; } $CI->db->where(array('page_id' => $page_id)); $res = $CI->db->update('page', $ins_data) ? '1' : '0'; # $CI->db->cache_delete_all(); if ($res) { $id = $page_id; // добавим теперь рубрики // вначале удалим все записи из рубрик с этим page_id $CI->db->where(array('page_id' => $page_id, 'links_id' => '0')); // чтобы линки не грохнуть $CI->db->delete('cat2obj'); // рубрики указаны в виде номеров через запятую $page_id_cat = isset($data['page_id_cat']) ? $data['page_id_cat'] : ''; $page_id_cat = mso_explode($page_id_cat); // в массив foreach ($page_id_cat as $key => $val) { $ins_data = array('page_id' => $id, 'category_id' => $val); $CI->db->insert('cat2obj', $ins_data); # $CI->db->cache_delete_all(); } // $page_tags = метка // метки - это мета данные // дефолтные данные $def_data = array('meta_key' => 'tags', 'meta_id_obj' => $id, 'meta_table' => 'page'); // вначале грохнем старые, потом добавим новые $CI->db->where($def_data); $CI->db->delete('meta'); // получим существующие метки $CI->db->select('meta_id'); $CI->db->where($def_data); $query = $CI->db->get('meta'); if (!$query->num_rows()) { // значит инсерт $page_tags = isset($data['page_tags']) ? $data['page_tags'] : ''; $tags = mso_explode($page_tags, false, false); // в массив - не только числа foreach ($tags as $key => $val) { $ins_data = $def_data; $ins_data['meta_value'] = $val; $CI->db->insert('meta', $ins_data); # $CI->db->cache_delete_all(); } } // опции - мета require_once getinfo('common_dir') . 'meta.php'; $page_meta_options = isset($data['page_meta_options']) ? $data['page_meta_options'] : ''; // title##VALUE##титул##METAFIELD##description##VALUE##описание##METAFIELD##keywords##VALUE##ключи##METAFIELD## $page_meta_options = explode('##METAFIELD##', $page_meta_options); // вначале удалим все мета этой записи //$where_in = array(); // здесь meta_key //foreach ($page_meta_options as $key=>$val) //{ // if (trim($val)) // { // $meta_temp = explode('##VALUE##', $val); // $where_in[] = trim($meta_temp[0]); // } //} // вначале грохнем старые, потом добавим новые //$CI->db->where( array('meta_id_obj' => $id, 'meta_table' => 'page') ); //$CI->db->where_in('meta_key', $where_in ); //$CI->db->delete('meta'); // теперь тоже самое, только добавляем через insert foreach ($page_meta_options as $key => $val) { if (trim($val)) { $meta_temp = explode('##VALUE##', $val); $meta_key = trim($meta_temp[0]); $meta_value = trim($meta_temp[1]); mso_add_meta($meta_key, $id, 'page', $meta_value); //$CI->db->insert('meta', array('meta_key'=>$meta_key, 'meta_value'=>$meta_value, // 'meta_table' => 'page', 'meta_id_obj' => $id) ); } } // результат возвращается в виде массива $res = array($id, $page_slug, $page_status, $page_password, $page_date_publish); $response = array('result' => $res, 'description' => 'Updating page'); mso_flush_cache(); // сбросим кэш } else { $response = array('result' => 0, 'description' => 'Error inserting page'); } if ($response['result']) { mso_hook('edit_page', $response['result']); mso_hook('edit_page_' . $page_status); } return $response; }
$current_dir .= '/'; } $path = getinfo('uploads_dir') . $current_dir; if (!is_dir($path)) { $path = getinfo('uploads_dir'); $current_dir = $current_dir_h2 = ''; } else { if ($current_dir_h2) { $current_dir_h2 = '/' . $current_dir_h2; } } //echo '<h2>' . t('Текущий каталог:') . ' uploads' . $current_dir_h2 . '</h2>'; # новый каталог - создаем до того, как отобразить навигацию if ($post = mso_check_post(array('f_session3_id', 'f_cat_name', 'f_newcat_submit'))) { mso_checkreferer(); $f_cat_name = mso_slug($post['f_cat_name']); if (!$f_cat_name) { echo '<div class="error">' . t('Нужно ввести имя каталога') . '</div>'; } else { $new_dir = getinfo('uploads_dir') . $f_cat_name; if (is_dir($new_dir)) { echo '<div class="error">' . t('Такой каталог уже есть!') . '</div>'; } else { @mkdir($new_dir, 0777); // нет каталога, пробуем создать @mkdir($new_dir . '/_mso_i', 0777); // нет каталога, пробуем создать @mkdir($new_dir . '/mini', 0777); // нет каталога, пробуем создать echo '<div class="update">' . sprintf(t('Каталог <strong>%s</strong> создан!'), $f_cat_name) . '</div>'; }
function tabs_widget_custom($options = array(), $num = 1) { $out = ''; if (!isset($options['header'])) { $options['header'] = ''; } if (!isset($options['tabs'])) { $options['tabs'] = ''; } if (!isset($options['type_func'])) { $options['type_func'] = 'widget'; } $ar = explode("\n", trim($options['tabs'])); // все табы в массив $tabs = array(); // наши закладки if ($ar) { foreach ($ar as $key => $val) { $t = explode('|', $val); if (isset($t[0]) and isset($t[1])) { $tabs[$key]['title'] = trim($t[0]); $tabs[$key]['ushka'] = trim($t[1]); } } } if ($tabs) { $out .= NR . '<div class="mso-tabs"><ul class="mso-tabs-nav">' . NR; $current = ' mso-tabs-current'; foreach ($tabs as $key => $tab) { $out .= '<li class="mso-tabs-elem' . $current . '"><span>' . $tab['title'] . '</span></li>' . NR; $current = ''; } $out .= '</ul>' . NR; $visible = ' mso-tabs-visible'; foreach ($tabs as $key => $tab) { if ($options['type_func'] == 'widget') { $func = $tab['ushka']; // category_widget 20 $nm = 0; // разделим и определим номер виджета $arr_w = explode(' ', $func); // в массив if (sizeof($arr_w) > 1) { $func = trim($arr_w[0]); // первый - функция $nm = trim($arr_w[1]); // второй - номер виджета } // замены номера виджета из mso_show_sidebar() $nm = mso_slug($nm); $nm = str_replace('--', '-', $nm); if (function_exists($func)) { $func = $func($nm); } else { $func = 'no-func'; } } else { if (function_exists('ushka')) { $func = ushka($tab['ushka']); } else { $func = ''; } } $out .= NR . '<div class="mso-tabs-box' . $visible . '">' . $func . '</div>' . NR; $visible = ''; } $out .= '</div><!-- div class="mso-tabs -->' . NR; } if ($out and $options['header']) { $out = $options['header'] . '<div class="mso-tabs-widget-content">' . $out . '</div><!-- /div.mso-tabs-widget-content -->'; } else { $out = '<div class="mso-tabs-widget-content">' . $out . '</div><!-- div.mso-tabs-widget-content -->'; } return $out; }
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 '<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Авторизация</title> </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 '<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Авторизация</title> </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('Не задан ответный пароль')); } if (!isset($options['unique'])) { $options['unique'] = 0; } // делать уникальный пароль // смотрятся входные 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); $pas = $data_siteurl; // делать пароль уникальным if ($options['unique']) { //pr($options['password']); // указанный пароль // pr($data_siteurl); // для какого сайта $pas = mb_strtolower($pas); $pas = convert_uuencode(mso_md5($options['password'] . $pas)); $pas = mb_strtolower($pas); $pas = mso_slug($pas); $pas = substr($pas, 1, 20); // _pr($pas); } // шифруем на основе двух ключей $my_email_pass = $CI->encrypt->encode($options['email'] . '##' . $pas, $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 '<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Авторизация</title> </head><body> <form method="post" action="' . $data_siteurl . 'maxsite-auth-reply"> <input type="hidden" name="data" value="' . base64_encode($data) . '"> <button type="submit">' . tf('Подтвердить авторизацию для') . ' ' . $data_siteurl . '</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; } }