Example #1
0
function mod_example()
{
    global $AVE_DB, $AVE_Template;
    $tpl_dir = BASE_DIR . '/modules/example/templates/';
    // Указываем путь до шаблона
    $AVE_Template->caching = true;
    $AVE_Template->cache_lifetime = 86400;
    // Время жизни кэша (1 день)
    //	$AVE_Template->cache_dir = BASE_DIR . '/cache/example'; // Папка для создания кэша
    // Если нету в кэше, то выполняем запрос
    if (!$AVE_Template->is_cached('example.tpl')) {
        // Проверяем, есть ли папка для кэша, если нет (первый раз) — создаем
        if (!is_file($AVE_Template->cache_dir)) {
            $oldumask = umask(0);
            @mkdir($AVE_Template->cache_dir, 0777);
            umask($oldumask);
        }
        $example = array();
        // Запрос трех последних документов (ссылка и название) из рубрики с ID 2 и с сортировкой ID по убыванию
        $sql = $AVE_DB->Query("\r\n\t\t\tSELECT\r\n\t\t\t\tId,\r\n\t\t\t\tdocument_title,\r\n\t\t\t\tdocument_alias\r\n\t\t\tFROM " . PREFIX . "_documents\r\n\t\t\tWHERE Id != 1\r\n\t\t\tAND Id != '" . PAGE_NOT_FOUND_ID . "'\r\n\t\t\tAND rubric_id = 2\r\n\t\t\tAND document_deleted != 1\r\n\t\t\tAND document_status != 0\r\n\t\t\tORDER BY Id DESC\r\n\t\t");
        while ($row = $sql->FetchRow()) {
            $row->document_alias = rewrite_link('index.php?id=' . $row->Id . '&doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
            array_push($example, $row);
        }
        // Закрываем соединение
        $sql->Close();
        // Назначаем переменную example для использования в шаблоне
        $AVE_Template->assign('example', $example);
    }
    // Выводим шаблон example.tpl
    $AVE_Template->display($tpl_dir . 'example.tpl');
    $AVE_Template->caching = false;
}
Example #2
0
/**
 * Функция обработки тега модуля
 *
 */
function mod_moredoc()
{
    global $AVE_Core, $AVE_DB, $AVE_Template;
    require_once BASE_DIR . '/functions/func.modulglobals.php';
    set_modul_globals('moredoc');
    $AVE_Template->caching = true;
    // Включаем кеширование
    $AVE_Template->cache_lifetime = 60 * 60 * 24;
    // Время жизни кеша 1 день в секундах
    //	$AVE_Template->cache_dir .= '/moredoc';   // Папка для кеша модуля
    $tpl_dir = BASE_DIR . '/modules/moredoc/templates/';
    // Указываем путь к шаблону модуля
    // Если нету в кеше, то начинаем обрабатывать
    if (!$AVE_Template->is_cached($tpl_dir . 'moredoc.tpl', $AVE_Core->curentdoc->Id)) {
        $limit = 5;
        // Количество связных документов
        $flagrubric = 1;
        // Учитывать или нет рубрику документа (0 - нет, 1 - да)
        $moredoc = array();
        // Проверяем, есть ли папка для кеша, если нет (первый раз) — создаем
        if (!is_dir($AVE_Template->cache_dir)) {
            $oldumask = umask(0);
            @mkdir($AVE_Template->cache_dir, 0777);
            umask($oldumask);
        }
        // Получаем ключевые слова, рубрику, извлекаем первое ключевое слово
        $row = $AVE_DB->Query("\r\n\t\t\tSELECT\r\n\t\t\t\trubric_id,\r\n\t\t\t\tdocument_meta_keywords\r\n\t\t\tFROM " . PREFIX . "_documents\r\n\t\t\tWHERE Id = '" . $AVE_Core->curentdoc->Id . "'\r\n\t\t\tLIMIT 1\r\n\t\t")->FetchRow();
        $keywords = explode(',', $row->document_meta_keywords);
        $keywords = trim($keywords[0]);
        if ($keywords != '') {
            $inrubric = $flagrubric ? "AND rubric_id = '" . $row->rubric_id . "'" : '';
            $doctime = get_settings('use_doctime') ? "AND document_published <= " . time() . " AND (document_expire = 0 OR document_expire >= " . time() . ")" : '';
            // Ищем документы где встречается такое-же слово
            $sql = $AVE_DB->Query("\r\n\t\t\t\tSELECT\r\n\t\t\t\t\tId,\r\n\t\t\t\t\tdocument_expire,\r\n\t\t\t\t\tdocument_title,\r\n\t\t\t\t\tdocument_alias,\r\n\t\t\t\t\tdocument_meta_description\r\n\t\t\t\tFROM " . PREFIX . "_documents\r\n\t\t\t\tWHERE document_meta_keywords LIKE '" . $keywords . "%'\r\n\t\t\t\tAND Id != 1\r\n\t\t\t\tAND Id != '" . PAGE_NOT_FOUND_ID . "'\r\n\t\t\t\tAND Id != '" . $AVE_Core->curentdoc->Id . "'\r\n\t\t\t\tAND document_status != '0'\r\n\t\t\t\tAND document_deleted != '1'\r\n\t\t\t\t" . $inrubric . "\r\n\t\t\t\t" . $doctime . "\r\n\t\t\t\tORDER BY document_count_view DESC\r\n\t\t\t\tLIMIT " . $limit);
            while ($row = $sql->FetchRow()) {
                if ($doctime != '' && time() + $AVE_Template->cache_lifetime > $row->document_expire) {
                    // Изменяем время жизни кеша так что-бы оно не превышало
                    // время окончания публикации попавших в выборку документов
                    $AVE_Template->cache_lifetime = $row->document_expire - time();
                }
                $row->document_link = rewrite_link('index.php?id=' . $row->Id . '&amp;doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
                array_push($moredoc, $row);
            }
            // Закрываем соединение
            $sql->Close();
        }
        // Передаём переменную moredoc в шаблон
        $AVE_Template->assign('moredoc', $moredoc);
    }
    // Выводим шаблон moredoc.tpl
    $AVE_Template->display($tpl_dir . 'moredoc.tpl', $AVE_Core->curentdoc->Id);
    $AVE_Template->caching = false;
    // Отключаем кеширование
}
Example #3
0
 function replaceWild($text)
 {
     /*
     		$text = str_replace('ь', 'ue', $text);
     		$text = str_replace('Ь', 'Ue', $text);
     		$text = str_replace('ц', 'oe', $text);
     		$text = str_replace('Ц', 'Oe', $text);
     		$text = str_replace('д', 'ae', $text);
     		$text = str_replace('Д', 'Ae', $text);
     		$text = str_replace(array('&', '&amp;'), 'and', $text);
     		$text = preg_replace("/[^+_A-Za-zА-Яа-яЁёЇЄІїєі0-9]/", "_", $text);
     */
     $text = prepare_url($text);
     return $text;
 }
Example #4
0
/**
 * Постраничная навигация документа
 *
 * @param string $text	текст многострочной части документа
 * @return string
 */
function document_pagination($text)
{
    global $AVE_Core;
    // IE8                    <div style="page-break-after: always"><span style="display: none">&nbsp;</span></div>
    // Chrome                 <div style="page-break-after: always; "><span style="DISPLAY:none">&nbsp;</span></div>
    // FF                     <div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>
    $pages = preg_split('#<div style="page-break-after:[; ]*always[; ]*"><span style="display:[ ]*none[;]*">&nbsp;</span></div>#i', $text);
    $total_page = @sizeof($pages);
    if ($total_page > 1) {
        $text = @$pages[get_current_page('artpage') - 1];
        $page_nav = ' <a class="pnav" href="index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias) . '&amp;artpage={s}' . '">{t}</a> ';
        $page_nav = get_pagination($total_page, 'artpage', $page_nav, get_settings('navi_box'));
        $text .= rewrite_link($page_nav);
    }
    return $text;
}
Example #5
0
 /**
  * Print the specified user's avatar.
  *
  * This method can be used in two ways:
  * <pre>
  * // Option 1:
  * $userpic = new moodle_user_picture();
  * // Set properties of $userpic
  * $OUTPUT->user_picture($userpic);
  *
  * // Option 2: (shortcut for simple cases)
  * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
  * $OUTPUT->user_picture($user, $COURSE->id);
  * </pre>
  *
  * @param object $userpic Object with at least fields id, picture, imagealt, firstname, lastname
  *     If any of these are missing, or if a userid is passed, the database is queried. Avoid this
  *     if at all possible, particularly for reports. It is very bad for performance.
  *     A moodle_user_picture object is a better parameter.
  * @param int $courseid courseid Used when constructing the link to the user's profile. Required if $userpic
  *     is not a moodle_user_picture object
  * @return string HTML fragment
  */
 public function user_picture($userpic, $courseid = null)
 {
     // Instantiate a moodle_user_picture object if $user is not already one
     if (!$userpic instanceof moodle_user_picture) {
         if (empty($courseid)) {
             throw new coding_exception('Called $OUTPUT->user_picture with a $user object but no $courseid.');
         }
         $user = $userpic;
         $userpic = new moodle_user_picture();
         $userpic->user = $user;
         $userpic->courseid = $courseid;
     } else {
         $userpic = clone $userpic;
     }
     $userpic->prepare();
     $output = $this->image($userpic->image);
     if (!empty($userpic->url)) {
         $actions = $userpic->get_actions();
         if ($userpic->popup && !empty($actions)) {
             $link = new html_link();
             $link->url = $userpic->url;
             $link->text = fullname($userpic->user);
             $link->title = fullname($userpic->user);
             foreach ($actions as $action) {
                 $link->add_action($action);
             }
             $output = $this->link_to_popup($link, $userpic->image);
         } else {
             $output = $this->link(prepare_url($userpic->url), $output);
         }
     }
     return $output;
 }
Example #6
0
function printQuickfinder(&$nav_items, &$quickfinder = '', $parent = '0')
{
    foreach ($nav_items[$parent] as $row) {
        if (strpos($row['navi_item_link'], 'module=') === false && start_with('index.php?', $row['navi_item_link'])) {
            $row['navi_item_link'] .= '&amp;doc=' . (empty($row['document_alias']) ? prepare_url($row['title']) : $row['document_alias']);
        }
        if (start_with('www.', $row['navi_item_link'])) {
            $row['navi_item_link'] = str_replace('www.', 'http://www.', $row['navi_item_link']);
        }
        $row['navi_item_link'] = rewrite_link($row['navi_item_link']);
        if (!start_with('javascript:', $row['navi_item_link'])) {
            if ($row['navi_item_target'] == '_blank') {
                $row['navi_item_link'] = "javascript:window.open('" . $row['navi_item_link'] . "', '', '')";
            } else {
                $row['navi_item_link'] = "window.location.href = '" . $row['navi_item_link'] . "'";
            }
        }
        $quickfinder .= '<option class="level_' . $row['navi_item_level'] . '" value="' . $row['navi_item_link'] . '"' . ($row['active'] == 1 ? ' selected="selected"' : '') . '>' . pretty_chars($row['title']) . '</option>';
        if (isset($nav_items[$row['Id']])) {
            printQuickfinder($nav_items, $quickfinder, $row['Id']);
        }
    }
}
Example #7
0
 /**
  * Метод, предназначенный для формирования URL
  *
  */
 function documentAliasCreate()
 {
     $alias = empty($_REQUEST['alias']) ? '' : prepare_url($_REQUEST['alias']);
     $prefix = empty($_REQUEST['prefix']) ? '' : prepare_url($_REQUEST['prefix']);
     $title = empty($_REQUEST['title']) ? '' : $_REQUEST['title'];
     $title = URL_YANDEX == true ? y_translate($title) : prepare_url($title);
     if ($alias != $title && $alias != trim($prefix . '/' . $title, '/')) {
         $alias = trim($alias . '/' . $title, '/');
     }
     return $alias;
 }
Example #8
0
/**
 * Рекурсивная функция для формирования меню навигации
 *
 * @param object	$navi_menu меню (шаблоны, параметры)
 * @param array		$navi_items (пункты по родителям)
 * @param array		$navi_active_way ("активный путь")
 * @param array		$navi_item_tpl (шаблоны пунктов)
 * @param int		$parent (исследуемый родитель, изначально 0 - верхний уровень)
 * @return string	$navi - готовый код навигации
 */
function printNavi($navi_menu, $navi_items, $navi_active_way, $navi_item_tpl, $parent = 0)
{
    // выясняем уровень
    $navi_item_level = $navi_items[$parent][0]['navi_item_level'];
    // собираем каждый пункт в данном родителе -> в переменной $item
    foreach ($navi_items[$parent] as $row) {
        // Проверяем пункт меню на принадлежность к "активному пути" и выбираем шаблон
        $item = in_array($row['Id'], $navi_active_way) ? $navi_item_tpl[$navi_item_level]['active'] : $navi_item_tpl[$navi_item_level]['inactive'];
        ################### ПАРСИМ ТЕГИ ###################
        // id
        @($item = str_replace('[tag:linkid]', $row['Id'], $item));
        // название
        @($item = str_replace('[tag:linkname]', $row['title'], $item));
        // ссылка
        if (strpos($row['navi_item_link'], 'module=') === false && start_with('index.php?', $row['navi_item_link'])) {
            $item = str_replace('[tag:link]', $row['navi_item_link'] . "&amp;doc=" . (!$row['document_alias'] ? prepare_url($row['title']) : $row['document_alias']), $item);
            $item = str_ireplace('"//"', '"/"', str_ireplace('///', '/', rewrite_link($item)));
        } else {
            $item = str_replace('[tag:link]', $row['navi_item_link'], $item);
            if (start_with('www.', $row['navi_item_link'])) {
                $item = str_replace('www.', 'http://www.', $item);
            }
        }
        // target
        $item = str_replace('[tag:target]', empty($row['navi_item_target']) ? '_self' : $row['navi_item_target'], $item);
        // описание
        @($item = str_replace('[tag:desc]', stripslashes($row['navi_item_desc']), $item));
        // изображение
        @($item = str_replace('[tag:img]', stripslashes($row['navi_item_Img']), $item));
        @($img = explode(".", $row['navi_item_Img']));
        @($row['Img_act'] = $img[0] . "_act." . $img[1]);
        @($item = str_replace('[tag:img_act]', stripslashes($row['Img_act']), $item));
        @($item = str_replace('[tag:img_id]', stripslashes($row['navi_item_Img_id']), $item));
        ################### /ПАРСИМ ТЕГИ ##################
        // Определяем тег для вставки следующего уровня
        switch ($navi_item_level) {
            case 1:
                $tag = '[tag:level:2]';
                break;
            case 2:
                $tag = '[tag:level:3]';
        }
        // Если есть подуровень, то заново запускаем для него функцию и вставляем вместо тега
        if (!empty($navi_items[$row['Id']])) {
            $item_sublevel = printNavi($navi_menu, $navi_items, $navi_active_way, $navi_item_tpl, $row['Id']);
            $item = @str_replace($tag, $item_sublevel, $item);
        } else {
            $item = @str_replace($tag, '', $item);
        }
        // Подставляем в переменную навигации готовый пункт
        if (empty($navi)) {
            $navi = '';
        }
        $navi .= $item;
    }
    // Вставляем все пункты уровня в шаблон уровня
    switch ($navi_item_level) {
        case 1:
            $navi = str_replace("[tag:content]", $navi, $navi_menu->navi_level1begin);
            break;
        case 2:
            $navi = str_replace("[tag:content]", $navi, $navi_menu->navi_level2begin);
            break;
        case 3:
            $navi = str_replace("[tag:content]", $navi, $navi_menu->navi_level3begin);
            break;
    }
    // Возвращаем сформированный уровень
    return $navi;
}
// and we haven't just asked it, ask it now.
if (!is_null($transition->confirmation_question) && $confirmed != 'yes') {
    echo "<p><b>" . _("Project ID") . ":</b> {$projectid}<br>\n";
    echo "<b>" . _("Title") . ":</b> {$project->nameofwork}<br>\n";
    echo "<b>" . _("Author") . ":</b> {$project->authorsname}</p>\n";
    echo $transition->confirmation_question;
    echo "<br>\n        <form action='changestate.php' method='POST'>\n        <input type='hidden' name='projectid'  value='{$projectid}'>\n        <input type='hidden' name='curr_state' value='{$curr_state}'>\n        <input type='hidden' name='next_state' value='{$next_state}'>\n        <input type='hidden' name='confirmed'  value='yes'>\n        <input type='hidden' name='return_uri' value='{$return_uri}'>" . sprintf(_("If so, %1\$s, otherwise go back to <a href='%2\$s'>where you were</a>"), "<input type='submit' value='" . attr_safe(_("confirm transition change")) . "'>", $return_uri) . "</form>";
    exit;
}
// At this point, we know that either there's no question associated
// with the transition, or there is and it has been answered yes.
if (!empty($transition->detour)) {
    // Detour (to collect data).
    $title = _("Transferring...");
    $body = "";
    $refresh_url = prepare_url($transition->detour);
    metarefresh(2, $refresh_url, $title, $body);
    exit;
}
$extras = array();
// -------------------------------------------------------------------------
$error_msg = $transition->do_state_change($project, $pguser, $extras);
if ($error_msg == '') {
    $title = _("Action Successful");
    $body = sprintf(_("Your request ('%s') was successful."), $transition->action_name);
} else {
    fatal_error(sprintf(_("Something went wrong, and your request ('%s') has probably not been carried out."), $transition->action_name) . "\n" . _("Error") . ":" . "\n" . $error_msg);
}
// Return the user to the screen they were at
// when they requested the state change.
$refresh_url = $return_uri;
Example #10
0
 /**
  * Метод, предназначенный для вывода контактной формы в публичной части сайта
  *
  * @param string $tpl_dir путь к папке с шаблонами
  * @param string $lang_file путь к языковому файлу
  * @param int $contact_form_id идентификатор формы
  * @param int $spam_protect использовать защитный код 1
  * @param int $max_upload максимальный размер прикреплённого файла
  * @param int $fetch вывод в браузер 1
  * @return string контактная форма
  */
 function contactFormShow($tpl_dir, $lang_file, $contact_form_id, $spam_protect = null, $max_upload = null, $fetch = '0')
 {
     global $AVE_Core, $AVE_DB, $AVE_Template;
     $contact_form_id = preg_replace('/\\D/', '', $contact_form_id);
     $AVE_Template->config_load($lang_file);
     // Получаем всю информацию о данной форме по ее идентификатору
     $row = $AVE_DB->Query("\r\n\t\t\tSELECT *\r\n\t\t\tFROM " . PREFIX . "_modul_contacts\r\n\t\t\tWHERE Id = '" . $contact_form_id . "'\r\n\t\t")->FetchRow();
     // Определяем группы, которым разрешен доступ к данной контактной форме
     $allowed_groups = array();
     if (isset($row->contact_form_allow_group)) {
         $allowed_groups = explode(',', $row->contact_form_allow_group);
     }
     // Если группа пользователя не входит в разрешенный список групп,
     // фиксируем ошибку и выводим сообщение.
     if (!in_array($_SESSION['user_group'], $allowed_groups)) {
         $AVE_Template->assign('no_access', 1);
         if (isset($row->contact_form_message_noaccess)) {
             $AVE_Template->assign('contact_form_message_noaccess', $row->contact_form_message_noaccess);
         }
     } else {
         // Определяем ряд переменных для использования в шаблоне
         $AVE_Template->assign('contact_form_id', $contact_form_id);
         $AVE_Template->assign('im', $spam_protect === null ? $row->contact_form_antispam : $spam_protect);
         $AVE_Template->assign('maxupload', $max_upload === null ? $row->contact_form_max_upload : $max_upload);
         $AVE_Template->assign('send_copy', $row->contact_form_send_copy);
         // Формируем список получателей данного сообщения (если их несколько)
         $recievers = array();
         if ($row->contact_form_reciever_multi != '') {
             $e_recievers = explode(';', $row->contact_form_reciever_multi);
             foreach ($e_recievers as $reciever) {
                 $e_reciever = explode(',', $reciever);
                 array_push($recievers, htmlspecialchars($e_reciever[0], ENT_QUOTES));
             }
         }
         $AVE_Template->assign('recievers', $recievers);
         // Если тема сообщения не указана, тогда используем название темы по умолчанию
         if ($row->contact_form_subject_show == '0' && $row->contact_form_subject_default != '') {
             $AVE_Template->assign('default_subject', $row->contact_form_subject_default);
         }
         // Выполняем запрос к БД на получение списка всех полей формы
         $fields = array();
         $sql = $AVE_DB->Query("\r\n\t\t\t    SELECT *\r\n\t\t\t    FROM " . PREFIX . "_modul_contact_fields\r\n\t\t\t    WHERE contact_field_status = '1'\r\n\t\t\t    AND contact_form_id = '" . $contact_form_id . "'\r\n\t\t\t    ORDER BY contact_field_position ASC\r\n\t\t    ");
         while ($row = $sql->FetchRow()) {
             // Определяем тип поля и формируем регулярное выражение
             // для проверки введённых символов и их количества
             switch ($row->contact_field_datatype) {
                 // Любые символы
                 case 'anysymbol':
                     $row->field_pattern = $row->contact_field_max_chars != '' ? '^([\\s\\S]{' . $row->contact_field_max_chars . '})' . ($row->contact_field_required != 1 ? '?$' : '{1}$') : '';
                     break;
                     // Только целые числа
                 // Только целые числа
                 case 'onlydecimal':
                     $row->field_pattern = $row->contact_field_max_chars != '' ? '^(\\d{' . $row->contact_field_max_chars . '})' . ($row->contact_field_required != 1 ? '?$' : '{1}$') : '';
                     break;
                     // Только буквы
                 // Только буквы
                 case 'onlychars':
                     $row->field_pattern = $row->contact_field_max_chars != '' ? '^(\\D{' . $row->contact_field_max_chars . '})' . ($row->contact_field_required != 1 ? '?$' : '{1}$') : '';
                     break;
                     // По умолчанию любые символы
                 // По умолчанию любые символы
                 default:
                     $row->field_pattern = $row->contact_field_max_chars != '' ? '^([\\s\\S]{' . $row->contact_field_max_chars . '})' . ($row->contact_field_required != 1 ? '?$' : '{1}$') : '';
                     break;
             }
             // Если тип поля "Выпадающий список", тогда получем все его элементы
             if ($row->contact_field_type == 'dropdown' && $row->contact_field_default != '') {
                 $value = explode(',', $row->contact_field_default);
                 $row->contact_field_default = $value;
             }
             // В имени поля заменяем пробелы на подчерки, и формируем массив данных полей
             $field_title_ = str_replace(' ', '_', $row->contact_field_title);
             $row->value = isset($_REQUEST[$field_title_]) ? $_REQUEST[$field_title_] : '';
             array_push($fields, $row);
         }
         // Перердаем в шаблон массив с данными полей и формируем ссылку для редиректа после отправки
         $AVE_Template->assign('fields', $fields);
         $action = rewrite_link('index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias));
         $AVE_Template->assign('contact_action', $action);
     }
     // Возвращаем сформированную контактную форму
     if ($fetch == 1) {
         return $AVE_Template->fetch($tpl_dir . 'form.tpl');
     }
     // Отображаем сформированную контактную форму
     if (file_exists($tpl_dir . 'form-' . $contact_form_id . '.tpl')) {
         $AVE_Template->display($tpl_dir . 'form-' . $contact_form_id . '.tpl');
     } else {
         $AVE_Template->display($tpl_dir . 'form.tpl');
     }
 }
Example #11
0
function url_param($parameter, $request = true, $name = null)
{
    $result = '';
    if (!is_array($parameter)) {
        if (!isset($name)) {
            if (!$request) {
                fatal_error('not request variable require url name [url_param]');
            }
            $name = $parameter;
        }
    }
    if ($request) {
        $var =& $_REQUEST[$parameter];
    } else {
        $var =& $parameter;
    }
    if (isset($var)) {
        $result = prepare_url($var, $name);
    }
    return $result;
}
Example #12
0
 /**
  * Метод, предназначенный для управления пунктами меню навигации в Панели управления
  *
  * @param int $id идентификатор меню навигации
  */
 function navigationItemEdit($nav_id)
 {
     global $AVE_DB;
     $nav_id = (int) $nav_id;
     // Циклически обрабатываем все параметры, пришедшие методом POST при сохранении изменений
     foreach ($_POST['title'] as $id => $title) {
         // Если название пункта меню не пустое
         if (!empty($title)) {
             $id = (int) $id;
             $_POST['navi_item_link'][$id] = strpos($_POST['navi_item_link'][$id], 'javascript') !== false ? str_replace(array(' ', '%'), '-', $_POST['navi_item_link'][$id]) : $_POST['navi_item_link'][$id];
             // Определяем флаг статуса пункта меню (активен/неактивен)
             $navi_item_status = empty($_POST['navi_item_status'][$id]) || empty($_POST['navi_item_link'][$id]) ? 0 : 1;
             $link_url = '';
             $matches = array();
             // Если ссылка оформлена как index.php?id=XX, где XX - число (id документа)
             preg_match('/^index\\.php\\?id=(\\d+)$/', trim($_POST['navi_item_link'][$id]), $matches);
             // тогда
             if (isset($matches[1])) {
                 // Выполняем запрос к БД и получаем URL (ЧПУ) для  данного документа
                 $link_url = $AVE_DB->Query("\r\n\t\t\t\t\t\tSELECT document_alias\r\n\t\t\t\t\t\tFROM " . PREFIX . "_documents\r\n\t\t\t\t\t\tWHERE id = '" . $matches[1] . "'\r\n\t\t\t\t\t")->GetCell();
             }
             // Выполняем запрос к БД на обновление информации
             $AVE_DB->Query("\r\n\t\t\t\t\tUPDATE " . PREFIX . "_navigation_items\r\n\t\t\t\t\tSET\r\n\t\t\t\t\t\ttitle = '" . $this->_replace_wildcode($title) . "',\r\n\t\t\t\t\t\tnavi_item_link  = '" . $_POST['navi_item_link'][$id] . "',\r\n\t\t\t\t\t\tnavi_item_position  = '" . intval($_POST['navi_item_position'][$id]) . "',\r\n\t\t\t\t\t\tnavi_item_target  = '" . $_POST['navi_item_target'][$id] . "',\r\n\t\t\t\t\t\tnavi_item_status = '" . $navi_item_status . "',\r\n\t\t\t\t\t\tdocument_alias   = '" . ($link_url == '' ? $_POST['navi_item_link'][$id] : $link_url) . "'\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\tId = '" . $id . "'\r\n\t\t\t\t");
         }
     }
     // Если в запросе пришел параметр на добавление нового пункта меню первого уровня
     if (!empty($_POST['Titel_N'][0])) {
         // Выполняем запрос к БД и добавляем новый пункт
         $AVE_DB->Query("\r\n\t\t\t\tINSERT\r\n\t\t\t\tINTO " . PREFIX . "_navigation_items\r\n\t\t\t\tSET\r\n\t\t\t\t\tId     = '',\r\n\t\t\t\t\ttitle  = '" . $this->_replace_wildcode($_POST['Titel_N'][0]) . "',\r\n\t\t\t\t\tparent_id  = '0',\r\n\t\t\t\t\tnavi_item_link   = '" . $_POST['Link_N'][0] . "',\r\n\t\t\t\t\tnavi_item_target   = '" . $_POST['Ziel_N'][0] . "',\r\n\t\t\t\t\tnavi_item_level  = '1',\r\n\t\t\t\t\tnavi_item_position   = '" . intval($_POST['Rang_N'][0]) . "',\r\n\t\t\t\t\tnavi_id = '" . intval($_POST['navi_id']) . "',\r\n\t\t\t\t\tnavi_item_status  = '" . (empty($_POST['Link_N'][0]) ? '0' : '1') . "',\r\n\t\t\t\t\tdocument_alias    = '" . prepare_url(empty($_POST['Url_N'][0]) ? $_POST['Titel_N'][0] : $_POST['Url_N'][0]) . "'\r\n\t\t\t");
         // Сохраняем системное сообщение в журнал
         reportLog($_SESSION['user_name'] . " - добавил пункт меню навигации (" . stripslashes($_POST['Titel_N'][0]) . ") - на первый уровень", 2, 2);
     }
     // Обрабатываем данные с целью добавления пунктов меню второго уровня
     foreach ($_POST['Titel_Neu_2'] as $new2_id => $title) {
         // Если название пункта не пустое
         if (!empty($title)) {
             $new2_id = (int) $new2_id;
             // Выполняем запрос к БД и добавляем новый подпункт
             $AVE_DB->Query("\r\n\t\t\t\t\tINSERT\r\n\t\t\t\t\tINTO " . PREFIX . "_navigation_items\r\n\t\t\t\t\tSET\r\n\t\t\t\t\t\tId     = '',\r\n\t\t\t\t\t\ttitle  = '" . $this->_replace_wildcode($title) . "',\r\n\t\t\t\t\t\tparent_id  = '" . $new2_id . "',\r\n\t\t\t\t\t\tnavi_item_link   = '" . $_POST['Link_Neu_2'][$new2_id] . "',\r\n\t\t\t\t\t\tnavi_item_target   = '" . $_POST['Ziel_Neu_2'][$new2_id] . "',\r\n\t\t\t\t\t\tnavi_item_level  = '2',\r\n\t\t\t\t\t\tnavi_item_position   = '" . intval($_POST['Rang_Neu_2'][$new2_id]) . "',\r\n\t\t\t\t\t\tnavi_id = '" . intval($_POST['navi_id']) . "',\r\n\t\t\t\t\t\tnavi_item_status  = '" . (empty($_POST['Link_Neu_2'][$new2_id]) ? '0' : '1') . "',\r\n\t\t\t\t\t\tdocument_alias    = '" . prepare_url(empty($_POST['Url_Neu_2'][$new2_id]) ? $title : $_POST['Url_Neu_2'][$new2_id]) . "'\r\n\t\t\t\t");
             // Сохраняем системное сообщение в журнал
             reportLog($_SESSION['user_name'] . " - добавил пункт меню навигации (" . stripslashes($title) . ") - второй уровень", 2, 2);
         }
     }
     // Обрабатываем данные с целью добавления пунктов меню третьего уровня
     foreach ($_POST['Titel_Neu_3'] as $new3_id => $title) {
         // Если название пункта не пустое
         if (!empty($title)) {
             $new3_id = (int) $new3_id;
             // Выполняем запрос к БД и добавляем новый подпункт
             $AVE_DB->Query("\r\n\t\t\t\t\tINSERT\r\n\t\t\t\t\tINTO " . PREFIX . "_navigation_items\r\n\t\t\t\t\tSET\r\n\t\t\t\t\t\tId     = '',\r\n\t\t\t\t\t\ttitle  = '" . $this->_replace_wildcode($title) . "',\r\n\t\t\t\t\t\tparent_id  = '" . $new3_id . "',\r\n\t\t\t\t\t\tnavi_item_link   = '" . $_POST['Link_Neu_3'][$new3_id] . "',\r\n\t\t\t\t\t\tnavi_item_target   = '" . $_POST['Ziel_Neu_3'][$new3_id] . "',\r\n\t\t\t\t\t\tnavi_item_level  = '3',\r\n\t\t\t\t\t\tnavi_item_position   = '" . intval($_POST['Rang_Neu_3'][$new3_id]) . "',\r\n\t\t\t\t\t\tnavi_id = '" . intval($_POST['navi_id']) . "',\r\n\t\t\t\t\t\tnavi_item_status  = '" . (empty($_POST['Link_Neu_3'][$new3_id]) ? '0' : '1') . "',\r\n\t\t\t\t\t\tdocument_alias    = '" . prepare_url(empty($_POST['Url_Neu_3'][$new3_id]) ? $title : $_POST['Url_Neu_3'][$new3_id]) . "'\r\n\t\t\t\t");
             // Сохраняем системное сообщение в журнал
             reportLog($_SESSION['user_name'] . " - добавил пункт меню навигации (" . stripslashes($title) . ") - третий уровень", 2, 2);
         }
     }
     // Если в запросе были отмечены пункты меню, которые необходимо удалить, тогда
     if (!empty($_POST['del']) && is_array($_POST['del'])) {
         // Циклически обрабатываем помеченные пункты
         foreach ($_POST['del'] as $del_id => $del) {
             if (!empty($del)) {
                 $del_id = (int) $del_id;
                 // Выполняем запрос к БД для определения у удаляемого пункта подпунктов
                 $num = $AVE_DB->Query("\r\n\t\t\t\t\t\tSELECT Id\r\n\t\t\t\t\t\tFROM " . PREFIX . "_navigation_items\r\n\t\t\t\t\t\tWHERE parent_id = '" . $del_id . "'\r\n\t\t\t\t\t\tLIMIT 1\r\n\t\t\t\t\t")->NumRows();
                 // Если данный пункт имеет подпункты, тогда
                 if ($num == 1) {
                     // Выполняем запрос к БД и деактивируем пункт меню
                     $AVE_DB->Query("\r\n\t\t\t\t\t\t\tUPDATE " . PREFIX . "_navigation_items\r\n\t\t\t\t\t\t\tSET navi_item_status = '0'\r\n\t\t\t\t\t\t\tWHERE Id = '" . $del_id . "'\r\n\t\t\t\t\t\t");
                     // Сохраняем системное сообщение в журнал
                     reportLog($_SESSION['user_name'] . " - деактивировал пункт меню навигации (" . $del_id . ")", 2, 2);
                 } else {
                     // В противном случае, если данный пункт не имеет подпунктов, тогда
                     // Выполняем запрос к БД и удаляем помеченный пункт
                     $AVE_DB->Query("\r\n\t\t\t\t\t\t\tDELETE\r\n\t\t\t\t\t\t\tFROM " . PREFIX . "_navigation_items\r\n\t\t\t\t\t\t\tWHERE Id = '" . $del_id . "'\r\n\t\t\t\t\t\t");
                     // Сохраняем системное сообщение в журнал
                     reportLog($_SESSION['user_name'] . " - удалил пункт меню навигации (" . $del_id . ")", 2, 2);
                 }
             }
         }
     }
     // Выполняем обновление страницы
     header('Location:index.php?do=navigation&action=entries&id=' . $nav_id . '&cp=' . SESSION);
     exit;
 }
Example #13
0
/**
 * Формирование хлебных крошек
 *
 * @return string ссылка
 */
function get_breadcrumb()
{
    global $AVE_DB;
    $crumb = array();
    $curent_document = get_current_document_id();
    $noprint = null;
    $sql = "SELECT * from " . PREFIX . "_documents where document_alias='" . ($_SESSION['user_language'] == DEFAULT_LANGUAGE ? '/' : $_SESSION['accept_langs'][$_SESSION['user_language']]) . "' and document_lang='" . $_SESSION['user_language'] . "'";
    $lang_home_alias = $AVE_DB->Query($sql)->FetchRow();
    $bread_crumb = $lang_home_alias ? "<a href=\"" . get_home_link() . "\">" . $lang_home_alias->document_breadcrum_title . "</a>&nbsp;&rarr;&nbsp;" : '';
    if ($curent_document == 1 || $curent_document == 2) {
        $noprint = 1;
    }
    $sql_document = $AVE_DB->Query("SELECT document_title, document_breadcrum_title, document_parent FROM " . PREFIX . "_documents WHERE Id = '" . $curent_document . "'", -1, 'doc_' . $curent_document);
    $row_document = $sql_document->fetchrow();
    $current->document_breadcrum_title = empty($row_document->document_breadcrum_title) ? $row_document->document_title : $row_document->document_breadcrum_title;
    if (isset($row_document->document_parent) && $row_document->document_parent != 0) {
        $i = 0;
        $current->document_parent = $row_document->document_parent;
        while ($current->document_parent != 0) {
            $sql_doc = $AVE_DB->Query("SELECT Id, document_alias, document_breadcrum_title, document_title, document_parent FROM " . PREFIX . "_documents WHERE Id = '" . $current->document_parent . "'", -1, 'doc_' . $current->document_parent);
            $row_doc = $sql_doc->fetchrow();
            $current->document_parent = $row_doc->document_parent;
            if ($row_doc->document_parent == $row_doc->Id) {
                echo "Ошибка! Вы указали в качестве родительского документа текущий документ.<br>";
                $current->document_parent = 1;
            }
            $crumb['document_breadcrum_title'][$i] = empty($row_doc->document_breadcrum_title) ? $row_doc->document_title : $row_doc->document_breadcrum_title;
            $crumb['document_alias'][$i] = $row_doc->document_alias;
            $crumb['Id'][$i] = $row_doc->Id;
            $i++;
        }
        $length = count($crumb['document_breadcrum_title']);
        $crumb['document_breadcrum_title'] = array_reverse($crumb['document_breadcrum_title']);
        $crumb['document_alias'] = array_reverse($crumb['document_alias']);
        $crumb['Id'] = array_reverse($crumb['Id']);
        for ($n = 0; $n < $length; $n++) {
            $url = rewrite_link('index.php?id=' . $crumb['Id'][$n] . '&amp;doc=' . (empty($crumb['document_alias'][$n]) ? prepare_url($crumb['document_breadcrum_title'][$n]) : $crumb['document_alias'][$n]));
            $bread_crumb .= "<a href=\"" . $url . "\"  target=\"_self\">" . $crumb['document_breadcrum_title'][$n] . "</a>&nbsp;&rarr;&nbsp;";
        }
    }
    $bread_crumb .= "<span>" . $current->document_breadcrum_title . "</span>";
    if (!$noprint) {
        return $bread_crumb;
    }
}
Example #14
0
/**
 * Рекурсивная функция формирования карты сайта
 *
 * @param int $nav_items
 * @param string $sitemap
 * @param int $parent
 */
function printSitemap(&$nav_items, &$sitemap = '', $parent = 0)
{
    $sitemap .= empty($sitemap) ? '<ul class="sitemap">' : '<ul>';
    foreach ($nav_items[$parent] as $row) {
        if (strpos($row['navi_item_link'], 'module=') === false && start_with('index.php?', $row['navi_item_link'])) {
            $row['navi_item_link'] .= '&amp;doc=' . (empty($row['document_alias']) ? prepare_url($row['title']) : $row['document_alias']);
        }
        if (start_with('www.', $row['navi_item_link'])) {
            $row['navi_item_link'] = str_replace('www.', 'http://www.', $row['navi_item_link']);
        }
        $row['navi_item_link'] = rewrite_link($row['navi_item_link']);
        $sitemap .= '<li><a href="' . $row['navi_item_link'] . '" target="' . $row['navi_item_target'] . '">';
        $sitemap .= pretty_chars($row['title']) . '</a>';
        if (isset($nav_items[$row['Id']])) {
            printSitemap($nav_items, $sitemap, $row['Id']);
        }
        $sitemap .= '</li>';
    }
    $sitemap .= '</ul>';
}
Example #15
0
function make_url_from_graphid($graphid, $full = false)
{
    $gurl = array();
    if ($full) {
        $gparams = array();
    } else {
        $gparams = array('height' => 1, 'width' => 1);
    }
    $graph = get_graph_by_graphid($graphid);
    if ($graph) {
        foreach ($graph as $name => $value) {
            if (!is_numeric($name) && !isset($gparams[$name])) {
                $gurl[$name] = $value;
            }
        }
    }
    $url = prepare_url($gurl);
    if (!empty($url)) {
        $url = ($gurl['graphtype'] == GRAPH_TYPE_PIE || $gurl['graphtype'] == GRAPH_TYPE_EXPLODED ? 'chart7.php?' : 'chart3.php?') . trim($url, '&');
    }
    return $url;
}
Example #16
0
 /**
  * Вывод галереи
  *
  * @param string $tpl_dir - путь к папке с шаблонами модуля
  * @param int $gallery_id - идентификатор галереи
  * @param int $lim - количество изображений на странице
  * @param int $ext - признак вывода всех изображений галереи
  */
 function galleryShow($tpl_dir, $gallery_id, $lim, $ext = 0)
 {
     global $AVE_DB, $AVE_Template, $AVE_Core;
     $assign = $images = array();
     $row_gs = $AVE_DB->Query("\r\n\t\t\tSELECT *\r\n\t\t\tFROM " . PREFIX . "_modul_gallery\r\n\t\t\tWHERE id = '" . $gallery_id . "'\r\n\t\t")->FetchRow();
     $limit = $row_gs->gallery_image_on_page > 0 ? $row_gs->gallery_image_on_page : $this->_default_limit_images;
     $limit = empty($lim) ? $limit : $lim;
     $limit = $ext != 1 ? $limit : 10000;
     $start = get_current_page() * $limit - $limit;
     switch ($row_gs->gallery_orderby) {
         case 'position':
             $order_by = "image_position ASC";
             break;
         case 'titleasc':
             $order_by = "image_title ASC";
             break;
         case 'titledesc':
             $order_by = "image_title DESC";
             break;
         case 'dateasc':
             $order_by = "image_date ASC";
             break;
         default:
             $order_by = "image_date DESC";
             break;
     }
     $num = $AVE_DB->Query("\r\n\t\t\tSELECT COUNT(*)\r\n\t\t\tFROM " . PREFIX . "_modul_gallery_images\r\n\t\t\tWHERE gallery_id = '" . $gallery_id . "'\r\n\t\t")->GetCell();
     $sql = $AVE_DB->Query("\r\n\t\t\tSELECT *\r\n\t\t\tFROM " . PREFIX . "_modul_gallery_images\r\n\t\t\tWHERE gallery_id = '" . $gallery_id . "'\r\n\t\t\tORDER BY " . $order_by . "\r\n\t\t\tLIMIT " . $start . "," . $limit . "\r\n\t\t");
     //		$num = $AVE_DB->Query("SELECT FOUND_ROWS()")->GetCell();
     $folder = rtrim('modules/gallery/uploads/' . $row_gs->gallery_folder, '/') . '/';
     while ($row = $sql->FetchAssocArray()) {
         $row['image_type'] = $this->_galleryFileTypeGet($row['image_file_ext']);
         $row['image_author'] = get_username_by_id($row['image_author_id']);
         $row['image_filename'] = rawurlencode($row['image_filename']);
         if (file_exists(BASE_DIR . '/' . $folder . 'th__' . $row['image_filename'])) {
             $row['thumbnail'] = ABS_PATH . $folder . 'th__' . $row['image_filename'];
         } else {
             $row['thumbnail'] = sprintf("%smodules/gallery/thumb.php?file=%s&amp;type=%s&amp;xwidth=%u&amp;folder=%s", ABS_PATH, $row['image_filename'], $row['image_type'], $row_gs->gallery_thumb_width, $row_gs->gallery_folder);
         }
         if ($row_gs->gallery_image_size_show == 1) {
             $fs = filesize(BASE_DIR . '/' . $folder . $row['image_filename']);
             $row['image_size'] = round($fs / 1024, 0);
         }
         if ($row_gs->gallery_type == 7) {
             $search = array('[tag:img:id]', '[tag:img:filename]', '[tag:img:thumbnail]', '[tag:img:title]', '[tag:img:description]', '[tag:gal:id]', '[tag:gal:folder]');
             $replace = array($row['id'], $row['image_filename'], $row['thumbnail'], htmlspecialchars(empty($row['image_title']) ? $AVE_Template->get_config_vars('NoTitle') : $row['image_title'], ENT_QUOTES), htmlspecialchars(empty($row['image_description']) ? $AVE_Template->get_config_vars('NoDescr') : $row['image_description'], ENT_QUOTES), $row_gs->id, ltrim($row_gs->gallery_folder . '/', '/'));
             $row['gallery_script'] = str_replace($search, $replace, $row_gs->gallery_script);
             $row['gallery_image_template'] = str_replace($search, $replace, $row_gs->gallery_image_template);
         }
         array_push($images, $row);
     }
     // Постраничная навигация
     if ($num > $limit) {
         $page_nav = ' <a class="pnav" href="index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias) . (isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']) ? '&amp;artpage=' . $_REQUEST['artpage'] : '') . (isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage']) ? '&amp;apage=' . $_REQUEST['apage'] : '') . '&amp;page={s}' . '">{t}</a> ';
         $page_nav = get_pagination(ceil($num / $limit), 'page', $page_nav, get_settings('navi_box'));
         $assign['page_nav'] = rewrite_link($page_nav);
     }
     $assign['more_images'] = intval(!empty($lim) && $num > $lim);
     $assign['gallery'] = $row_gs;
     $assign['images'] = $images;
     $AVE_Template->assign($assign);
     $AVE_Template->display($tpl_dir . ($ext == 1 ? 'gallery_popup.tpl' : 'gallery.tpl'));
 }
Example #17
0
/**
 * Обработка тега запроса.
 * Возвращает список документов удовлетворяющих параметрам запроса
 * оформленный с использованием шаблона
 *
 * @param int $id	идентификатор запроса
 * @return string
 */
function request_parse($id, $params = array())
{
    global $AVE_Core, $AVE_DB, $request_documents;
    //Доберусь - надо сделать фишку чтобы если афтар не активен или удален то документы его в реквесте не выводятся
    //по идее это бы надстройкой к рекесту сделать чтобы новости не побить и т.д.
    $gen_time = microtime();
    $return = '';
    if (is_array($id)) {
        $id = $id[1];
    }
    $row_ab = $AVE_DB->Query("\n\t\tSELECT *\n\t\tFROM " . PREFIX . "_request\n\t\tWHERE Id = '" . $id . "'\n\t")->FetchRow();
    if (is_object($row_ab)) {
        $ttl = (int) $row_ab->request_cache_lifetime;
        $limit = isset($params['LIMIT']) && intval($params['LIMIT']) > 0 ? intval($params['LIMIT']) : ($row_ab->request_items_per_page > 0 ? $row_ab->request_items_per_page : 0);
        $main_template = $row_ab->request_template_main;
        $item_template = $row_ab->request_template_item;
        $request_order_by = $row_ab->request_order_by;
        $request_asc_desc = $row_ab->request_asc_desc;
        //строим списки подключаемых полей для сортировки
        $request_order = $request_order_by . " " . $request_asc_desc;
        $request_order_fields = '';
        $request_order_tables = '';
        $request_order1 = '';
        if ($row_ab->request_order_by_nat) {
            $request_order_tables = "LEFT JOIN " . PREFIX . "_document_fields AS s" . $row_ab->request_order_by_nat . "\n\t\t\t    ON (s" . $row_ab->request_order_by_nat . ".document_id = a.Id and s" . $row_ab->request_order_by_nat . ".rubric_field_id=" . $row_ab->request_order_by_nat . ")";
            $request_order_fields = "s" . $row_ab->request_order_by_nat . ".field_value, ";
            $request_order = "s" . $row_ab->request_order_by_nat . ".field_value " . $row_ab->request_asc_desc;
        }
        $x = 0;
        if (!empty($params['SORT']) && is_array($params['SORT'])) {
            foreach ($params['SORT'] as $k => $v) {
                if (intval($k) > 0) {
                    $x++;
                    $request_order_tables .= "LEFT JOIN " . PREFIX . "_document_fields AS s" . $k . "\n\t\t\t\t\t\tON (s" . $k . ".document_id = a.Id and s" . $k . ".rubric_field_id=" . $k . ")";
                    if (strpos($v, 'INT') === false) {
                        $request_order_fields .= "s" . $k . ".field_value, ";
                    } else {
                        $request_order_fields .= "s" . $k . ".field_number_value, ";
                        $v = str_replace('INT', '', $v);
                    }
                    $request_order1 .= $x . ' ' . $v . ', ';
                }
            }
        }
        /* ----------- */
        $request_order = addslashes($request_order1 . $request_order);
        $request_order2 = '';
        /* ----------- */
        //Этот кусок для того чтобы можно было параметрами попросить произвольный статус досумента
        //- например в личном кабинете попросить архивные документы
        $docstatus = "AND a.document_status != '0'";
        $docstatus = "AND a.document_status = '1'";
        if (isset($params['STATUS'])) {
            $docstatus = "AND a.document_status = '" . intval($params['STATUS']) . "'";
        }
        $doctime = get_settings('use_doctime') ? "AND a.document_published <= UNIX_TIMESTAMP() AND\n \t\t         \t(a.document_expire = 0 OR a.document_expire >=UNIX_TIMESTAMP())" : '';
        $where_cond = empty($_POST['req_' . $id]) && empty($_SESSION['doc_' . $AVE_Core->curentdoc->Id]['req_' . $id]) ? unserialize($row_ab->request_where_cond) : unserialize(request_get_condition_sql_string($row_ab->Id));
        $where_cond['from'] = str_replace('%%PREFIX%%', PREFIX, $where_cond['from']);
        @($where_cond['where'] = str_replace('%%PREFIX%%', PREFIX, $where_cond['where']));
        $whFromUser = (isset($params['USER_ID']) && intval($params['USER_ID']) > 0 ? ' AND a.document_author_id=' . intval($params['USER_ID']) : '') . (isset($params['USER_WHERE']) && $params['USER_WHERE'] > '' ? ' AND ' . $params['USER_WHERE'] : '') . (isset($params['PARENT']) && intval($params['PARENT']) > 0 ? ' AND a.document_parent=' . intval($params['PARENT']) : '');
        $other_fields = '';
        $other_tables = '';
        $other_fields .= $request_order_fields;
        $other_tables .= $request_order_tables;
        if (isset($params['VIEWS'])) {
            $other_fields .= "(SELECT sum(v1.`count`) FROM " . PREFIX . "_view_count AS v1 WHERE v1.document_id=a.Id AND v1.day_id>" . strtotime($params['VIEWS'] ? $params['VIEWS'] : '-30 years') . ") AS dayviews,\n\t\t\t\t";
            if ($params['VIEWS_ORDER'] > '') {
                $request_order1 = count(explode(',', $other_fields)) - 1 . ' ' . $params['VIEWS_ORDER'] . ',';
            }
        }
        if (isset($params['VOTE'])) {
            $other_fields .= "(SELECT " . $params['VOTE'] . "(v2.`vote`) FROM " . PREFIX . "_module_vote AS v2 WHERE type_of_doc='document' and v2.document_id=a.Id) AS votes,\n\t\t\t\t";
            if ($params['VOTE_ORDER'] > '') {
                $request_order2 = count(explode(',', $other_fields)) - 1 . ' ' . $params['VOTE_ORDER'];
            }
        }
        if (!empty($AVE_Core->install_modules['comment']->ModuleStatus)) {
            $other_tables .= "\n\t\t\t\t\tLEFT JOIN\n\t\t\t\t\t\t" . PREFIX . "_module_comment_info AS b\n\t\t\t\t\t\t\tON b.document_id = a.Id " . (!empty($params['COMMENT']) ? " and b.comment_published>" . strtotime($params['COMMENT']) : '') . "\n\t\t\t\t\t";
            $other_fields .= "COUNT(b.document_id) AS nums,\n\t\t\t\t";
            if (!empty($params['COMMENT_ORDER'])) {
                $request_order1 = count(explode(',', $other_fields)) - 1 . ' ' . $params['COMMENT_ORDER'] . ',';
            }
        }
        $request_order = addslashes($request_order1 . ($request_order2 > '' ? $request_order1 ? $request_order2 . ',' : $request_order2 : '') . $request_order);
        $num = $AVE_DB->Query(eval2var(" ?>\n\t\t\tSELECT COUNT(*)\n\t\t\tFROM\n\t\t\t" . ($where_cond['from'] ? $where_cond['from'] : '') . "\n\t\t\t" . PREFIX . "_documents AS a\n\t\t\tWHERE\n\t\t\t\ta.Id != '1'\n\t\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\n\t\t\tAND a.rubric_id = '" . $row_ab->rubric_id . "'\n\t\t\tAND a.document_deleted != '1'\n\t\t\t" . $docstatus . "\n\t\t\t" . $whFromUser . "\n\t\t\t" . $where_cond['where'] . "\n\t\t\t" . ($row_ab->request_lang ? "AND a.document_lang='" . $_SESSION['user_language'] . "'" : "") . "\n\t\t\t" . $doctime . "\n\t\t<?php "), $ttl, 'rub_' . $row_ab->rubric_id)->GetCell();
        if ($row_ab->request_show_pagination == 1) {
            $num_pages = $limit > 0 ? ceil($num / $limit) : 0;
            @($GLOBALS['page_id'][$_REQUEST['id']]['apage'] = @$GLOBALS['page_id'][$_REQUEST['id']]['apage'] > $num_pages ? $GLOBALS['page_id'][$_REQUEST['id']]['apage'] : $num_pages);
            if (isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage']) && $_REQUEST['apage'] > $num_pages) {
                $redirect_link = rewrite_link('index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias) . (isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']) ? '&amp;artpage=' . $_REQUEST['artpage'] : '') . (isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) ? '&amp;page=' . $_REQUEST['page'] : ''));
                header('Location:' . $redirect_link);
                exit;
            }
            $start = get_current_page('apage') * $limit - $limit;
        } else {
            $start = 0;
        }
        $q = " ?>\n\t\t\tSELECT\n\t\t\t\t" . $other_fields . "\n\t\t\t\ta.Id,\n\t\t\t\ta.document_parent,\n\t\t\t\ta.document_title,\n\t\t\t\ta.document_alias,\n\t\t\t\ta.document_author_id,\n\t\t\t\ta.document_count_view,\n\t\t\t\ta.document_published,\n\t\t\t\ta.document_meta_keywords\n\t\t\tFROM\n\t\t\t\t" . ($where_cond['from'] ? $where_cond['from'] : '') . "\n\t\t\t\t" . PREFIX . "_documents AS a\n\t\t\t" . ($other_tables > '' ? $other_tables : '') . "\n\t\t\tWHERE\n\t\t\t\ta.Id != '1'\n\t\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\n\t\t\tAND a.rubric_id = '" . $row_ab->rubric_id . "'\n\t\t\tAND a.document_deleted != '1'\n\t\t\t" . ($row_ab->request_lang ? "AND a.document_lang='" . $_SESSION['user_language'] . "'" : "") . "\n\t\t\t" . $whFromUser . "\n\t\t\t" . $docstatus . "\n\t\t\t" . $where_cond['where'] . "\n\t\t\t" . $doctime . "\n\t\t\tGROUP BY a.Id\n\t\t\tORDER BY " . $request_order . "\n\t\t\t" . ($limit > 0 ? "LIMIT " . $start . "," . $limit : '') . " <?php ";
        $q = eval2var($q);
        $q = $AVE_DB->Query($q, $ttl, 'rub_' . $row_ab->rubric_id);
        if ($q->NumRows() > 0) {
            $main_template = preg_replace('/\\[tag:if_empty](.*?)\\[\\/tag:if_empty]/si', '', $main_template);
            $main_template = str_replace(array('[tag:if_notempty]', '[/tag:if_notempty]'), '', $main_template);
        } else {
            $main_template = preg_replace('/\\[tag:if_notempty](.*?)\\[\\/tag:if_notempty]/si', '', $main_template);
            $main_template = str_replace(array('[tag:if_empty]', '[/tag:if_empty]'), '', $main_template);
        }
        $page_nav = '';
        if ($row_ab->request_show_pagination == 1 && $num_pages > 1) {
            $page_nav = ' <a class="pnav" href="index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias) . (isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']) ? '&amp;artpage=' . $_REQUEST['artpage'] : '') . '&amp;apage={s}' . (isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) ? '&amp;page=' . $_REQUEST['page'] : '') . '">{t}</a> ';
            $page_nav = get_pagination($num_pages, 'apage', $page_nav, get_settings('navi_box'));
            //$page_nav = rewrite_link($page_nav);
            // Костыль
            $page_nav = str_ireplace('"//"', '"/"', str_ireplace('///', '/', rewrite_link($page_nav)));
        }
        $rows = array();
        $request_documents = array();
        while ($row = $q->FetchRow()) {
            array_push($request_documents, $row->Id);
            array_push($rows, $row);
        }
        $items = '';
        $x = 0;
        $items_count = count($rows);
        foreach ($rows as $row) {
            $x++;
            $item = showrequestelement($row, $item_template, $x, $x == $items_count ? true : false);
            $items .= $item;
        }
        //		$items = preg_replace_callback('/\[tag:teaser:(\d+)\]/', "showteaser", $items);
        $main_template = preg_replace_callback('/\\[tag:sysblock:([0-9-]+)\\]/', 'parse_sysblock', $main_template);
        $main_template = str_replace('[tag:pages]', $page_nav, $main_template);
        $main_template = preg_replace('/\\[tag:date:([a-zA-Z0-9-]+)\\]/e', "RusDate(date('\$1', " . $AVE_Core->curentdoc->document_published . "))", $main_template);
        $main_template = str_replace('[tag:docid]', $AVE_Core->curentdoc->Id, $main_template);
        $main_template = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
        $main_template = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
        $main_template = str_replace('[tag:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_template);
        $main_template = str_replace('[tag:doctotal]', $num, $main_template);
        $main_template = str_replace('[tag:pagetitle]', $AVE_Core->curentdoc->document_title, $main_template);
        $main_template = preg_replace('/\\[tag:dropdown:([,0-9]+)\\]/e', "request_get_dropdown(\"\$1\", " . $row_ab->rubric_id . ", " . $row_ab->Id . ");", $main_template);
        $return = str_replace('[tag:content]', $items, $main_template);
        // парсим тизер документа
        //$return = preg_replace_callback('/\[tag:teaser:(\d+)\]/e', "showteaser", $return);
        $return = str_replace('[tag:path]', ABS_PATH, $return);
        $return = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $return);
        $return = $AVE_Core->coreModuleTagParse($return);
    }
    $gen_time = microtime() - $gen_time;
    $GLOBALS['block_generate'][] = array('REQUEST_' . $id => $gen_time);
    return $return;
}
Example #18
0
/**
 * Рекурсивная функция для формирования меню навигации
 *
 * @param string $navi
 * @param int $ebenen
 * @param string $way
 * @param int $rub
 * @param array $nav_items
 * @param string $row_ul
 * @param int $parent
 */
