function buildTOC(&$text, $chapters, $parents = '') { global $chapters_elem; $i = 0; $toc = '<ol style="list-style:none;">'; foreach ($chapters as $chapter_raw => $subchapters) { $chapter = strip_tags(trim($chapter_raw)); $i++; $elem = $chapters_elem[$chapter_raw]; $level = $parents . $i; $url = $_SERVER["REQUEST_URI"] . "#ch{$level}"; $toc .= "<li><a href=\"{$url}\" title=\"{$chapter}\">{$level}. {$chapter}</a>"; $text = str_replace("<{$elem}>{$chapter_raw}</{$elem}>", "<a name=\"ch{$level}\"></a><{$elem}>{$level}. {$chapter}</{$elem}>", $text); if (count($subchapters) > 0) { $toc .= buildTOC($text, $subchapters, $level . '.'); } $toc .= '</li>'; } $toc .= '</ol>'; return $toc; }
/** * Builds TOC list and implodes anchors in source text * @param string $text source HTML * @param array $toc_data Array of TOC structure generated with getTOC() function * @return string */ function buildTOC(&$text, $toc_data) { global $out; $toc = ''; $toc_list = ''; foreach ($toc_data as $number => $data) { $toc_item = ''; $prefix = cot::$cfg['plugin']['autotoc']['ch_prefix']; $class = cot::$cfg['plugin']['autotoc']['ch_class']; $params = array('title_safe' => trim(strip_tags($data['title'])), 'class' => $class ? $class : 'anchor', 'prefix' => $prefix ? $prefix : 'ch', 'url' => $out['canonical_uri'] . '#' . ($prefix ? $prefix : 'ch') . $number); $params['title_safe'] = preg_replace('/\\s*[\\.]$/i', '', $params['title_safe']); if (cot::$cfg['plugin']['autotoc']['strip_tags']) { $data['title'] = $params['title_safe']; } $tpl_data = array_merge($data, $params); $new_item = cot_rc('autotoc_anchor', $tpl_data); // adding anchors $pos = strpos($text, $data['heading']); $text = substr_replace($text, $new_item, $pos, strlen($data['heading'])); if (count($data['sublist']) > 0) { $tpl_data['sublist'] = buildTOC($text, $data['sublist']); } $params['title_safe'] = preg_replace('/\\s*[:\\.]$/i', '', $params['title_safe']); $tpl_data['title'] = $tpl_data['title_safe'] = $params['title_safe']; $toc_item = cot_rc('autotoc_item', $tpl_data); $toc_list .= $toc_item; } if ($toc_list) { $toc = cot_rc('autotoc_list', array('toc_list' => $toc_list)); } return $toc; }
<?php /* ==================== [BEGIN_COT_EXT] Hooks=page.tags [END_COT_EXT] ==================== */ defined('COT_CODE') or die('Wrong URL'); require_once cot_langfile('autotoc'); require_once cot_incfile('autotoc', 'plug'); require_once cot_incfile('autotoc', 'plug', 'resources'); $elems = explode(',', $cfg['plugin']['autotoc']['ch_elements']); $text = $t->vars['PAGE_TEXT']; $toc = getTOC($text, $elems); if (sizeof($toc)) { $t->assign('PAGE_TOC', trim(buildTOC($text, $toc))); $t->assign('PAGE_TEXT', $text); }