function printNavi(&$navi, &$ebenen, &$way, &$rub, &$nav_items, &$row_ul, $parent = 0)
{
    $ebene = $nav_items[$parent][0]['navi_item_level'];
    switch ($ebene) {
        case 1:
            $navi .= $row_ul->navi_level1begin;
            break;
        case 2:
            $navi .= $row_ul->navi_level2begin;
            break;
        case 3:
            $navi .= $row_ul->navi_level3begin;
            break;
    }
    foreach ((array) $nav_items[$parent] as $row) {
        //		$aktiv = (in_array($row['Id'], $way) || strpos($row['navi_item_link'], 'index.php?' . $_SERVER['QUERY_STRING']) !== false) ? 'aktiv' : 'inaktiv';
        $aktiv = in_array($row['Id'], $way) ? 'aktiv' : 'inaktiv';
        $akt = str_replace('[tag:linkname]', $row['title'], $ebenen[$ebene][$aktiv]);
        $akt = str_replace('[tag:linkid]', $row['Id'], $akt);
        if (strpos($row['navi_item_link'], 'module=') === false && start_with('index.php?', $row['navi_item_link'])) {
            if ($row['navi_item_link'] == 'index.php?id=1') {
                $akt = str_replace('[tag:link]', ABS_PATH, $akt);
            } else {
                $akt = str_replace('[tag:link]', $row['navi_item_link'] . "&amp;doc=" . (empty($row['document_alias']) ? prepare_url($row['title']) : $row['document_alias']), $akt);
            }
        } else {
            //			if (strpos($row['navi_item_link'], 'module=') === false) $row['navi_item_link'] = $row['navi_item_link'] . URL_SUFF;
            $akt = str_replace('[tag:link]', $row['navi_item_link'], $akt);
            if (start_with('www.', $row['navi_item_link'])) {
                $akt = str_replace('www.', 'http://www.', $akt);
            }
        }
        $navi .= str_replace('[tag:target]', $row['navi_item_target'], $akt);
        //		$akt = str_replace('[tag:target]', $row['navi_item_target'], $akt);
        //		$navi .= rewrite_link($akt);
        if (isset($nav_items[$row['Id']])) {
            printNavi($navi, $ebenen, $way, $rub, $nav_items, $row_ul, $row['Id']);
        }
    }
    switch ($ebene) {
        case 1:
            $navi .= $row_ul->navi_level1end;
            break;
        case 2:
            $navi .= $row_ul->navi_level2end;
            break;
        case 3:
            $navi .= $row_ul->navi_level3end;
            break;
    }
}
Example #19
0
 /**
  *	ВНЕШНИЕ МЕТОДЫ
  */
 function searchResultGet($tpl_dir, $lang_file)
 {
     global $AVE_DB, $AVE_Template;
     $AVE_Template->config_load($lang_file);
     define('MODULE_SITE', $AVE_Template->get_config_vars('SEARCH_RESULTS'));
     $stem_words = array();
     $tmp = preg_replace('/[^\\x20-\\xFF]|[><!?.,;=-]/', ' ', $_GET['query']);
     $this->_search_string = trim(preg_replace('/  +/', ' ', stripslashes($tmp)));
     if (mb_strlen($this->_search_string) > 2) {
         // экранирование для LIKE
         $tmp = str_replace('\\', '\\\\', $this->_search_string);
         $tmp = addcslashes(addslashes($tmp), '%_');
         //			$tmp = preg_replace('/  +/', ' ', $tmp);
         $tmp = preg_split('/\\s+/', $tmp);
         $where = '';
         if (sizeof($tmp)) {
             $_tmp = preg_grep('/^[^\\+|-].{3,}/', $tmp);
             array_walk($_tmp, array(&$this, '_create_string_like'));
             // +
             $__tmp = preg_grep('/^\\+.{3,}/', $tmp);
             array_walk($__tmp, array(&$this, '_create_string_like'), '+');
             // -
             $___tmp = preg_grep('/^-.{3,}/', $tmp);
             array_walk($___tmp, array(&$this, '_create_string_like'), '-');
             if (!empty($_tmp)) {
                 $where = 'WHERE (' . implode(isset($_REQUEST['or']) && 1 == $_REQUEST['or'] ? ' OR ' : ' AND ', $_tmp) . ')';
                 if (!empty($__tmp)) {
                     $where .= ' AND ' . implode(' AND ', array_merge($__tmp, $___tmp));
                 }
             } elseif (!empty($__tmp)) {
                 $where = 'WHERE ' . implode(' AND ', array_merge($__tmp, $___tmp));
             }
         }
         $num = 0;
         if ($where != '') {
             $type_search = isset($_REQUEST['ts']) && 1 == $_REQUEST['ts'];
             $limit = $this->_limit;
             $start = get_current_page() * $limit - $limit;
             $query_feld = $AVE_DB->Query("\r\n\t\t\t\t\tSELECT SQL_CALC_FOUND_ROWS\r\n\t\t\t\t\t\tdocument_id,\r\n\t\t\t\t\t\tfield_value\r\n\t\t\t\t\tFROM " . PREFIX . "_document_fields\r\n\t\t\t\t\tLEFT JOIN " . PREFIX . "_rubric_fields AS rub\r\n\t\t\t\t\t\tON rubric_field_id = rub.Id\r\n\t\t\t\t\t" . $where . "\r\n\t\t\t\t\tAND rubric_field_type = '" . ($type_search ? 'kurztext' : 'langtext') . "'\r\n\t\t\t\t\tAND document_in_search = '1'\r\n\t\t\t\t\tLIMIT " . $start . "," . $limit);
             $num = $AVE_DB->Query("SELECT FOUND_ROWS()")->GetCell();
             $sw = addslashes(mb_strtolower($this->_search_string));
             $exist = $AVE_DB->Query("\r\n\t\t\t\t\tSELECT 1\r\n\t\t\t\t\tFROM " . PREFIX . "_modul_search\r\n\t\t\t\t\tWHERE search_query = '" . $sw . "'\r\n\t\t\t\t\tLIMIT 1\r\n\t\t\t\t")->NumRows();
             if ($exist) {
                 $AVE_DB->Query("\r\n\t\t\t\t\t\tUPDATE " . PREFIX . "_modul_search\r\n\t\t\t\t\t\tSET\r\n\t\t\t\t\t\t\tsearch_found = '" . (int) $num . "',\r\n\t\t\t\t\t\t\tsearch_count = search_count+1\r\n\t\t\t\t\t\tWHERE search_query = '" . $sw . "'\r\n\t\t\t\t\t");
             } else {
                 $AVE_DB->Query("\r\n\t\t\t\t\t\tINSERT\r\n\t\t\t\t\t\tINTO " . PREFIX . "_modul_search\r\n\t\t\t\t\t\tSET\r\n\t\t\t\t\t\t\tId = '',\r\n\t\t\t\t\t\t\tsearch_found = '" . (int) $num . "',\r\n\t\t\t\t\t\t\tsearch_query = '" . $sw . "',\r\n\t\t\t\t\t\t\tsearch_count = 1\r\n\t\t\t\t\t");
             }
             if ($num > $limit) {
                 $page_nav = " <a class=\"pnav\" href=\"index.php?module=search&amp;query=" . urlencode($this->_search_string) . ($type_search ? '&amp;ts=1' : '') . (isset($_REQUEST['or']) && 1 == $_REQUEST['or'] ? "&amp;or=1" : "") . "&amp;page={s}\">{t}</a> ";
                 $page_nav = get_pagination(ceil($num / $limit), 'page', $page_nav, trim(get_settings('navi_box')));
                 $AVE_Template->assign('q_navi', $page_nav);
             }
         }
         if ($num > 0) {
             $modul_search_results = array();
             array_walk($this->_stem_words, create_function('&$val', '$val=preg_quote(stripslashes(stripslashes(str_replace("\\"","&quot;",$val))),"/");'));
             $regex_snapshot = '/.{0,100}[^\\s]*' . implode('[^\\s]*.{0,100}|.{0,100}[^\\s]*', $this->_stem_words) . '[^\\s]*.{0,100}/is';
             $regex_highlight = '/[^\\s]*' . implode('[^\\s]*|[^\\s]*', $this->_stem_words) . '[^\\s]*/is';
             $doctime = get_settings('use_doctime') ? "AND document_published <= " . time() . " AND (document_expire = 0 OR document_expire >= " . time() . ")" : '';
             while ($row_feld = $query_feld->FetchRow()) {
                 $sql = $AVE_DB->Query("\r\n\t\t\t\t\t\tSELECT\r\n\t\t\t\t\t\t\tId,\r\n\t\t\t\t\t\t\tdocument_title,\r\n\t\t\t\t\t\t\tdocument_alias\r\n\t\t\t\t\t\tFROM " . PREFIX . "_documents\r\n\t\t\t\t\t\tWHERE Id = '" . $row_feld->document_id . "'\r\n\t\t\t\t\t\tAND document_deleted = '0'\r\n\t\t\t\t\t\tAND document_status = '1'\r\n\t\t\t\t\t\t" . $doctime);
                 while ($row = $sql->FetchRow()) {
                     $row->Text = $row_feld->field_value;
                     $row->Text = strip_tags($row->Text, $this->_allowed_tags);
                     $fo = array();
                     preg_match($regex_snapshot, $row->Text, $fo);
                     $row->Text = $type_search ? '' : ' ... ';
                     while (list($key, $val) = @each($fo)) {
                         $row->Text .= $val . ($type_search ? '' : ' ... ');
                     }
                     if (1 == $this->_highlight && !empty($this->_stem_words)) {
                         $row->Text = @preg_replace($regex_highlight, "<span class=\"mod_search_highlight\">\$0</span>", $row->Text);
                     }
                     $row->document_alias = rewrite_link('index.php?id=' . $row->Id . '&amp;doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
                     array_push($modul_search_results, $row);
                 }
             }
             $AVE_Template->assign('searchresults', $modul_search_results);
         } else {
             $AVE_Template->assign('no_results', 1);
         }
     } else {
         $AVE_Template->assign('no_results', 1);
     }
     if (!defined('MODULE_CONTENT')) {
         $AVE_Template->assign('inc_path', BASE_DIR . '/modules/search/templates');
         define('MODULE_CONTENT', $AVE_Template->fetch($tpl_dir . 'results.tpl'));
     }
 }
Example #20
0
            }
            if ($row_fields->rubric_field_id == $rss_settings->rss_description_id) {
                if ($rss_settings->rss_description_lenght == 0) {
                    $teaser = explode('<a name="more"></a>', $row_fields->field_value);
                    $rss_item['description'] = $teaser[0];
                } else {
                    if (mb_strlen($row_fields->field_value) > $rss_settings->rss_description_lenght) {
                        $rss_item['description'] = mb_substr($row_fields->field_value, 0, $rss_settings->rss_description_lenght) . '…';
                    } else {
                        $rss_item['description'] = $row_fields->field_value;
                    }
                }
                $rss_item['description'] = parse_hide($rss_item['description']);
            }
        }
        $link_doc = !empty($row_doc->document_alias) ? $row_doc->document_alias : prepare_url($row_doc->document_title);
        $link = rewrite_link('index.php?id=' . $row_doc->Id . '&amp;doc=' . $link_doc);
        $rss_item['link'] = $rss_settings->rss_site_url . mb_substr($link, mb_strlen(ABS_PATH));
        $rss_item['pubDate'] = $row_doc->document_published ? date('r', $row_doc->document_published) : date('r', time());
        array_push($rss_items, $rss_item);
    }
}
// Ну а тут собственно шлем заголовок, что у нас документ XML и в путь... выводим данные
header("Content-Type: application/xml");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
echo '<?xml version="1.0" encoding="utf8"?>';
?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
Example #21
0
 function test_prepare_url()
 {
     global $CFG, $PAGE;
     $fullexternalurl = 'http://www.externalsite.com/somepage.php';
     $fullmoodleurl = $CFG->wwwroot . '/mod/forum/view.php?id=5';
     $relativeurl1 = 'edit.php';
     $relativeurl2 = '/edit.php';
     $this->assertEqual($fullmoodleurl, prepare_url($fullmoodleurl));
     $this->assertEqual($fullexternalurl, prepare_url($fullexternalurl));
     $this->assertEqual("{$CFG->wwwroot}/admin/report/unittest/{$relativeurl1}", prepare_url($relativeurl1));
     $this->assertEqual("{$CFG->wwwroot}{$relativeurl2}", prepare_url($relativeurl2));
     // Use moodle_url object
     $this->assertEqual($fullmoodleurl, prepare_url(new moodle_url('/mod/forum/view.php', array('id' => 5))));
     $this->assertEqual($fullexternalurl, prepare_url(new moodle_url($fullexternalurl)));
     $this->assertEqual("{$CFG->wwwroot}/admin/report/unittest/{$relativeurl1}", prepare_url(new moodle_url($relativeurl1)));
     $this->assertEqual("{$CFG->wwwroot}{$relativeurl2}", prepare_url(new moodle_url($relativeurl2)));
 }
function url_param($param, $isRequest = true, $name = null)
{
    $result = '';
    if (!is_array($param)) {
        if (is_null($name)) {
            if (!$isRequest) {
                fatal_error(_('Not request variable require.'));
            }
            $name = $param;
        }
    }
    if ($isRequest) {
        $var =& $_REQUEST[$param];
    } else {
        $var =& $param;
    }
    if (isset($var)) {
        $result = prepare_url($var, $name);
    }
    return $result;
}
Example #23
0
/**
 * Выборка докуметов из БД на основании Месяца, Года и Дня
 * День необязательный параметр
 *
 * @param int $newsarchive_id	идентификатор архива
 * @param int $month			месяц
 * @param int $year				год
 * @param int $day				день
 */
function show_by($newsarchive_id, $month, $year, $day = 0)
{
    global $AVE_DB, $AVE_Template;
    if (defined('MODULE_CONTENT')) {
        return;
    }
    $assign = array();
    $tpl_dir = BASE_DIR . '/modules/newsarchive/templates/';
    $lang_file = BASE_DIR . '/modules/newsarchive/lang/' . $_SESSION['user_language'] . '.txt';
    $AVE_Template->config_load($lang_file, 'admin');
    // Определяем, пришел ли в запросе номер дня
    $db_day = is_numeric($day) && $day != 0 ? "AND DAYOFMONTH(FROM_UNIXTIME(a.document_published)) = '" . $day . "'" : '';
    // Выбираем все параметры для запроса с текущим ID
    $newsarchive = $AVE_DB->Query("\r\n\t\tSELECT *\r\n\t\tFROM " . PREFIX . "_modul_newsarchive\r\n\t\tWHERE id = '" . (int) $newsarchive_id . "'\r\n\t")->FetchRow();
    // Формирование условий сортировки выводимых документов
    $db_sort = 'ORDER BY a.document_published ASC';
    if (isset($_REQUEST['sort'])) {
        switch ($_REQUEST['sort']) {
            case 'title':
                $db_sort = 'ORDER BY a.document_title ASC';
                break;
            case 'title_desc':
                $db_sort = 'ORDER BY a.document_title DESC';
                break;
            case 'date':
                $db_sort = 'ORDER BY a.document_published ASC';
                break;
            case 'date_desc':
                $db_sort = 'ORDER BY a.document_published DESC';
                break;
            case 'rubric':
                $db_sort = 'ORDER BY b.rubric_title ASC';
                break;
            case 'rubric_desc':
                $db_sort = 'ORDER BY b.rubric_title DESC';
                break;
            default:
                $db_sort = 'ORDER BY a.document_published ASC';
                break;
        }
    }
    $doctime = get_settings('use_doctime') ? "AND document_published <= " . time() . " AND (document_expire = 0 OR document_expire >= " . time() . ")" : '';
    // Выбираем из БД документы. которые соответствуют условиям для запроса и модуля
    $query = $AVE_DB->Query("\r\n\t\tSELECT\r\n\t\t  \ta.Id,\r\n\t\t  \ta.rubric_id,\r\n\t\t  \ta.document_title,\r\n\t\t  \ta.document_alias,\r\n\t\t  \ta.document_published,\r\n\t\t  \tb.rubric_title\r\n\t  \tFROM\r\n\t  \t\t" . PREFIX . "_documents as a,\r\n\t  \t\t" . PREFIX . "_rubrics as b\r\n\t\tWHERE rubric_id IN (" . $newsarchive->newsarchive_rubrics . ")\r\n\t\tAND MONTH(FROM_UNIXTIME(a.document_published)) = '" . (int) $month . "'\r\n\t\tAND YEAR(FROM_UNIXTIME(a.document_published))= '" . (int) $year . "'\r\n\t\t" . $db_day . "\r\n\t\tAND a.rubric_id = b.Id\r\n\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\r\n  \t\tAND document_deleted != '1'\r\n  \t\tAND document_status != '0'\r\n  \t\t" . $doctime . "\r\n\t\t" . $db_sort . "\r\n\t");
    // Заполняем массив докуметов результатами из БД
    $documents = array();
    while ($doc = $query->FetchRow()) {
        $doc->document_alias = rewrite_link('index.php?id=' . $doc->Id . '&amp;doc=' . (empty($doc->document_alias) ? prepare_url($doc->document_title) : $doc->document_alias));
        array_push($documents, $doc);
    }
    // Формируем меню навигации по дням
    $day_in_month = date('t', mktime(0, 0, 0, (int) $month, 1, (int) $year));
    $m_arr = array(null, 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь');
    $assign['newsarchive'] = $newsarchive;
    $assign['documents'] = $documents;
    $assign['days'] = range(1, $day_in_month);
    $assign['month_name'] = $m_arr[(int) $month];
    $assign['year'] = (int) $year;
    $assign['month'] = (int) $month;
    $assign['day'] = (int) $day;
    $AVE_Template->assign($assign);
    define('MODULE_SITE', $AVE_Template->get_config_vars('ARCHIVE_FROM') . ' ' . $m_arr[(int) $month] . ', ' . (int) $year . ' ' . $AVE_Template->get_config_vars('ARCHIVE_YEAR'));
    define('MODULE_CONTENT', $AVE_Template->fetch($tpl_dir . 'archive_result.tpl'));
}
Example #24
0
/**
 * Обработка тега запроса.
 * Возвращает список документов удовлетворяющих параметрам запроса
 * оформленный с использованием шаблона
 *
 * @param int $id	идентификатор запроса
 * @return string
 */
function request_parse($id)
{
    global $AVE_Core, $AVE_DB, $request_documents;
    $return = '';
    if (is_array($id)) {
        $id = $id[1];
    }
    $row_ab = $AVE_DB->Query("\r\n\t\tSELECT *\r\n\t\tFROM " . PREFIX . "_request\r\n\t\tWHERE Id = '" . $id . "'\r\n\t")->FetchRow();
    if (is_object($row_ab)) {
        $ttl = (int) $row_ab->request_cache_lifetime;
        $limit = $row_ab->request_items_per_page < 1 ? 1 : $row_ab->request_items_per_page;
        $main_template = $row_ab->request_template_main;
        $item_template = $row_ab->request_template_item;
        $request_order_by = $row_ab->request_order_by;
        $request_asc_desc = $row_ab->request_asc_desc;
        $request_order = $request_order_by . " " . $request_asc_desc;
        $request_order_fields = '';
        $request_order_tables = '';
        if ($row_ab->request_order_by_nat) {
            $request_order_tables = "LEFT JOIN " . PREFIX . "_document_fields AS s" . $row_ab->request_order_by_nat . "\r\n\t\t\t    ON (s" . $row_ab->request_order_by_nat . ".document_id = a.Id and s" . $row_ab->request_order_by_nat . ".rubric_field_id=" . $row_ab->request_order_by_nat . ")";
            $request_order_fields = "s" . $row_ab->request_order_by_nat . ".field_value, ";
            $request_order = "s" . $row_ab->request_order_by_nat . ".field_value " . $row_ab->request_asc_desc;
        }
        $doctime = get_settings('use_doctime') ? "AND a.document_published <= UNIX_TIMESTAMP() AND\r\n \t\t         \t(a.document_expire = 0 OR a.document_expire >=UNIX_TIMESTAMP())" : '';
        $where_cond = empty($_POST['req_' . $id]) && empty($_SESSION['doc_' . $AVE_Core->curentdoc->Id]['req_' . $id]) ? unserialize($row_ab->request_where_cond) : unserialize(request_get_condition_sql_string($row_ab->Id));
        $where_cond['from'] = str_replace('%%PREFIX%%', PREFIX, $where_cond['from']);
        $where_cond['where'] = str_replace('%%PREFIX%%', PREFIX, $where_cond['where']);
        if ($row_ab->request_show_pagination == 1) {
            if (!empty($AVE_Core->install_modules['comment']->Status)) {
                $num = $AVE_DB->Query(eval2var(" ?> \r\n\t\t\t\t\tSELECT COUNT(*)\r\n\t\t\t\t\tFROM \r\n\t\t\t\t\t" . ($where_cond['from'] ? $where_cond['from'] : '') . "\r\n\t\t\t\t\t" . PREFIX . "_documents AS a\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\ta.Id != '1'\r\n\t\t\t\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\r\n\t\t\t\t\tAND a.Id != '" . get_current_document_id() . "'\r\n\t\t\t\t\tAND a.rubric_id = '" . $row_ab->rubric_id . "'\r\n\t\t\t\t\tAND a.document_deleted != '1'\r\n\t\t\t\t\tAND a.document_status != '0'\r\n\t\t\t\t\t" . $where_cond['where'] . "\r\n\t\t\t\t\t" . $doctime . "\r\n\t\t\t\t<?php "), $ttl, 'rub_' . $row_ab->rubric_id)->GetCell();
            } else {
                $num = $AVE_DB->Query(eval2var(" ?>\r\n\t\t\t\t\tSELECT COUNT(*)\r\n\t\t\t\t\tFROM \r\n\t\t\t\t\t" . ($where_cond['from'] ? $where_cond['from'] : '') . "\r\n\t\t\t\t\t" . PREFIX . "_documents AS a\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\ta.Id != '1'\r\n\t\t\t\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\r\n\t\t\t\t\tAND a.Id != '" . get_current_document_id() . "'\r\n\t\t\t\t\tAND a.rubric_id = '" . $row_ab->rubric_id . "'\r\n\t\t\t\t\tAND a.document_deleted != '1'\r\n\t\t\t\t\tAND a.document_status != '0'\r\n\t\t\t\t\t" . $where_cond['where'] . "\r\n\t\t\t\t\t" . $doctime . "\r\n\t\t\t\t<?php "), $ttl, 'rub_' . $row_ab->rubric_id)->GetCell();
            }
            $seiten = ceil($num / $limit);
            if (isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage']) && $_REQUEST['apage'] > $seiten) {
                $redirect_link = rewrite_link('index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias) . (isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']) ? '&amp;artpage=' . $_REQUEST['artpage'] : '') . (isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) ? '&amp;page=' . $_REQUEST['page'] : ''));
                header('Location:' . $redirect_link);
                exit;
            }
            $start = get_current_page('apage') * $limit - $limit;
        } else {
            $start = 0;
        }
        if ($row_ab->request_items_per_page != 0) {
            $filter_limit = "LIMIT " . $start . "," . $limit;
        }
        if (!empty($AVE_Core->install_modules['comment']->Status)) {
            $q = " ?>\r\n\t\t\t\tSELECT\r\n\t\t\t\t\t" . $request_order_fields . "\r\n\t\t\t\t\ta.Id,\r\n\t\t\t\t\ta.document_title,\r\n\t\t\t\t\ta.document_alias,\r\n\t\t\t\t\ta.document_author_id,\r\n\t\t\t\t\ta.document_count_view,\r\n\t\t\t\t\ta.document_published,\r\n\t\t\t\t\tCOUNT(b.document_id) AS nums\r\n\t\t\t\tFROM\r\n\t\t\t\t\t" . ($where_cond['from'] ? $where_cond['from'] : '') . "\r\n\t\t\t\t\t" . PREFIX . "_documents AS a\r\n\t\t\t\tLEFT JOIN\r\n\t\t\t\t\t" . PREFIX . "_modul_comment_info AS b\r\n\t\t\t\t\t\tON b.document_id = a.Id\r\n\t\t\t\t    " . ($request_order_tables > '' ? $request_order_tables : '') . "\t\r\n\t\t\t\tWHERE\r\n\t\t\t\t\ta.Id != '1'\r\n\t\t\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\r\n\t\t\t\tAND a.Id != '" . get_current_document_id() . "'\r\n\t\t\t\tAND a.rubric_id = '" . $row_ab->rubric_id . "'\r\n\t\t\t\tAND a.document_deleted != '1'\r\n\t\t\t\tAND a.document_status != '0'\r\n\t\t\t\t" . $where_cond['where'] . "\r\n\t\t\t\t" . $doctime . "\r\n\t\t\t\tGROUP BY a.Id\r\n\t\t\t\tORDER BY " . $request_order . "\r\n\t\t\t\t" . $filter_limit . " <?php ";
        } else {
            $q = " ?>\r\n\t\t\t\tSELECT\r\n\t\t\t\t\t" . $request_order_fields . "\r\n\t\t\t\t\ta.Id,\r\n\t\t\t\t\ta.document_title,\r\n\t\t\t\t\ta.document_alias,\r\n\t\t\t\t\ta.document_author_id,\r\n\t\t\t\t\ta.document_count_view,\r\n\t\t\t\t\ta.document_published\r\n\t\t\t\tFROM\r\n\t\t\t\t\t" . ($where_cond['from'] ? $where_cond['from'] : '') . "\r\n\t\t\t\t\t\r\n\t\t\t\t\t" . PREFIX . "_documents AS a\r\n\t\t\t\t\t" . ($request_order_tables > '' ? $request_order_tables : "") . "\r\n\t\t\t\tWHERE\r\n\t\t\t\t\ta.Id != '1'\r\n\t\t\t\tAND a.Id != '" . PAGE_NOT_FOUND_ID . "'\r\n\t\t\t\tAND a.Id != '" . get_current_document_id() . "'\r\n\t\t\t\tAND a.rubric_id = '" . $row_ab->rubric_id . "'\r\n\t\t\t\tAND a.document_deleted != '1'\r\n\t\t\t\tAND a.document_status != '0'\r\n\t\t\t\t" . $where_cond['where'] . "\r\n\t\t\t\t" . $doctime . "\r\n\t\t\t\tORDER BY " . $request_order . "\r\n\t\t\t\t" . $filter_limit . " <?php ";
        }
        $q = eval2var($q);
        $q = $AVE_DB->Query($q, $ttl, 'rub_' . $row_ab->rubric_id);
        if ($q->NumRows() > 0) {
            $main_template = preg_replace('/\\[tag:if_empty](.*?)\\[\\/tag:if_empty]/si', '', $main_template);
            $main_template = str_replace(array('[tag:if_notempty]', '[/tag:if_notempty]'), '', $main_template);
        } else {
            $main_template = preg_replace('/\\[tag:if_notempty](.*?)\\[\\/tag:if_notempty]/si', '', $main_template);
            $main_template = str_replace(array('[tag:if_empty]', '[/tag:if_empty]'), '', $main_template);
        }
        $page_nav = '';
        if ($row_ab->request_show_pagination == 1 && $seiten > 1 && $row_ab->request_items_per_page != 0) {
            $page_nav = ' <a class="pnav" href="index.php?id=' . $AVE_Core->curentdoc->Id . '&amp;doc=' . (empty($AVE_Core->curentdoc->document_alias) ? prepare_url($AVE_Core->curentdoc->document_title) : $AVE_Core->curentdoc->document_alias) . (isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']) ? '&amp;artpage=' . $_REQUEST['artpage'] : '') . '&amp;apage={s}' . (isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) ? '&amp;page=' . $_REQUEST['page'] : '') . '">{t}</a> ';
            $page_nav = get_pagination($seiten, 'apage', $page_nav, get_settings('navi_box'));
            $page_nav = rewrite_link($page_nav);
        }
        $rows = array();
        $request_documents = array();
        while ($row = $q->FetchRow()) {
            array_push($request_documents, $row->Id);
            array_push($rows, $row);
        }
        $items = '';
        foreach ($rows as $row) {
            $cachefile_docid = BASE_DIR . '/cache/sql/doc_' . $row->Id . '/request-' . $id . '.cache';
            if (!file_exists($cachefile_docid)) {
                $item = preg_replace('/\\[tag:rfld:(\\d+)]\\[(more|esc|[0-9-]+)]/e', "request_get_document_field(\"\$1\", {$row->Id}, \"\$2\")", $item_template);
                //if(!file_exists(dirname($cachefile_docid)))mkdir(dirname($cachefile_docid),0777,true);
                //file_put_contents($cachefile_docid,$item);
            } else {
                $item = file_get_contents($cachefile_docid);
            }
            $link = rewrite_link('index.php?id=' . $row->Id . '&amp;doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
            $item = str_replace('[tag:link]', $link, $item);
            $item = str_replace('[tag:docid]', $row->Id, $item);
            $item = str_replace('[tag:doctitle]', $row->document_title, $item);
            $item = str_replace('[tag:docparent]', $row->document_parent, $item);
            $item = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $row->document_published)), $item);
            $item = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $row->document_published)), $item);
            $item = str_replace('[tag:docauthor]', get_username_by_id($row->document_author_id), $item);
            $item = str_replace('[tag:docviews]', $row->document_count_view, $item);
            $item = str_replace('[tag:doccomments]', isset($row->nums) ? $row->nums : '', $item);
            $items .= $item;
        }
        $main_template = str_replace('[tag:pages]', $page_nav, $main_template);
        $main_template = str_replace('[tag:doctotal]', $seiten * $q->NumRows(), $main_template);
        $main_template = str_replace('[tag:pagetitle]', $AVE_DB->Query("SELECT document_title FROM " . PREFIX . "_documents WHERE Id = '" . $AVE_Core->curentdoc->Id . "' ")->GetCell(), $main_template);
        $main_template = str_replace('[tag:docid]', $AVE_Core->curentdoc->Id, $main_template);
        $main_template = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
        $main_template = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
        $main_template = str_replace('[tag:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_template);
        $main_template = preg_replace('/\\[tag:dropdown:([,0-9]+)\\]/e', "request_get_dropdown(\"\$1\", " . $row_ab->rubric_id . ", " . $row_ab->Id . ");", $main_template);
        $return = str_replace('[tag:content]', $items, $main_template);
        $return = str_replace('[tag:path]', ABS_PATH, $return);
        $return = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . THEME_FOLDER . '/', $return);
        $return = $AVE_Core->coreModuleTagParse($return);
    }
    return $return;
}
Example #25
0
/**
 * Формирование хлебных крошек
 *
 * @return string ссылка
 */
function get_breadcrumb()
{
    global $AVE_DB;
    $crumb = array();
    $curent_document = get_current_document_id();
    $bread_crumb = "<a href=\"" . get_home_link() . "\">Главная</a>&nbsp;&rarr;&nbsp;";
    if ($curent_document == 1 || $curent_document == 2) {
        $noprint = 1;
    }
    $sql_document = $AVE_DB->Query("SELECT document_title, document_parent FROM " . PREFIX . "_documents WHERE Id = '" . $curent_document . "'", -1, 'doc_' . $curent_document);
    $row_document = $sql_document->fetchrow();
    $current->document_title = $row_document->document_title;
    if (isset($row_document->document_parent) && $row_document->document_parent != 0) {
        $i = 0;
        $current->document_parent = $row_document->document_parent;
        while ($current->document_parent != 0) {
            $sql_doc = $AVE_DB->Query("SELECT Id, document_alias, document_title, document_parent FROM " . PREFIX . "_documents WHERE Id = '" . $current->document_parent . "'", -1, 'doc_' . $current->document_parent);
            $row_doc = $sql_doc->fetchrow();
            $current->document_parent = $row_doc->document_parent;
            if ($row_doc->document_parent == $row_doc->Id) {
                echo "Ошибка! Вы указали в качестве родительского документа текущий документ.<br>";
                $current->document_parent = 1;
            }
            $crumb['document_title'][$i] = $row_doc->document_title;
            $crumb['document_alias'][$i] = $row_doc->document_alias;
            $crumb['Id'][$i] = $row_doc->Id;
            $i++;
        }
        $length = count($crumb['document_title']);
        $crumb['document_title'] = array_reverse($crumb['document_title']);
        $crumb['document_alias'] = array_reverse($crumb['document_alias']);
        $crumb['Id'] = array_reverse($crumb['Id']);
        for ($n = 0; $n < $length; $n++) {
            $url = rewrite_link('index.php?id=' . $crumb['Id'][$n] . '&amp;doc=' . (empty($crumb['document_alias'][$n]) ? prepare_url($crumb['document_title'][$n]) : $crumb['document_alias'][$n]));
            $bread_crumb .= "<a href=\"" . $url . "\"  target=\"_self\">" . $crumb['document_title'][$n] . "</a>&nbsp;&rarr;&nbsp;";
        }
    }
    $bread_crumb .= "<span>" . $current->document_title . "</span>";
    if (!$noprint) {
        return $bread_crumb;
    }
}