示例#1
0
function preText($s, $prefs)
{
    extract($prefs);
    callback_event('pretext');
    if (gps('rss')) {
        include txpath . '/publish/rss.php';
        exit(rss());
    }
    if (gps('atom')) {
        include txpath . '/publish/atom.php';
        exit(atom());
    }
    // set messy variables
    $out = makeOut('id', 's', 'c', 'q', 'pg', 'p', 'month', 'author');
    // some useful vars for taghandlers, plugins
    $out['request_uri'] = preg_replace("|^https?://[^/]+|i", "", serverSet('REQUEST_URI'));
    $out['qs'] = serverSet('QUERY_STRING');
    // IIS fix
    if (!$out['request_uri'] and serverSet('SCRIPT_NAME')) {
        $out['request_uri'] = serverSet('SCRIPT_NAME') . (serverSet('QUERY_STRING') ? '?' . serverSet('QUERY_STRING') : '');
    }
    // another IIS fix
    if (!$out['request_uri'] and serverSet('argv')) {
        $argv = serverSet('argv');
        $out['request_uri'] = @substr($argv[0], strpos($argv[0], ';') + 1);
    }
    // define the useable url, minus any subdirectories.
    // this is pretty fugly, if anyone wants to have a go at it - dean
    $out['subpath'] = $subpath = preg_quote(preg_replace("/https?:\\/\\/.*(\\/.*)/Ui", "\$1", hu), "/");
    $out['req'] = $req = preg_replace("/^{$subpath}/i", "/", $out['request_uri']);
    $is_404 = 0;
    // if messy vars exist, bypass url parsing
    if (!$out['id'] && !$out['s'] && !(txpinterface == 'css') && !(txpinterface == 'admin')) {
        // return clean URL test results for diagnostics
        if (gps('txpcleantest')) {
            exit(show_clean_test($out));
        }
        extract(chopUrl($req));
        //first we sniff out some of the preset url schemes
        if (strlen($u1)) {
            switch ($u1) {
                case 'atom':
                    include txpath . '/publish/atom.php';
                    exit(atom());
                case 'rss':
                    include txpath . '/publish/rss.php';
                    exit(rss());
                    // urldecode(strtolower(urlencode())) looks ugly but is the only way to
                    // make it multibyte-safe without breaking backwards-compatibility
                // urldecode(strtolower(urlencode())) looks ugly but is the only way to
                // make it multibyte-safe without breaking backwards-compatibility
                case urldecode(strtolower(urlencode(gTxt('section')))):
                    $out['s'] = ckEx('section', $u2) ? $u2 : '';
                    $is_404 = empty($out['s']);
                    break;
                case urldecode(strtolower(urlencode(gTxt('category')))):
                    $out['c'] = ckEx('category', $u2) ? $u2 : '';
                    $is_404 = empty($out['c']);
                    break;
                case urldecode(strtolower(urlencode(gTxt('author')))):
                    $out['author'] = !empty($u2) ? $u2 : '';
                    break;
                    // AuthorID gets resolved from Name further down
                // AuthorID gets resolved from Name further down
                case urldecode(strtolower(urlencode(gTxt('file_download')))):
                    $out['s'] = 'file_download';
                    $out['id'] = !empty($u2) ? $u2 : '';
                    break;
                default:
                    // then see if the prefs-defined permlink scheme is usable
                    switch ($permlink_mode) {
                        case 'section_id_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            } else {
                                $rs = lookupByIDSection($u2, $u1);
                                $out['s'] = @$rs['Section'];
                                $out['id'] = @$rs['ID'];
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            }
                            break;
                        case 'year_month_day_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            } elseif (empty($u4)) {
                                $month = "{$u1}-{$u2}";
                                if (!empty($u3)) {
                                    $month .= "-{$u3}";
                                }
                                if (preg_match('/\\d+-\\d+(?:-\\d+)?/', $month)) {
                                    $out['month'] = $month;
                                    $out['s'] = 'default';
                                } else {
                                    $is_404 = 1;
                                }
                            } else {
                                $when = "{$u1}-{$u2}-{$u3}";
                                $rs = lookupByDateTitle($when, $u4);
                                $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                                $out['s'] = !empty($rs['Section']) ? $rs['Section'] : '';
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            }
                            break;
                        case 'section_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            } else {
                                $rs = lookupByTitleSection($u2, $u1);
                                $out['id'] = @$rs['ID'];
                                $out['s'] = @$rs['Section'];
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            }
                            break;
                        case 'title_only':
                            $rs = lookupByTitle($u1);
                            $out['id'] = @$rs['ID'];
                            $out['s'] = empty($rs['Section']) ? ckEx('section', $u1) : $rs['Section'];
                            $is_404 = empty($out['s']);
                            break;
                        case 'id_title':
                            if (is_numeric($u1) && ckExID($u1)) {
                                $rs = lookupByID($u1);
                                $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                                $out['s'] = !empty($rs['Section']) ? $rs['Section'] : '';
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            } else {
                                # We don't want to miss the /section/ pages
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            }
                            break;
                    }
            }
        } else {
            $out['s'] = 'default';
        }
    } else {
        // Messy mode, but prevent to get the id for file_downloads
        if ($out['id'] && !$out['s']) {
            $rs = lookupByID($out['id']);
            $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
            $out['s'] = !empty($rs['Section']) ? $rs['Section'] : '';
            $is_404 = (empty($out['s']) or empty($out['id']));
        }
    }
    // Resolve AuthorID from Authorname
    if ($out['author']) {
        $name = urldecode(strtolower(urlencode($out['author'])));
        $name = safe_field('name', 'txp_users', "RealName like '" . doSlash($out['author']) . "'");
        if ($name) {
            $out['author'] = $name;
        } else {
            $out['author'] = '';
            $is_404 = true;
        }
    }
    // allow article preview
    if (gps('txpreview') and is_logged_in()) {
        global $nolog;
        $nolog = true;
        $rs = safe_row("ID as id,Section as s", 'textpattern', 'ID = ' . intval(gps('txpreview')) . ' limit 1');
        if ($rs and $is_404) {
            $is_404 = false;
            $out = array_merge($out, $rs);
        }
    }
    // Stats: found or not
    $out['status'] = $is_404 ? '404' : '200';
    $out['pg'] = is_numeric($out['pg']) ? intval($out['pg']) : '';
    $out['id'] = is_numeric($out['id']) ? intval($out['id']) : '';
    if ($out['s'] == 'file_download') {
        // get id of potential filename
        if (!is_numeric($out['id'])) {
            $rs = safe_row("*", "txp_file", "filename='" . doSlash($out['id']) . "' and status = 4");
        } else {
            $rs = safe_row("*", "txp_file", 'id=' . intval($out['id']) . ' and status = 4');
        }
        $out = $rs ? array_merge($out, $rs) : array('s' => 'file_download', 'file_error' => 404);
        return $out;
    }
    if (!$is_404) {
        $out['s'] = empty($out['s']) ? 'default' : $out['s'];
    }
    $s = $out['s'];
    $id = $out['id'];
    // hackish
    global $is_article_list;
    if (empty($id)) {
        $is_article_list = true;
    }
    // by this point we should know the section, so grab its page and css
    $rs = safe_row("page, css", "txp_section", "name = '" . doSlash($s) . "' limit 1");
    $out['page'] = @$rs['page'];
    $out['css'] = @$rs['css'];
    if (is_numeric($id) and !$is_404) {
        $a = safe_row('*, unix_timestamp(Posted) as uPosted, unix_timestamp(Expires) as uExpires, unix_timestamp(LastMod) as uLastMod', 'textpattern', 'ID=' . intval($id) . (gps('txpreview') ? '' : ' and Status in (4,5)'));
        if ($a) {
            $Posted = $a['Posted'];
            $out['id_keywords'] = $a['Keywords'];
            $out['id_author'] = $a['AuthorID'];
            populateArticleData($a);
            $uExpires = $a['uExpires'];
            if ($uExpires and time() > $uExpires and !$publish_expired_articles) {
                $out['status'] = '410';
            }
            if ($np = getNextPrev($id, $Posted, $s)) {
                $out = array_merge($out, $np);
            }
        }
    }
    $out['path_from_root'] = rhu;
    // these are deprecated as of 1.0
    $out['pfr'] = rhu;
    // leaving them here for plugin compat
    $out['path_to_site'] = $path_to_site;
    $out['permlink_mode'] = $permlink_mode;
    $out['sitename'] = $sitename;
    return $out;
}
示例#2
0
function preText($s, $prefs)
{
    extract($prefs);
    if (gps('rss')) {
        include txpath . '/publish/rss.php';
        exit(rss());
    }
    if (gps('atom')) {
        include txpath . '/publish/atom.php';
        exit(atom());
    }
    // set messy variables
    $out = makeOut('id', 's', 'c', 'q', 'pg', 'p', 'month');
    // if messy vars exist, bypass url parsing
    if (!$out['id'] && !$out['s']) {
        // define the useable url, minus any subdirectories.
        // this is pretty fugly, if anyone wants to have a go at it - dean
        $subpath = preg_quote(preg_replace("/http:\\/\\/.*(\\/.*)/Ui", "\$1", hu), "/");
        $req = preg_replace("/^{$subpath}/i", "/", serverSet('REQUEST_URI'));
        extract(chopUrl($req));
        //first we sniff out some of the preset url schemes
        if (!empty($u1)) {
            switch ($u1) {
                case 'atom':
                    include txpath . '/publish/atom.php';
                    exit(atom());
                case 'rss':
                    include txpath . '/publish/rss.php';
                    exit(rss());
                case strtolower(gTxt('section')):
                    $out['s'] = ckEx('section', $u2) ? $u2 : 'default';
                    break;
                case strtolower(gTxt('category')):
                    $out['c'] = ckEx('category', $u2) ? $u2 : '';
                    break;
                case urlencode(strtolower(gTxt('author'))):
                    $author_name = !empty($u2) ? urldecode($u2) : '';
                    $out['author'] = safe_field('name', 'txp_users', "RealName like '{$author_name}'");
                    break;
                case strtolower(gTxt('file_download')):
                    $out['s'] = 'file_download';
                    $out['id'] = !empty($u2) ? $u2 : '';
                    break;
                case 'p':
                    $out['p'] = is_numeric($u2) ? $u2 : '';
                    break;
                default:
                    // then see if the prefs-defined permlink scheme is usable
                    switch ($permlink_mode) {
                        case 'section_id_title':
                            $out['s'] = ckEx('section', $u1) ? $u1 : 'default';
                            $out['id'] = is_numeric($u2) && ckExID($u2) ? $u2 : '';
                            break;
                        case 'year_month_day_title':
                            if (empty($u4)) {
                                $out['month'] = "{$u1}-{$u2}";
                                if (!empty($u3)) {
                                    $out['month'] .= "-{$u3}";
                                }
                                $out['s'] = 'default';
                            } else {
                                $when = date("Y-m-d", strtotime("{$u1}-{$u2}-{$u3}") + $timeoffset);
                                $rs = lookupByDateTitle($when, $u4);
                                $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                                $out['s'] = !empty($rs['Section']) ? $rs['Section'] : '';
                            }
                            break;
                        case 'section_title':
                            $rs = lookupByTitleSection($u2, $u1);
                            $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                            $out['s'] = ckEx('section', $u1) ? $u1 : 'default';
                            break;
                        case 'title_only':
                            $rs = lookupByTitle($u1);
                            $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                            $out['s'] = !empty($rs['Section']) ? $rs['Section'] : ckEx('section', $u1) ? $u1 : 'default';
                            break;
                        case 'id_title':
                            if (is_numeric($u1) && ckExID($u1)) {
                                $rs = lookupByID($u1);
                                $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                                $out['s'] = !empty($rs['Section']) ? $rs['Section'] : 'default';
                            } else {
                                # We don't want to miss the /section/ pages
                                $out['s'] = ckEx('section', $u1) ? $u1 : 'default';
                            }
                            break;
                    }
            }
        } else {
            $out['s'] = 'default';
        }
    } else {
        // Messy mode, but prevent to get the id for file_downloads
        if ($out['id'] && !$out['s']) {
            $out['s'] = safe_field('section', 'textpattern', "ID='" . doSlash($out['id']) . "'");
        }
    }
    if ($out['s'] == 'file_download') {
        // get id of potential filename
        if (!is_numeric($out['id'])) {
            $rs = safe_row("*", "txp_file", "filename='" . $out['id'] . "'");
        } else {
            $rs = safe_row("*", "txp_file", "id='" . $out['id'] . "'");
        }
        $out = $rs ? array_merge($out, $rs) : array('s' => 'file_download', 'file_error' => 404);
        return $out;
    }
    $out['s'] = empty($out['s']) ? 'default' : $out['s'];
    $s = $out['s'];
    $id = $out['id'];
    // hackish
    if (empty($id)) {
        $GLOBALS['is_article_list'] = true;
    }
    // by this point we should know the section, so grab its page and css
    $rs = safe_row("*", "txp_section", "name = '{$s}' limit 1");
    $out['page'] = @$rs['page'];
    $out['css'] = @$rs['css'];
    if (is_numeric($id)) {
        $idrs = safe_row("Posted, AuthorID, Keywords", "textpattern", "ID={$id}");
        extract($idrs);
        if ($np = getNextPrev($id, $Posted, $s)) {
            $out = array_merge($out, $np);
        }
        $out['id_keywords'] = $Keywords;
        $out['id_author'] = get_author_name($AuthorID);
    }
    $out['path_from_root'] = $path_from_root;
    // these are deprecated as of 1.0
    $out['pfr'] = $path_from_root;
    // leaving them here for plugin compat
    $out['path_to_site'] = $path_to_site;
    $out['permlink_mode'] = $permlink_mode;
    $out['sitename'] = htmlspecialchars($sitename);
    return $out;
}
示例#3
0
function preText($s, $prefs)
{
    extract($prefs);
    callback_event('pretext');
    if (gps('rss')) {
        include txpath . '/publish/rss.php';
        exit(rss());
    }
    if (gps('atom')) {
        include txpath . '/publish/atom.php';
        exit(atom());
    }
    // set messy variables
    $out = makeOut('id', 's', 'c', 'q', 'pg', 'p', 'month', 'author');
    // some useful vars for taghandlers, plugins
    $out['request_uri'] = serverSet('REQUEST_URI');
    $out['qs'] = serverSet('QUERY_STRING');
    // IIS - can someone confirm whether or not this works?
    if (!$out['request_uri'] and $argv = serverSet('argv')) {
        $out['request_uri'] = @substr($argv[0], strpos($argv[0], ';' + 1));
    }
    // define the useable url, minus any subdirectories.
    // this is pretty fugly, if anyone wants to have a go at it - dean
    $out['subpath'] = $subpath = preg_quote(preg_replace("/http:\\/\\/.*(\\/.*)/Ui", "\$1", hu), "/");
    $out['req'] = $req = preg_replace("/^{$subpath}/i", "/", serverSet('REQUEST_URI'));
    $is_404 = 0;
    // if messy vars exist, bypass url parsing
    if (!$out['id'] && !$out['s']) {
        extract(chopUrl($req));
        //first we sniff out some of the preset url schemes
        if (!empty($u1)) {
            switch ($u1) {
                case 'atom':
                    include txpath . '/publish/atom.php';
                    exit(atom());
                case 'rss':
                    include txpath . '/publish/rss.php';
                    exit(rss());
                    // urldecode(strtolower(urlencode())) looks ugly but is the only way to
                    // make it multibyte-safe without breaking backwards-compatibility
                // urldecode(strtolower(urlencode())) looks ugly but is the only way to
                // make it multibyte-safe without breaking backwards-compatibility
                case urldecode(strtolower(urlencode(gTxt('section')))):
                    $out['s'] = ckEx('section', $u2) ? $u2 : '';
                    break;
                case urldecode(strtolower(urlencode(gTxt('category')))):
                    $out['c'] = ckEx('category', $u2) ? $u2 : '';
                    break;
                case urldecode(strtolower(urlencode(gTxt('author')))):
                    $out['author'] = !empty($u2) ? $u2 : '';
                    break;
                    // AuthorID gets resolved from Name further down
                // AuthorID gets resolved from Name further down
                case urldecode(strtolower(urlencode(gTxt('file_download')))):
                    $out['s'] = 'file_download';
                    $out['id'] = !empty($u2) ? $u2 : '';
                    break;
                case 'p':
                    $out['p'] = is_numeric($u2) ? $u2 : '';
                    break;
                default:
                    // then see if the prefs-defined permlink scheme is usable
                    switch ($permlink_mode) {
                        case 'section_id_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            } else {
                                $rs = ckExID($u2);
                                $out['s'] = @$rs['Section'];
                                $out['id'] = @$rs['ID'];
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            }
                            break;
                        case 'year_month_day_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            } elseif (empty($u4)) {
                                $month = "{$u1}-{$u2}";
                                if (!empty($u3)) {
                                    $month .= "-{$u3}";
                                }
                                if (preg_match('/\\d+-\\d+(?:-\\d+)?/', $month)) {
                                    $out['month'] = $month;
                                    $out['s'] = 'default';
                                } else {
                                    $is_404 = 1;
                                }
                            } else {
                                $when = "{$u1}-{$u2}-{$u3}";
                                $rs = lookupByDateTitle($when, $u4);
                                $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                                $out['s'] = !empty($rs['Section']) ? $rs['Section'] : '';
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            }
                            break;
                        case 'section_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            } else {
                                $rs = lookupByTitleSection($u2, $u1);
                                $out['id'] = @$rs['ID'];
                                $out['s'] = @$rs['Section'];
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            }
                            break;
                        case 'title_only':
                            $rs = lookupByTitle($u1);
                            $out['id'] = @$rs['ID'];
                            $out['s'] = empty($rs['Section']) ? ckEx('section', $u1) : $rs['Section'];
                            $is_404 = empty($out['s']);
                            break;
                        case 'id_title':
                            if (is_numeric($u1) && ckExID($u1)) {
                                $rs = lookupByID($u1);
                                $out['id'] = !empty($rs['ID']) ? $rs['ID'] : '';
                                $out['s'] = !empty($rs['Section']) ? $rs['Section'] : '';
                                $is_404 = (empty($out['s']) or empty($out['id']));
                            } else {
                                # We don't want to miss the /section/ pages
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                                $is_404 = empty($out['s']);
                            }
                            break;
                    }
            }
        } else {
            $out['s'] = 'default';
        }
    } else {
        // Messy mode, but prevent to get the id for file_downloads
        if ($out['id'] && !$out['s']) {
            $out['s'] = safe_field('section', 'textpattern', "ID='" . doSlash($out['id']) . "'");
        }
    }
    // Resolve AuthorID from Authorname
    if ($out['author']) {
        $out['author'] = safe_field('name', 'txp_users', "RealName like '" . doSlash($out['author']) . "'");
    }
    // Stats: found or not
    $out['status'] = $is_404 ? '404' : '200';
    if ($out['s'] == 'file_download') {
        // get id of potential filename
        if (!is_numeric($out['id'])) {
            $rs = safe_row("*", "txp_file", "filename='" . doSlash($out['id']) . "'");
        } else {
            $rs = safe_row("*", "txp_file", "id='" . intval($out['id']) . "'");
        }
        $out = $rs ? array_merge($out, $rs) : array('s' => 'file_download', 'file_error' => 404);
        return $out;
    }
    if (!$is_404) {
        $out['s'] = empty($out['s']) ? 'default' : $out['s'];
    }
    $s = $out['s'];
    $id = $out['id'];
    // hackish
    if (empty($id)) {
        $GLOBALS['is_article_list'] = true;
    }
    // by this point we should know the section, so grab its page and css
    $rs = safe_row("*", "txp_section", "name = '" . doSlash($s) . "' limit 1");
    $out['page'] = @$rs['page'];
    // Remove the below line if nothing breaks
    // 		$out['css']  = @$rs['css'];
    if (is_numeric($id)) {
        $idrs = safe_row("Posted, AuthorID, Keywords", "textpattern", "ID=" . doSlash($id));
        extract($idrs);
        if ($np = getNextPrev($id, $Posted, $s)) {
            $out = array_merge($out, $np);
        }
        $out['id_keywords'] = $Keywords;
        $out['id_author'] = get_author_name($AuthorID);
    }
    $out['path_from_root'] = $path_from_root;
    // these are deprecated as of 1.0
    $out['pfr'] = $path_from_root;
    // leaving them here for plugin compat
    $out['path_to_site'] = $path_to_site;
    $out['permlink_mode'] = $permlink_mode;
    $out['sitename'] = htmlspecialchars($sitename);
    return $out;
}
 function _textpattern()
 {
     global $plugins_ver, $pretext, $prefs, $plugin_callback;
     $this->debug('Plugin: ' . $this->plugin_name . ' - ' . $plugins_ver[$this->plugin_name]);
     $this->debug('Function: ' . __FUNCTION__ . '()');
     // URI
     $req = $pretext['req'];
     $req = preg_replace('%\\?[^\\/]+$%', '', $req);
     $this->debug('Request URI: ' . $req);
     $uri = explode('/', trim($req, '/'));
     // The number of components comes in useful when determining the best partial match.
     $uri_component_count = count($uri);
     // Permanent links
     $permlinks = $this->get_all_permlinks(1);
     // Force Textpattern and tags to use messy URLs - these are easier to
     // find in regex
     $this->set_permlink_mode();
     if (count($permlinks)) {
         // We also want to match the front page of the site (for page numbers / feeds etc..).
         // Add a permlinks rule which will do that.
         $permlinks['default'] = array('components' => array(), 'settings' => array('pl_name' => 'gbp_permanent_links_default', 'pl_precedence' => '', 'pl_preview' => '/', 'con_section' => '', 'con_category' => '', 'des_section' => '', 'des_category' => '', 'des_permlink' => '', 'des_feed' => '', 'des_location' => '', 'des_page' => ''));
         // Extend the pretext_replacement scope outside the foreach permlink loop
         $pretext_replacement = NULL;
         foreach ($permlinks as $id => $pl) {
             // Extract the permlink settings
             $pl_settings = $pl['settings'];
             extract($pl_settings);
             $this->debug('Permlink name: ' . $pl_name);
             $this->debug('Permlink id: ' . $id);
             $this->debug('Preview: ' . $pl_preview);
             $pl_components = $pl['components'];
             // URI components
             $uri_components = $uri;
             $this->debug('PL component count: ' . count($pl_components));
             $this->debug('URL component count: ' . count($uri_components));
             $date = false;
             $title_page_feed = false;
             foreach ($pl_components as $pl_c) {
                 // Are we expecting a date component? If so the number of pl and uri components won't match
                 if ($pl_c['type'] == 'date') {
                     $date = true;
                 } else {
                     if (in_array($pl_c['type'], array('title', 'page', 'feed'))) {
                         $title_page_feed = true;
                     }
                 }
             }
             if (!$title_page_feed) {
                 // If there isn't a title, page or feed component then append a special type for cleaver partial matching
                 $pl_components[] = array('type' => 'title_page_feed', 'prefix' => '', 'suffix' => '', 'regex' => '', 'text' => '');
             }
             // Exit early if there are more URL components than PL components,
             // taking into account whether there is a data component
             if (!$uri_components[0] || count($uri_components) > count($pl_components) + ($date ? 2 : 0)) {
                 $this->debug('More URL components than PL components');
                 continue;
             }
             // Reset pretext_replacement as we are about to start another comparison
             $pretext_replacement = array('permlink_id' => $id);
             // Reset the article context string
             $context = array();
             unset($context_str);
             if (!empty($des_section)) {
                 $context[] = "`Section` = '{$des_section}'";
             }
             if (!empty($des_category)) {
                 $context[] = "(`Category1` = '{$des_category}' OR `Category2` = '{$des_category}')";
             }
             $context_str = count($context) > 0 ? 'and ' . join(' and ', $context) : '';
             // Assume there is no match
             $partial_match = false;
             $cleaver_partial_match = false;
             // Loop through the permlink components
             foreach ($pl_components as $pl_c_index => $pl_c) {
                 // Assume there is no match
                 $match = false;
                 // Check to see if there are still URI components to be checked.
                 if (count($uri_components)) {
                     // Get the next component.
                     $uri_c = array_shift($uri_components);
                 } else {
                     if (!$title_page_feed && count($pl_components) - 1 == $uri_component_count) {
                         // If we appended a title_page_feed component earlier and permlink and URI components
                         // counts are equal, we must of finished checking this permlink, and it matches so break.
                         $match = true;
                         break;
                     } else {
                         // If there are no more URI components then we have a partial match.
                         // Store the partial match data unless there has been a preceding permlink with the
                         // same number of components, as permlink have already been sorted by precedence.
                         if (!array_key_exists($uri_component_count, $this->partial_matches)) {
                             $this->partial_matches[$uri_component_count] = $pretext_replacement;
                         }
                         // Unset pretext_replacement as changes could of been made in a preceding component
                         unset($pretext_replacement);
                         // Break early form the foreach permlink components loop.
                         $partial_match = true;
                         break;
                     }
                 }
                 // Extract the permlink components.
                 extract($pl_c);
                 // If it's a date, grab and combine the next two URI components.
                 if ($type == 'date') {
                     $uri_c .= '/' . array_shift($uri_components) . '/' . array_shift($uri_components);
                 }
                 // Decode the URL
                 $uri_c = urldecode($uri_c);
                 // Always check the type unless the prefix or suffix aren't there
                 $check_type = true;
                 // Check prefix
                 if ($prefix && $this->pref('show_prefix')) {
                     $sanitized_prefix = urldecode($this->encode_url($prefix));
                     if (($pos = strpos($uri_c, $sanitized_prefix)) === false || $pos != 0) {
                         $check_type = false;
                         $this->debug('Can\'t find prefix: ' . $prefix);
                     } else {
                         // Check passed, remove prefix ready for the next check
                         $uri_c = substr_replace($uri_c, '', 0, strlen($sanitized_prefix));
                     }
                 }
                 // Check suffix
                 if ($check_type && $suffix && $this->pref('show_suffix')) {
                     $sanitized_suffix = urldecode($this->encode_url($suffix));
                     if (($pos = strrpos($uri_c, $sanitized_suffix)) === false) {
                         $check_type = false;
                         $this->debug('Can\'t find suffix: ' . $suffix);
                     } else {
                         // Check passed, remove suffix ready for the next check
                         $uri_c = substr_replace($uri_c, '', $pos, strlen($sanitized_suffix));
                     }
                 }
                 // Both the prefix and suffix settings have passed
                 if ($check_type) {
                     $this->debug('Checking if "' . $uri_c . '" is of type "' . $type . '"');
                     $uri_c = doSlash($uri_c);
                     //
                     if ($prefs['permalink_title_format']) {
                         $mt_search = array('/_/', '/\\.html$/');
                         $mt_replace = array('-', '');
                     } else {
                         $mt_search = array('/(?:^|_)(.)/e', '/\\.html$/');
                         $mt_replace = array("strtoupper('\\1')", '');
                     }
                     $mt_uri_c = $this->pref('redirect_mt_style_links') ? preg_replace($mt_search, $mt_replace, $uri_c) : '';
                     // Compare based on type
                     switch ($type) {
                         case 'section':
                             if ($rs = safe_row('name', 'txp_section', "(`name` like '{$uri_c}' or `name` like '{$mt_uri_c}') limit 1")) {
                                 $this->debug('Section name: ' . $rs['name']);
                                 $pretext_replacement['s'] = $rs['name'];
                                 $context[] = "`Section` = '{$rs['name']}'";
                                 $match = true;
                             }
                             break;
                         case 'category':
                             if ($rs = safe_row('name', 'txp_category', "(`name` like '{$uri_c}' or `name` like '{$mt_uri_c}') and `type` = 'article' limit 1")) {
                                 $this->debug('Category name: ' . $rs['name']);
                                 $pretext_replacement['c'] = $rs['name'];
                                 $context[] = "(`Category1` = '{$rs['name']}' OR `Category2` = '{$uri_c}')";
                                 $match = true;
                             }
                             break;
                         case 'title':
                             if ($rs = safe_row('url_title', 'textpattern', "(`url_title` like '{$uri_c}' or `url_title` like '{$mt_uri_c}') {$context_str} and `Status` >= 4 limit 1")) {
                                 $this->debug('URL Title: ' . $rs['url_title']);
                                 $mt_redirect = $uri_c != $mt_uri_c;
                                 $pretext_replacement['url_title'] = $rs['url_title'];
                                 $match = true;
                             }
                             break;
                         case 'id':
                             if ($rs = safe_row('ID, Posted', 'textpattern', "`ID` = '{$uri_c}' {$context_str} and `Status` >= 4 limit 1")) {
                                 $pretext_replacement['id'] = $rs['ID'];
                                 $pretext_replacement['Posted'] = $rs['Posted'];
                                 $pretext['numPages'] = 1;
                                 $pretext['is_article_list'] = false;
                                 $match = true;
                             }
                             break;
                         case 'author':
                             if ($author = safe_field('name', 'txp_users', "RealName like '{$uri_c}' limit 1")) {
                                 $pretext_replacement['author'] = $author;
                                 $context[] = "`AuthorID` = '{$author}'";
                                 $match = true;
                             }
                             break;
                         case 'login':
                             if ($author = safe_field('name', 'txp_users', "name like '{$uri_c}' limit 1")) {
                                 $pretext_replacement['author'] = $author;
                                 $context[] = "`AuthorID` = '{$author}'";
                                 $match = true;
                             }
                             break;
                         case 'custom':
                             $custom_options = array_values(array_map(array($this, "encode_url"), safe_column("custom_{$custom}", 'textpattern', "custom_{$custom} != ''")));
                             if ($this->pref('force_lowercase_urls')) {
                                 $custom_options = array_map("strtolower", $custom_options);
                             }
                             if (in_array($uri_c, $custom_options)) {
                                 $match = true;
                             }
                             break;
                         case 'date':
                             if (preg_match('/^\\d{4}\\/\\d{2}\\/\\d{2}$/', $uri_c)) {
                                 $pretext_replacement['date'] = str_replace('/', '-', $uri_c);
                                 $match = true;
                             }
                             break;
                         case 'year':
                             if (preg_match('/^\\d{4}$/', $uri_c)) {
                                 $pretext_replacement['year'] = $uri_c;
                                 $match = true;
                             }
                             break;
                         case 'month':
                         case 'day':
                             if (preg_match('/^\\d{2}$/', $uri_c)) {
                                 $pretext_replacement[$type] = $uri_c;
                                 $match = true;
                             }
                             break;
                         case 'page':
                             if (is_numeric($uri_c)) {
                                 $pretext_replacement['pg'] = $uri_c;
                                 $match = true;
                             }
                             break;
                         case 'feed':
                             if (in_array($uri_c, array('rss', 'atom'))) {
                                 $pretext_replacement[$uri_c] = 1;
                                 $match = true;
                             }
                             break;
                         case 'search':
                             $pretext_replacement['q'] = $uri_c;
                             $match = true;
                             break;
                         case 'text':
                             if ($this->encode_url($text) == $uri_c) {
                                 $match = true;
                                 $pretext_replacement["permlink_text_{$name}"] = $uri_c;
                             }
                             break;
                         case 'regex':
                             // Check to see if regex is valid without outputting error messages.
                             ob_start();
                             preg_match($regex, $uri_c, $regex_matches);
                             $is_valid_regex = !ob_get_clean();
                             if ($is_valid_regex && @$regex_matches[0]) {
                                 $match = true;
                                 $pretext_replacement["permlink_regex_{$name}"] = $regex_matches[0];
                             }
                             break;
                     }
                     // switch type end
                     // Update the article context string
                     $context_str = count($context) > 0 ? 'and ' . join(' and ', $context) : '';
                     $this->debug($match == true ? 'YES' : 'NO');
                     if (!$match && !$cleaver_partial_match && $this->pref('use_cleaver_partial_matches')) {
                         // There hasn't been a match or a complete cleaver partial match. Lets try to be cleaver and
                         // check to see if this component is either a title, page or a feed. This makes it more probable
                         // a successful match for a given permlink rule occurs.
                         $this->debug('Checking if "' . $uri_c . '" is of type "title_page_feed"');
                         if ($type != 'title' && ($url_title = safe_field('url_title', 'textpattern', "`url_title` like '{$uri_c}' {$context_str} and `Status` >= 4 limit 1"))) {
                             $pretext_replacement['url_title'] = $url_title;
                             $pretext['numPages'] = 1;
                             $pretext['is_article_list'] = false;
                             $cleaver_partial_match = true;
                         } else {
                             if ($this->pref('clean_page_archive_links') && $type != 'page' && is_numeric($uri_c)) {
                                 $pretext_replacement['pg'] = $uri_c;
                                 $cleaver_partial_match = true;
                             } else {
                                 if ($type != 'feed' && in_array($uri_c, array('rss', 'atom'))) {
                                     $pretext_replacement[$uri_c] = 1;
                                     $cleaver_partial_match = true;
                                 }
                             }
                         }
                         $this->debug($cleaver_partial_match == true ? 'YES' : 'NO');
                         if ($cleaver_partial_match) {
                             $this->cleaver_partial_match = $pretext_replacement;
                             // Unset pretext_replacement as changes could of been made in a preceding component
                             unset($pretext_replacement);
                             $cleaver_partial_match = true;
                             continue 2;
                         }
                     }
                 }
                 // check type end
                 // Break early if the component doesn't match, as there is no point continuing
                 if ($match == false) {
                     // Unset pretext_replacement as changes could of been made in a preceding component
                     unset($pretext_replacement);
                     break;
                 }
             }
             // foreach permlink component end
             if (!isset($pretext_replacement['id'])) {
                 if (isset($pretext_replacement['url_title'])) {
                     if (isset($pretext_replacement['date'])) {
                         $date_val = $pretext_replacement['date'];
                     } else {
                         if (isset($pretext_replacement['year'])) {
                             $date_val = $pretext_replacement['year'];
                             if (isset($pretext_replacement['month'])) {
                                 $date_val .= '-' . $pretext_replacement['month'];
                                 if (isset($pretext_replacement['day'])) {
                                     $date_val .= '-' . $pretext_replacement['day'];
                                 }
                             }
                         }
                     }
                     if (isset($date_val)) {
                         $context_str .= " and `Posted` like '{$date_val}%'";
                     }
                     if ($rs = safe_row('ID, Posted', 'textpattern', "`url_title` like '{$pretext_replacement['url_title']}' {$context_str} and `Status` >= 4 order by `Posted` desc limit 1")) {
                         if (isset($date_val)) {
                             $this->debug('Found date and title-based match.');
                         } else {
                             $this->debug('Found title-based match.');
                         }
                         $pretext_replacement['id'] = $rs['ID'];
                         $pretext_replacement['Posted'] = $rs['Posted'];
                         $pretext['numPages'] = 1;
                         $pretext['is_article_list'] = false;
                     } else {
                         $match = false;
                         unset($pretext_replacement);
                     }
                 }
             }
             if ($match || $partial_match || $cleaver_partial_match) {
                 // Extract the settings for this permlink
                 @extract($permlinks[$pretext_replacement['permlink_id']]['settings']);
                 // Check the permlink section and category conditions
                 if (!empty($con_section) && $con_section != @$pretext_replacement['s'] || !empty($con_category) && $con_category != @$pretext_replacement['c']) {
                     $this->debug('Permlink conditions failed');
                     if (@$con_section) {
                         $this->debug('con_section = ' . $con_section);
                     }
                     if (@$con_category) {
                         $this->debug('con_category = ' . $con_category);
                     }
                     unset($pretext_replacement);
                 } else {
                     if ($match && isset($pretext_replacement)) {
                         $this->debug('We have a match!');
                     } else {
                         if ($partial_match && count($this->partial_matches)) {
                             $this->debug('We have a \'partial match\'');
                         } else {
                             if ($cleaver_partial_match && isset($cleaver_partial_match)) {
                                 $this->debug('We have a \'cleaver partial match\'');
                             } else {
                                 $this->debug('Error: Can\'t determine the correct type match');
                                 // This permlink has failed, continue execution of the foreach permlinks loop
                                 unset($pretext_replacement);
                             }
                         }
                     }
                 }
             }
             // We have a match
             if (@$pretext_replacement) {
                 break;
             }
         }
         // foreach permlinks end
         // If there is no match restore the most likely partial match. Sorted by number of components and then precedence
         if (!@$pretext_replacement && count($this->partial_matches)) {
             $pt_slice = array_slice($this->partial_matches, -1);
             $pretext_replacement = array_shift($pt_slice);
         }
         unset($this->partial_matches);
         // Restore the cleaver_partial_match if there is no other matches
         if (!@$pretext_replacement && $this->cleaver_partial_match) {
             $pretext_replacement = $this->cleaver_partial_match;
         }
         unset($this->cleaver_partial_match);
         // Extract the settings for this permlink
         @extract($permlinks[$pretext_replacement['permlink_id']]['settings']);
         // If pretext_replacement is still set here then we have a match
         if (@$pretext_replacement) {
             $this->debug('Pretext Replacement ' . print_r($pretext_replacement, 1));
             if (!empty($des_section)) {
                 $pretext_replacement['s'] = $des_section;
             }
             if (!empty($des_category)) {
                 $pretext_replacement['c'] = $des_category;
             }
             if (!empty($des_feed)) {
                 $pretext_replacement[$des_feed] = 1;
             }
             if (@$pretext_replacement['id'] && @$pretext_replacement['Posted']) {
                 if ($np = getNextPrev($pretext_replacement['id'], $pretext_replacement['Posted'], @$pretext_replacement['s'])) {
                     $pretext_replacement = array_merge($pretext_replacement, $np);
                 }
             }
             unset($pretext_replacement['Posted']);
             // If there is a match then we most set the http status correctly as txp's pretext might set it to 404
             $pretext_replacement['status'] = '200';
             // Store the orginial HTTP status code
             // We might need to log the page hit if it equals 404
             $orginial_status = $pretext['status'];
             // Txp only looks at the month, but due to how we phase the month we can manipulate the sql to our needs
             if (array_key_exists('date', $pretext_replacement)) {
                 $pretext_replacement['month'] = $pretext_replacement['date'];
                 unset($pretext_replacement['date']);
             } else {
                 if (array_key_exists('year', $pretext_replacement) || array_key_exists('month', $pretext_replacement) || array_key_exists('day', $pretext_replacement)) {
                     $month = '';
                     $month .= array_key_exists('year', $pretext_replacement) ? $pretext_replacement['year'] . '-' : '____-';
                     $month .= array_key_exists('month', $pretext_replacement) ? $pretext_replacement['month'] . '-' : '__-';
                     $month .= array_key_exists('day', $pretext_replacement) ? $pretext_replacement['day'] . ' ' : '__ ';
                     $pretext_replacement['month'] = $month;
                     unset($pretext_replacement['year']);
                     unset($pretext_replacement['day']);
                 }
             }
             // Section needs to be defined so we can always get a page template.
             if (!array_key_exists('s', $pretext_replacement)) {
                 if (!@$pretext_replacement['id']) {
                     $pretext_replacement['s'] = 'default';
                 } else {
                     $pretext_replacement['s'] = safe_field('Section', 'textpattern', 'ID = ' . $pretext_replacement['id']);
                 }
             }
             // Set the css and page template, otherwise we get an unknown section
             $section_settings = safe_row('css, page', 'txp_section', "name = '{$pretext_replacement['s']}' limit 1");
             $pretext_replacement['page'] = @$des_page ? $des_page : $section_settings['page'];
             $pretext_replacement['css'] = $section_settings['css'];
             $this->matched_permlink = $pretext_replacement;
             global $permlink_mode;
             if (in_array($prefs['permlink_mode'], array('id_title', 'section_id_title')) && @$pretext_replacement['pg'] && !@$pretext_replacement['id']) {
                 $pretext_replacement['id'] = '';
                 $pretext_replacement['is_article_list'] = true;
             }
             // Merge pretext_replacement with pretext
             $pretext = array_merge($pretext, $pretext_replacement);
             if (is_numeric(@$pretext['id'])) {
                 $a = safe_row('*, unix_timestamp(Posted) as uPosted, unix_timestamp(Expires) as uExpires, unix_timestamp(LastMod) as uLastMod', 'textpattern', 'ID=' . intval($pretext['id']) . ' and Status >= 4');
                 populateArticleData($a);
             }
             // Export required values to the global namespace
             foreach (array('id', 's', 'c', 'pg', 'is_article_list', 'prev_id', 'prev_title', 'next_id', 'next_title', 'css') as $key) {
                 if (array_key_exists($key, $pretext)) {
                     $GLOBALS[$key] = $pretext[$key];
                 }
             }
             if (count($this->matched_permlink) || @$mt_redirect) {
                 $pl_index = $pretext['permlink_id'];
                 if (!@$mt_redirect || !$this->pref('redirect_mt_style_links')) {
                     $pl = $this->get_permlink($pretext['permlink_id']);
                     $pl_index = @$pl['settings']['des_permlink'];
                 }
                 if (@$pretext['id'] && $pl_index) {
                     if (count($this->get_permlink($pl_index)) > 0) {
                         ob_clean();
                         global $siteurl;
                         $rs = safe_row('*, ID as thisid, unix_timestamp(Posted) as posted', 'textpattern', "ID = '{$pretext['id']}'");
                         $host = rtrim(str_replace(rtrim(doStrip($pretext['subpath']), '/'), '', hu), '/');
                         $this->redirect($host . $this->_permlinkurl($rs, PERMLINKURL, $pl_index), $this->pref('permlink_redirect_http_status'));
                     }
                 } else {
                     if ($url = @$pl['settings']['des_location']) {
                         ob_clean();
                         $this->redirect($url, $this->pref('url_redirect_http_status'));
                     }
                 }
             }
             if (@$pretext['rss']) {
                 if (@$pretext['s']) {
                     $_POST['section'] = $pretext['s'];
                 }
                 if (@$pretext['c']) {
                     $_POST['category'] = $pretext['c'];
                 }
                 ob_clean();
                 include txpath . '/publish/rss.php';
                 exit(rss());
             }
             if (@$pretext['atom']) {
                 if (@$pretext['s']) {
                     $_POST['section'] = $pretext['s'];
                 }
                 if (@$pretext['c']) {
                     $_POST['category'] = $pretext['c'];
                 }
                 ob_clean();
                 include txpath . '/publish/atom.php';
                 exit(atom());
             }
             $this->debug('Pretext ' . print_r($pretext, 1));
         } else {
             $this->debug('NO CHANGES MADE');
         }
         // Log this page hit
         if (@$orginial_status == 404) {
             log_hit($pretext['status']);
         }
         // Start output buffering and pseudo callback to textpattern_end
         ob_start(array(&$this, '_textpattern_end_callback'));
         // TxP 4.0.5 (r2436) introduced the textpattern_end callback making the following redundant
         $version = array_sum(array_map(create_function('$line', 'if (preg_match(\'/^\\$' . 'LastChangedRevision: (\\w+) \\$/\', $line, $match)) return $match[1];'), @file(txpath . '/publish.php')));
         if ($version >= '2436') {
             return;
         }
         // Remove the plugin callbacks which have already been called
         function filter_callbacks($c)
         {
             if ($c['event'] != 'textpattern') {
                 return true;
             }
             if (@$c['function'][0]->plugin_name == 'gbp_permanent_links' && @$c['function'][1] == '_textpattern') {
                 $GLOBALS['gbp_found_self'] = true;
                 return false;
             }
             return @$GLOBALS['gbp_found_self'];
         }
         $plugin_callback = array_filter($plugin_callback, 'filter_callbacks');
         unset($GLOBALS['gbp_found_self']);
         // Re-call textpattern
         textpattern();
         // Call custom textpattern_end callback
         $this->_textpattern_end();
         // textpattern() has run, kill the connection
         die;
     }
 }
示例#5
0
function preText($s, $prefs)
{
    extract($prefs);
    if (gps('rss')) {
        include txpath . '/publish/rss.php';
        exit(rss());
    }
    if (gps('atom')) {
        include txpath . '/publish/atom.php';
        exit(atom());
    }
    if (!$s) {
        $s = gps('s');
    }
    $id = gps('id');
    $id = !$id && $url_mode ? frompath() : $id;
    // hackish
    if (empty($id)) {
        $GLOBALS['is_article_list'] = true;
    }
    $out['id'] = $id;
    // what section are we in?
    if ($s) {
        $out['s'] = $s;
    } elseif ($id) {
        $out['s'] = fetch('Section', 'textpattern', 'ID', $id);
    } else {
        $out['s'] = "default";
    }
    $s = $out['s'];
    $rs = safe_row("*", "txp_section", "name = '{$s}' limit 1");
    if ($rs) {
        // useful stuff from the database
        extract($rs);
        $out['page'] = $page;
        $out['css'] = $css;
    }
    $out['c'] = gps('c');
    // category?
    $out['q'] = gps('q');
    // search query?
    $out['count'] = gps('count');
    // pageby count? *deprecated*
    $out['pg'] = gps('pg');
    // paging?
    $out['p'] = gps('p');
    // image?
    if ($id) {
        // check for next or previous article in the same section
        $Posted = fetch('Posted', 'textpattern', 'ID', $id);
        $thenext = getNeighbour($Posted, $s, '>');
        $out['next_id'] = $thenext ? $thenext['ID'] : '';
        $out['next_title'] = $thenext ? $thenext['Title'] : '';
        $out['next_utitle'] = $thenext ? $thenext['url_title'] : '';
        $theprev = getNeighbour($Posted, $s, '<');
        $out['prev_id'] = $theprev ? $theprev['ID'] : '';
        $out['prev_title'] = $theprev ? $theprev['Title'] : '';
        $out['prev_utitle'] = $theprev ? $theprev['url_title'] : '';
    }
    $out['path_from_root'] = $path_from_root;
    $out['pfr'] = $path_from_root;
    $out['url_mode'] = $url_mode;
    $out['sitename'] = $sitename;
    return $out;
}
示例#6
0
 function update_weblog_prefs()
 {
     global $DSP, $IN, $DB, $LOG, $LANG, $FNS, $PREFS, $SESS, $LOC;
     if (!$DSP->allowed_group('can_admin_weblogs')) {
         return $DSP->no_access_message();
     }
     // If the $weblog_id variable is present we are editing an
     // existing weblog, otherwise we are creating a new one
     $edit = isset($_POST['weblog_id']) ? TRUE : FALSE;
     $add_rss = isset($_POST['add_rss']) ? TRUE : FALSE;
     unset($_POST['add_rss']);
     $return = $IN->GBL('return') ? TRUE : FALSE;
     unset($_POST['return']);
     unset($_POST['edit_group_prefs']);
     $dupe_id = $IN->GBL('duplicate_weblog_prefs');
     unset($_POST['duplicate_weblog_prefs']);
     // Check for required fields
     $error = array();
     if ($_POST['blog_name'] == '') {
         $error[] = $LANG->line('no_weblog_name');
     }
     if ($_POST['blog_title'] == '') {
         $error[] = $LANG->line('no_weblog_title');
     }
     if (preg_match('/[^a-z0-9\\-\\_]/i', $_POST['blog_name'])) {
         $error[] = $LANG->line('invalid_short_name');
     }
     if (isset($_POST['url_title_prefix']) && $_POST['url_title_prefix'] != '') {
         $_POST['url_title_prefix'] = strtolower(strip_tags($_POST['url_title_prefix']));
         if (!preg_match("/^[\\w\\-]+\$/", $_POST['url_title_prefix'])) {
             $error[] = $LANG->line('invalid_url_title_prefix');
         }
     }
     if (count($error) > 0) {
         $msg = '';
         foreach ($error as $val) {
             $msg .= $val . BR;
         }
         return $DSP->error_message($msg);
     }
     if (isset($_POST['comment_expiration'])) {
         if (!is_numeric($_POST['comment_expiration']) || $_POST['comment_expiration'] == '') {
             $_POST['comment_expiration'] = 0;
         }
     }
     // Is the weblog name taken?
     $sql = "SELECT COUNT(*) AS count FROM exp_weblogs WHERE site_id = '" . $DB->escape_str($PREFS->ini('site_id')) . "' AND blog_name = '" . $DB->escape_str($_POST['blog_name']) . "'";
     if ($edit == TRUE) {
         $sql .= " AND weblog_id != '" . $DB->escape_str($_POST['weblog_id']) . "'";
     }
     $query = $DB->query($sql);
     if ($query->row['count'] > 0) {
         return $DSP->error_message($LANG->line('taken_weblog_name'));
     }
     /** -----------------------------------------
     		/**  Template Error Trapping
     		/** -----------------------------------------*/
     if ($edit == FALSE) {
         $create_templates = $IN->GBL('create_templates');
         $old_group_id = $IN->GBL('old_group_id');
         $group_name = strtolower($IN->GBL('group_name', 'POST'));
         $template_theme = $FNS->filename_security($IN->GBL('template_theme'));
         unset($_POST['create_templates']);
         unset($_POST['old_group_id']);
         unset($_POST['group_name']);
         unset($_POST['template_theme']);
         if ($create_templates != 'no') {
             $LANG->fetch_language_file('templates');
             if (!$DSP->allowed_group('can_admin_templates')) {
                 return $DSP->no_access_message();
             }
             if (!$group_name) {
                 return $DSP->error_message($LANG->line('group_required'));
             }
             if (!preg_match("#^[a-zA-Z0-9_\\-/]+\$#i", $group_name)) {
                 return $DSP->error_message($LANG->line('illegal_characters'));
             }
             $reserved[] = 'act';
             $reserved[] = 'trackback';
             if ($PREFS->ini("forum_is_installed") == 'y' and $PREFS->ini("forum_trigger") != '') {
                 $reserved[] = $PREFS->ini("forum_trigger");
             }
             if (in_array($group_name, $reserved)) {
                 return $DSP->error_message($LANG->line('reserved_name'));
             }
             $query = $DB->query("SELECT COUNT(*) AS count FROM exp_template_groups \n\t\t\t\t\t\t\t\t\t WHERE site_id = '" . $DB->escape_str($PREFS->ini('site_id')) . "' \n\t\t\t\t\t\t\t\t\t AND group_name = '" . $DB->escape_str($group_name) . "'");
             if ($query->row['count'] > 0) {
                 return $DSP->error_message($LANG->line('template_group_taken'));
             }
         }
     }
     /** -----------------------------------------
     		/**  Create Weblog
     		/** -----------------------------------------*/
     // Construct the query based on whether we are updating or inserting
     if (isset($_POST['apply_expiration_to_existing'])) {
         $this->update_comment_expiration($_POST['weblog_id'], $_POST['comment_expiration']);
     }
     unset($_POST['apply_expiration_to_existing']);
     if (isset($_POST['cat_group']) && is_array($_POST['cat_group'])) {
         foreach ($_POST['cat_group'] as $key => $value) {
             unset($_POST['cat_group_' . $key]);
         }
         $_POST['cat_group'] = implode('|', $_POST['cat_group']);
     }
     if ($edit == FALSE) {
         unset($_POST['weblog_id']);
         unset($_POST['clear_versioning_data']);
         $_POST['blog_url'] = $FNS->fetch_site_index();
         $_POST['blog_lang'] = $PREFS->ini('xml_lang');
         $_POST['blog_encoding'] = $PREFS->ini('charset');
         // Assign field group if there is only one
         if (!isset($_POST['field_group']) or isset($_POST['field_group']) && !is_numeric($_POST['field_group'])) {
             $query = $DB->query("SELECT group_id FROM exp_field_groups WHERE site_id = '" . $DB->escape_str($PREFS->ini('site_id')) . "'");
             if ($query->num_rows == 1) {
                 $_POST['field_group'] = $query->row['group_id'];
             }
         }
         // Insert data
         $_POST['site_id'] = $PREFS->ini('site_id');
         // duplicating preferences?
         if ($dupe_id !== FALSE and is_numeric($dupe_id)) {
             $wquery = $DB->query("SELECT * FROM exp_weblogs WHERE weblog_id = '" . $DB->escape_str($dupe_id) . "'");
             if ($wquery->num_rows == 1) {
                 $exceptions = array('weblog_id', 'site_id', 'blog_name', 'blog_title', 'total_entries', 'total_comments', 'total_trackbacks', 'last_entry_date', 'last_comment_date', 'last_trackback_date');
                 foreach ($wquery->row as $key => $val) {
                     // don't duplicate fields that are unique to each weblog
                     if (!in_array($key, $exceptions)) {
                         switch ($key) {
                             // category, field, and status fields should only be duped
                             // if both weblogs are assigned to the same group of each
                             case 'cat_group':
                                 // allow to implicitly set category group to "None"
                                 if (!isset($_POST[$key])) {
                                     $_POST[$key] = $val;
                                 }
                                 break;
                             case 'status_group':
                             case 'field_group':
                                 if (!isset($_POST[$key]) or $_POST[$key] == '') {
                                     $_POST[$key] = $val;
                                 }
                                 break;
                             case 'deft_status':
                                 if (!isset($_POST['status_group']) or $_POST['status_group'] == $wquery->row['status_group']) {
                                     $_POST[$key] = $val;
                                 }
                                 break;
                             case 'search_excerpt':
                                 if (!isset($_POST['field_group']) or $_POST['field_group'] == $wquery->row['field_group']) {
                                     $_POST[$key] = $val;
                                 }
                                 break;
                             case 'deft_category':
                                 if (!isset($_POST['cat_group']) or count(array_diff(explode('|', $_POST['cat_group']), explode('|', $wquery->row['cat_group']))) == 0) {
                                     $_POST[$key] = $val;
                                 }
                                 break;
                             case 'blog_url':
                             case 'comment_url':
                             case 'search_results_url':
                             case 'tb_return_url':
                             case 'ping_return_url':
                             case 'rss_url':
                                 if ($create_templates != 'no') {
                                     if (!isset($old_group_name)) {
                                         $gquery = $DB->query("SELECT group_name FROM exp_template_groups WHERE group_id = '" . $DB->escape_str($old_group_id) . "'");
                                         $old_group_name = $gquery->row['group_name'];
                                     }
                                     $_POST[$key] = str_replace("/{$old_group_name}/", "/{$group_name}/", $val);
                                 } else {
                                     $_POST[$key] = $val;
                                 }
                                 break;
                             default:
                                 $_POST[$key] = $val;
                                 break;
                         }
                     }
                 }
             }
         }
         $sql = $DB->insert_string('exp_weblogs', $_POST);
         $DB->query($sql);
         $insert_id = $DB->insert_id;
         $weblog_id = $insert_id;
         $success_msg = $LANG->line('weblog_created');
         $crumb = $DSP->crumb_item($LANG->line('new_weblog'));
         $LOG->log_action($success_msg . $DSP->nbs(2) . $_POST['blog_title']);
     } else {
         if (isset($_POST['clear_versioning_data'])) {
             $DB->query("DELETE FROM exp_entry_versioning WHERE weblog_id  = '" . $DB->escape_str($_POST['weblog_id']) . "'");
             unset($_POST['clear_versioning_data']);
         }
         $sql = $DB->update_string('exp_weblogs', $_POST, 'weblog_id=' . $DB->escape_str($_POST['weblog_id']));
         $DB->query($sql);
         $weblog_id = $DB->escape_str($_POST['weblog_id']);
         $success_msg = $LANG->line('weblog_updated');
         $crumb = $DSP->crumb_item($LANG->line('update'));
     }
     /** -----------------------------------------
     		/**  Create Templates
     		/** -----------------------------------------*/
     if ($edit == FALSE) {
         if ($create_templates != 'no') {
             $query = $DB->query("SELECT COUNT(*) AS count FROM exp_template_groups WHERE is_user_blog = 'n'");
             $group_order = $query->row['count'] + 1;
             $DB->query($DB->insert_string('exp_template_groups', array('group_id' => '', 'group_name' => $group_name, 'group_order' => $group_order, 'is_site_default' => 'n', 'site_id' => $PREFS->ini('site_id'))));
             $group_id = $DB->insert_id;
             if ($create_templates == 'duplicate') {
                 $query = $DB->query("SELECT group_name FROM exp_template_groups WHERE group_id = '" . $DB->escape_str($old_group_id) . "'");
                 $old_group_name = $query->row['group_name'];
                 $query = $DB->query("SELECT template_name, template_data, template_type, template_notes, cache, refresh, no_auth_bounce, allow_php, php_parse_location FROM exp_templates WHERE group_id = '" . $DB->escape_str($old_group_id) . "'");
                 if ($query->num_rows == 0) {
                     $DB->query($DB->insert_string('exp_templates', array('template_id' => '', 'group_id' => $group_id, 'template_name' => 'index', 'edit_date' => $LOC->now, 'site_id' => $PREFS->ini('site_id'))));
                 } else {
                     $old_blog_name = '';
                     foreach ($query->result as $row) {
                         if ($old_blog_name == '') {
                             if (preg_match_all("/weblog=[\"'](.+?)[\"']/", $row['template_data'], $matches)) {
                                 for ($i = 0; $i < count($matches['1']); $i++) {
                                     if (substr($matches['1'][$i], 0, 1) != '{') {
                                         $old_blog_name = $matches['1'][$i];
                                         break;
                                     }
                                 }
                             }
                         }
                         $temp = str_replace('weblog="' . $old_blog_name . '"', 'weblog="' . $_POST['blog_name'] . '"', $row['template_data']);
                         $temp = str_replace("weblog='" . $old_blog_name . "'", 'weblog="' . $_POST['blog_name'] . '"', $temp);
                         $temp = preg_replace("/{stylesheet=.+?\\/(.+?)}/", "{stylesheet=" . $group_name . "/\\1}", $temp);
                         $temp = preg_replace("#assign_variable:master_weblog_name=\".+?\"#", 'assign_variable:master_weblog_name="' . $_POST['blog_name'] . '"', $temp);
                         $temp = preg_replace("#assign_variable:master_weblog_name=\\'.+?\\'#", "assign_variable:master_weblog_name='" . $_POST['blog_name'] . "'", $temp);
                         $temp = preg_replace('#assign_variable:my_template_group=(\\042|\\047)([^\\1]*?)\\1#', "assign_variable:my_template_group=\\1{$group_name}\\1", $temp);
                         $temp = preg_replace("#" . $old_group_name . "/(.+?)#", $group_name . "/\\1", $temp);
                         $data = array('template_id' => '', 'group_id' => $group_id, 'template_name' => $row['template_name'], 'template_notes' => $row['template_notes'], 'cache' => $row['cache'], 'refresh' => $row['refresh'], 'no_auth_bounce' => $row['no_auth_bounce'], 'php_parse_location' => $row['php_parse_location'], 'allow_php' => $SESS->userdata['group_id'] == 1 ? $row['allow_php'] : 'n', 'template_type' => $row['template_type'], 'template_data' => $temp, 'edit_date' => $LOC->now, 'site_id' => $PREFS->ini('site_id'));
                         $DB->query($DB->insert_string('exp_templates', $data));
                     }
                 }
             } else {
                 $type = 'core';
                 if ($fp = @opendir(PATH_MOD)) {
                     while (false !== ($file = readdir($fp))) {
                         if (strpos($file, '.') === FALSE) {
                             if ($file == 'mailinglist') {
                                 $type = 'full';
                                 break;
                             }
                         }
                     }
                     closedir($fp);
                 }
                 require PATH_THEMES . 'site_themes/' . $template_theme . '/' . $template_theme . '.php';
                 foreach ($template_matrix as $tmpl) {
                     $Q[] = array($tmpl['0'](), "INSERT INTO exp_templates(template_id, group_id, template_name, template_type, template_data, edit_date, site_id) \n\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES ('', '{$group_id}', '" . $DB->escape_str($tmpl['0']) . "', '" . $DB->escape_str($tmpl['1']) . "', '{template}', '" . $LOC->now . "', '" . $DB->escape_str($PREFS->ini('site_id')) . "')");
                 }
                 if ($add_rss == TRUE) {
                     require PATH_THEMES . 'site_themes/rss/rss.php';
                     $Q[] = array(rss_2(), "INSERT INTO exp_templates(template_id, group_id, template_name, template_type, template_data, edit_date, site_id) \n\t\t\t\t\t\t\t\t\t\t\t   VALUES ('', '{$group_id}', 'rss_2.0', 'rss', '{template}', '" . $DB->escape_str($LOC->now) . "', '" . $DB->escape_str($PREFS->ini('site_id')) . "')");
                     $Q[] = array(atom(), "INSERT INTO exp_templates(template_id, group_id, template_name, template_type, template_data, edit_date, site_id) \n\t\t\t\t\t\t\t\t\t\t\t  VALUES ('', '{$group_id}', 'atom', 'rss', '{template}', '" . $DB->escape_str($LOC->now) . "', '" . $DB->escape_str($PREFS->ini('site_id')) . "')");
                 }
                 foreach ($Q as $val) {
                     $temp = $val['0'];
                     $temp = str_replace('weblog="weblog1"', 'weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace("weblog='weblog1'", 'weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace('my_weblog="weblog1"', 'my_weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace("my_weblog='weblog1'", 'my_weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace('weblog="default_site"', 'weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace("weblog='default_site'", 'weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace('my_weblog="default_site"', 'my_weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace("my_weblog='default_site'", 'my_weblog="' . $_POST['blog_name'] . '"', $temp);
                     $temp = str_replace('my_template_group="site"', 'my_template_group="' . $group_name . '"', $temp);
                     $temp = str_replace("my_template_group='site'", 'my_template_group="' . $group_name . '"', $temp);
                     $temp = str_replace("{stylesheet=weblog/weblog_css}", "{stylesheet=" . $group_name . "/site_css}", $temp);
                     $temp = str_replace("{stylesheet=site/site_css}", "{stylesheet=" . $group_name . "/site_css}", $temp);
                     $temp = str_replace('assign_variable:master_weblog_name="weblog1"', 'assign_variable:master_weblog_name="' . $_POST['blog_name'] . '"', $temp);
                     $temp = preg_replace("#weblog/(.+?)#", $group_name . "/\\1", $temp);
                     $temp = addslashes($temp);
                     $sql = str_replace('{template}', $temp, $val['1']);
                     $DB->query($sql);
                 }
             }
         }
     }
     $message = $DSP->qdiv('itemWrapper', $DSP->qspan('success', $success_msg) . NBS . NBS . '<b>' . $_POST['blog_title'] . '</b>');
     if ($edit == FALSE or $return === TRUE) {
         return $this->weblog_overview($message);
     } else {
         return $this->edit_blog_form($message, $weblog_id);
     }
 }
function cnk_pretext()
{
    global $prefs;
    // only takeover url algorithm when in section_title mode
    if (CNK_FRIENDLY_URLS && $prefs['permlink_mode'] == 'section_title') {
        extract($prefs);
        $out = array();
        // some useful vars for taghandlers, plugins
        $out['request_uri'] = preg_replace("|^https?://[^/]+|i", "", serverSet('REQUEST_URI'));
        $out['qs'] = serverSet('QUERY_STRING');
        // IIS fix
        if (!$out['request_uri'] and serverSet('SCRIPT_NAME')) {
            $out['request_uri'] = serverSet('SCRIPT_NAME') . (serverSet('QUERY_STRING') ? '?' . serverSet('QUERY_STRING') : '');
        }
        // another IIS fix
        if (!$out['request_uri'] and serverSet('argv')) {
            $argv = serverSet('argv');
            $out['request_uri'] = @substr($argv[0], strpos($argv[0], ';') + 1);
        }
        $subpath = preg_quote(preg_replace("/https?:\\/\\/.*(\\/.*)/Ui", "\$1", hu), "/");
        $req = preg_replace("/^{$subpath}/i", "/", $out['request_uri']);
        $url_chunks = explode('/', trim($req, '/'));
        $req = '/' . implode('/', array_slice($url_chunks, -2));
        //echo $req;
        extract(chopUrl($req));
        //first we sniff out some of the preset url schemes
        if (strlen($u1)) {
            switch ($u1) {
                case 'atom':
                    include txpath . '/publish/atom.php';
                    exit(atom());
                case 'rss':
                    include txpath . '/publish/rss.php';
                    exit(rss());
                    // urldecode(strtolower(urlencode())) looks ugly but is the only way to
                    // make it multibyte-safe without breaking backwards-compatibility
                // urldecode(strtolower(urlencode())) looks ugly but is the only way to
                // make it multibyte-safe without breaking backwards-compatibility
                case urldecode(strtolower(urlencode(gTxt('section')))):
                    $out['s'] = ckEx('section', $u2) ? $u2 : '';
                    break;
                case urldecode(strtolower(urlencode(gTxt('category')))):
                    $out['c'] = ckEx('category', $u2) ? $u2 : '';
                    break;
                case urldecode(strtolower(urlencode(gTxt('author')))):
                    $out['author'] = !empty($u2) ? $u2 : '';
                    break;
                    // AuthorID gets resolved from Name further down
                // AuthorID gets resolved from Name further down
                case urldecode(strtolower(urlencode(gTxt('file_download')))):
                    $out['s'] = 'file_download';
                    $out['id'] = !empty($u2) ? $u2 : '';
                    break;
                default:
                    // then see if the prefs-defined permlink scheme is usable
                    switch ($permlink_mode) {
                        /*
                        case 'section_id_title':
                        		if (empty($u2)) 
                        		{
                        				$out['s'] = (ckEx('section',$u1)) ? $u1 : '';
                        		}
                        		else 
                        		{
                        				$rs = lookupByIDSection($u2, $u1);
                        				$out['s'] = @$rs['Section'];
                        				$out['id'] = @$rs['ID'];
                        		}
                        break;
                        
                        case 'year_month_day_title':
                        		if (empty($u2)) 
                        		{
                        				$out['s'] = (ckEx('section',$u1)) ? $u1 : '';
                        		}
                        		elseif (empty($u4))
                        		{
                        				$month = "$u1-$u2";
                        				if (!empty($u3)) $month.= "-$u3";
                        				if (preg_match('/\d+-\d+(?:-\d+)?/', $month)) {
                        						$out['month'] = $month;
                        						$out['s'] = 'default';
                        				}
                        		}
                        		else
                        		{
                        				$when = "$u1-$u2-$u3";
                        				$rs = lookupByDateTitle($when,$u4);
                        				$out['id'] = (!empty($rs['ID'])) ? $rs['ID'] : '';
                        				$out['s'] = (!empty($rs['Section'])) ? $rs['Section'] : '';
                        		}
                        break;
                        */
                        case 'section_title':
                            if (empty($u2)) {
                                $out['s'] = ckEx('section', $u1) ? $u1 : '';
                            } else {
                                // match section/title
                                $rs = lookupByTitleSection($u2, $u1);
                                if (count($rs)) {
                                    $out['id'] = @$rs['ID'];
                                    $out['s'] = @$rs['Section'];
                                } else {
                                    // match parentsection/section
                                    $rs = safe_row("name, lft", 'txp_section', "lower(name) like '" . doSlash($u2) . "' AND lower(parent)='" . doSlash($u1) . "' limit 1");
                                    if (count($rs)) {
                                        // check path TODO: move to function
                                        $rs_path = safe_rows("name", "txp_section", "lft <= " . $rs['lft'] . " and ((rgt-lft) > 1 OR lft = " . $rs['lft'] . ") and name != 'default' order by lft");
                                        $path = '/';
                                        for ($i = 0; $i < count($rs_path); $i++) {
                                            $path .= $rs_path[$i]['name'] . '/';
                                        }
                                        if ($path == '/' . implode('/', $url_chunks) . '/') {
                                            $out['s'] = @$rs['name'];
                                        }
                                    }
                                }
                            }
                            break;
                            /*
                            								case 'title_only':
                            										$rs = lookupByTitle($u1);
                            										$out['id'] = @$rs['ID'];
                            										$out['s'] = (empty($rs['Section']) ? ckEx('section', $u1) : $rs['Section']);
                            								break;
                            
                            								case 'id_title':
                            										if (is_numeric($u1) && ckExID($u1))
                            										{
                            												$rs = lookupByID($u1);
                            												$out['id'] = (!empty($rs['ID'])) ? $rs['ID'] : '';
                            												$out['s'] = (!empty($rs['Section'])) ? $rs['Section'] : '';
                            										}
                            										else
                            										{
                            												# We don't want to miss the /section/ pages
                            												$out['s']= ckEx('section',$u1)? $u1 : '';
                            										}
                            								break; */
                    }
            }
        } else {
            $out['s'] = 'default';
        }
        //print_r($out);
        if (isset($out['id'])) {
            $_GET['id'] = $out['id'];
        }
        if (isset($out['s'])) {
            $_GET['s'] = $out['s'];
        }
    }
}
示例#8
0
    /**
     * Channel preference submission handler
     *
     * This function receives the submitted channel preferences
     * and stores them in the database.
     *
     * @access	public
     * @return	void
     */
    function channel_update()
    {
        if (!$this->cp->allowed_group('can_access_admin') or !$this->cp->allowed_group('can_access_content_prefs')) {
            show_error($this->lang->line('unauthorized_access'));
        }
        $this->lang->loadfile('admin_content');
        unset($_POST['channel_prefs_submit']);
        // submit button
        // If the $channel_id variable is present we are editing an
        // existing channel, otherwise we are creating a new one
        $edit = isset($_POST['channel_id']) ? TRUE : FALSE;
        // Load the layout Library & update the layouts
        $this->load->library('layout');
        $add_rss = isset($_POST['add_rss']) ? TRUE : FALSE;
        unset($_POST['add_rss']);
        $return = $this->input->get_post('return') ? TRUE : FALSE;
        unset($_POST['return']);
        $edit_group_prefs = TRUE;
        if ($this->input->get_post('edit_group_prefs') !== 'y') {
            unset($_POST['cat_group']);
            unset($_POST['status_group']);
            unset($_POST['field_group']);
            $edit_group_prefs = FALSE;
        }
        unset($_POST['edit_group_prefs']);
        $dupe_id = $this->input->get_post('duplicate_channel_prefs');
        unset($_POST['duplicate_channel_prefs']);
        // Check for required fields
        $error = array();
        if (isset($_POST['comment_expiration']) && $_POST['comment_expiration'] == '') {
            $_POST['comment_expiration'] = 0;
        }
        // Template Error Trapping
        if ($edit == FALSE) {
            $this->load->library('security');
            $create_templates = $this->input->get_post('create_templates');
            $old_group_id = $this->input->get_post('old_group_id');
            $group_name = $this->input->post('group_name');
            $template_theme = $this->security->sanitize_filename($this->input->get_post('template_theme'));
            unset($_POST['create_templates']);
            unset($_POST['old_group_id']);
            unset($_POST['group_name']);
            unset($_POST['template_theme']);
            if ($create_templates != 'no') {
                $this->lang->loadfile('design');
                if (!$this->cp->allowed_group('can_admin_templates')) {
                    show_error($this->lang->line('unauthorized_access'));
                }
                if (!$group_name) {
                    show_error($this->lang->line('group_required'));
                }
                if (!preg_match("#^[a-zA-Z0-9_\\-/]+\$#i", $group_name)) {
                    show_error($this->lang->line('illegal_characters'));
                }
                $reserved[] = 'act';
                if ($this->config->item("forum_is_installed") == 'y' and $this->config->item("forum_trigger") != '') {
                    $reserved[] = $this->config->item("forum_trigger");
                }
                if (in_array($group_name, $reserved)) {
                    show_error($this->lang->line('reserved_name'));
                }
                $this->db->where('site_id', $this->config->item('site_id'));
                $this->db->where('group_name', $group_name);
                $count = $this->db->count_all_results('template_groups');
                if ($count > 0) {
                    show_error($this->lang->line('template_group_taken'));
                }
            }
        }
        if ($this->input->post('apply_comment_enabled_to_existing')) {
            if ($this->input->post('comment_system_enabled') == 'y') {
                $this->channel_model->update_comments_allowed($_POST['channel_id'], 'y');
            } elseif ($this->input->post('comment_system_enabled') == 'n') {
                $this->channel_model->update_comments_allowed($_POST['channel_id'], 'n');
            }
        }
        unset($_POST['apply_comment_enabled_to_existing']);
        if (isset($_POST['apply_expiration_to_existing'])) {
            if ($this->input->post('comment_expiration') == 0) {
                $this->channel_model->update_comment_expiration($_POST['channel_id'], $_POST['comment_expiration'], TRUE);
            } else {
                $this->channel_model->update_comment_expiration($_POST['channel_id'], $_POST['comment_expiration'] * 86400);
            }
        }
        unset($_POST['apply_expiration_to_existing']);
        if (isset($_POST['cat_group']) && is_array($_POST['cat_group'])) {
            foreach ($_POST['cat_group'] as $key => $value) {
                unset($_POST['cat_group_' . $key]);
            }
            $_POST['cat_group'] = implode('|', $_POST['cat_group']);
        }
        // Create Channel
        // Construct the query based on whether we are updating or inserting
        if ($edit == FALSE) {
            unset($_POST['channel_id']);
            unset($_POST['clear_versioning_data']);
            $_POST['channel_url'] = $this->functions->fetch_site_index();
            $_POST['channel_lang'] = $this->config->item('xml_lang');
            // Assign field group if there is only one
            if (!isset($_POST['field_group']) or isset($_POST['field_group']) && !is_numeric($_POST['field_group'])) {
                $this->db->select('group_id');
                $this->db->where('site_id', $this->config->item('site_id'));
                $query = $this->db->get('field_groups');
                if ($query->num_rows() == 1) {
                    $_POST['field_group'] = $query->row('group_id');
                }
            }
            // Insert data
            $_POST['site_id'] = $this->config->item('site_id');
            // duplicating preferences?
            if ($dupe_id !== FALSE and is_numeric($dupe_id)) {
                $this->db->where('channel_id', $dupe_id);
                $wquery = $this->db->get('channels');
                if ($wquery->num_rows() == 1) {
                    $exceptions = array('channel_id', 'site_id', 'channel_name', 'channel_title', 'total_entries', 'total_comments', 'last_entry_date', 'last_comment_date');
                    foreach ($wquery->row_array() as $key => $val) {
                        // don't duplicate fields that are unique to each channel
                        if (!in_array($key, $exceptions)) {
                            switch ($key) {
                                // category, field, and status fields should only be duped
                                // if both channels are assigned to the same group of each
                                case 'cat_group':
                                    // allow to implicitly set category group to "None"
                                    if (!isset($_POST[$key])) {
                                        $_POST[$key] = $val;
                                    }
                                    break;
                                case 'status_group':
                                case 'field_group':
                                    if (!isset($_POST[$key])) {
                                        $_POST[$key] = $val;
                                    } elseif ($_POST[$key] == '') {
                                        $_POST[$key] = NULL;
                                    }
                                    break;
                                case 'deft_status':
                                case 'deft_status':
                                    if (!isset($_POST['status_group']) or $_POST['status_group'] == $wquery->row('status_group')) {
                                        $_POST[$key] = $val;
                                    }
                                    break;
                                case 'search_excerpt':
                                    if (!isset($_POST['field_group']) or $_POST['field_group'] == $wquery->row('field_group')) {
                                        $_POST[$key] = $val;
                                    }
                                    break;
                                case 'deft_category':
                                    if (!isset($_POST['cat_group']) or count(array_diff(explode('|', $_POST['cat_group']), explode('|', $wquery->row('cat_group')))) == 0) {
                                        $_POST[$key] = $val;
                                    }
                                    break;
                                case 'blog_url':
                                case 'comment_url':
                                case 'search_results_url':
                                case 'ping_return_url':
                                case 'rss_url':
                                    if ($create_templates != 'no') {
                                        if (!isset($old_group_name)) {
                                            $this->db->select('group_name');
                                            $this->db->where('group_id', $old_group_id);
                                            $gquery = $this->db->get('template_groups');
                                            $old_group_name = $gquery->row('group_name');
                                        }
                                        $_POST[$key] = str_replace("/{$old_group_name}/", "/{$group_name}/", $val);
                                    } else {
                                        $_POST[$key] = $val;
                                    }
                                    break;
                                default:
                                    $_POST[$key] = $val;
                                    break;
                            }
                        }
                    }
                }
            }
            $_POST['default_entry_title'] = !isset($_POST['default_entry_title']) ? '' : $_POST['default_entry_title'];
            $_POST['url_title_prefix'] = !isset($_POST['url_title_prefix']) ? '' : $_POST['url_title_prefix'];
            $this->db->insert('channels', $_POST);
            $insert_id = $this->db->insert_id();
            $channel_id = $insert_id;
            if ($dupe_id !== FALSE and is_numeric($dupe_id) && $edit_group_prefs == FALSE) {
                // Duplicate layouts
                $this->layout->duplicate_layout($dupe_id, $channel_id);
            }
            $success_msg = $this->lang->line('channel_created');
            $this->logger->log_action($success_msg . NBS . NBS . $_POST['channel_title']);
        } else {
            if (isset($_POST['clear_versioning_data'])) {
                $this->db->delete('entry_versioning', array('channel_id' => $_POST['channel_id']));
                unset($_POST['clear_versioning_data']);
            }
            // Only one possible is revisions- enabled or disabled.
            // We treat as installed/not and delete the whole tab.
            $this->layout->sync_layout($_POST, $_POST['channel_id']);
            $sql = $this->db->update_string('exp_channels', $_POST, 'channel_id=' . $this->db->escape_str($_POST['channel_id']));
            $this->db->query($sql);
            $channel_id = $this->db->escape_str($_POST['channel_id']);
            $success_msg = $this->lang->line('channel_updated');
        }
        /** -----------------------------------------
        		/**  Create Templates
        		/** -----------------------------------------*/
        if ($edit == FALSE) {
            if ($create_templates != 'no') {
                $query = $this->db->query("SELECT COUNT(*) AS count FROM exp_template_groups");
                $group_order = $query->row('count') + 1;
                $this->db->insert('template_groups', array('group_name' => $group_name, 'group_order' => $group_order, 'is_site_default' => 'n', 'site_id' => $this->config->item('site_id')));
                $group_id = $this->db->insert_id();
                if ($create_templates == 'duplicate') {
                    $this->db->select('group_name');
                    $this->db->where('group_id', $old_group_id);
                    $query = $this->db->get('template_groups');
                    $old_group_name = $query->row('group_name');
                    $this->db->select('template_name, template_data, template_type, 
										template_notes, cache, refresh, no_auth_bounce, 
										allow_php, php_parse_location');
                    $this->db->where('group_id', $old_group_id);
                    $query = $this->db->get('templates');
                    if ($query->num_rows() == 0) {
                        $this->db->insert('templates', array('group_id' => $group_id, 'template_name' => 'index', 'edit_date' => $this->localize->now, 'site_id' => $this->config->item('site_id')));
                    } else {
                        $old_channel_name = '';
                        foreach ($query->result_array() as $row) {
                            if ($old_channel_name == '') {
                                if (preg_match_all("/channel=[\"'](.+?)[\"']/", $row['template_data'], $matches)) {
                                    for ($i = 0; $i < count($matches['1']); $i++) {
                                        if (substr($matches['1'][$i], 0, 1) != '{') {
                                            $old_channel_name = $matches['1'][$i];
                                            break;
                                        }
                                    }
                                }
                            }
                            $temp = str_replace('channel="' . $old_channel_name . '"', 'channel="' . $_POST['channel_name'] . '"', $row['template_data']);
                            $temp = str_replace("channel='" . $old_channel_name . "'", 'channel="' . $_POST['channel_name'] . '"', $temp);
                            $temp = preg_replace("/{stylesheet=.+?\\/(.+?)}/", "{stylesheet=" . $group_name . "/\\1}", $temp);
                            $temp = preg_replace("#preload_replace:master_channel_name=\".+?\"#", 'preload_replace:master_channel_name="' . $_POST['channel_name'] . '"', $temp);
                            $temp = preg_replace("#preload_replace:master_channel_name=\\'.+?\\'#", "preload_replace:master_channel_name='" . $_POST['channel_name'] . "'", $temp);
                            $temp = preg_replace('#preload_replace:my_template_group=(\\042|\\047)([^\\1]*?)\\1#', "preload_replace:my_template_group=\\1{$group_name}\\1", $temp);
                            $temp = preg_replace("#" . $old_group_name . "/(.+?)#", $group_name . "/\\1", $temp);
                            $data = array('group_id' => $group_id, 'template_name' => $row['template_name'], 'template_notes' => $row['template_notes'], 'cache' => $row['cache'], 'refresh' => $row['refresh'], 'no_auth_bounce' => $row['no_auth_bounce'], 'php_parse_location' => $row['php_parse_location'], 'allow_php' => $this->session->userdata['group_id'] == 1 ? $row['allow_php'] : 'n', 'template_type' => $row['template_type'], 'template_data' => $temp, 'edit_date' => $this->localize->now, 'last_author_id' => 0, 'site_id' => $this->config->item('site_id'));
                            $this->db->insert('templates', $data);
                        }
                    }
                } else {
                    $type = 'core';
                    if ($fp = @opendir(PATH_MOD)) {
                        while (FALSE !== ($file = readdir($fp))) {
                            if (strpos($file, '.') === FALSE) {
                                if ($file == 'mailinglist') {
                                    $type = 'full';
                                    break;
                                }
                            }
                        }
                        closedir($fp);
                    }
                    require PATH_THEMES . 'site_themes/' . $template_theme . '/' . $template_theme . '.php';
                    foreach ($template_matrix as $tmpl) {
                        $Q[] = array($tmpl['0'](), "INSERT INTO exp_templates(group_id, template_name, template_type, template_data, edit_date, site_id)\n\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES ('{$group_id}', '" . $this->db->escape_str($tmpl['0']) . "', '" . $this->db->escape_str($tmpl['1']) . "', '{template}', '" . $this->localize->now . "', '" . $this->db->escape_str($this->config->item('site_id')) . "')");
                    }
                    if ($add_rss == TRUE) {
                        require PATH_THEMES . 'site_themes/rss/rss.php';
                        $Q[] = array(rss_2(), "INSERT INTO exp_templates(group_id, template_name, template_type, template_data, edit_date, site_id)\n\t\t\t\t\t\t\t\t\t\t\t\tVALUES ('{$group_id}', 'rss_2.0', 'feed', '{template}', '" . $this->db->escape_str($this->localize->now) . "', '" . $this->db->escape_str($this->config->item('site_id')) . "')");
                        $Q[] = array(atom(), "INSERT INTO exp_templates(group_id, template_name, template_type, template_data, edit_date, site_id)\n\t\t\t\t\t\t\t\t\t\t\t  VALUES ('{$group_id}', 'atom', 'feed', '{template}', '" . $this->db->escape_str($this->localize->now) . "', '" . $this->db->escape_str($this->config->item('site_id')) . "')");
                    }
                    foreach ($Q as $val) {
                        $temp = $val['0'];
                        $temp = str_replace('channel="channel1"', 'channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace("channel='channel1'", 'channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace('my_channel="channel1"', 'my_channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace("my_channel='channel1'", 'my_channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace('channel="default_site"', 'channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace("channel='default_site'", 'channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace('my_channel="default_site"', 'my_channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace("my_channel='default_site'", 'my_channel="' . $_POST['channel_name'] . '"', $temp);
                        $temp = str_replace('my_template_group="site"', 'my_template_group="' . $group_name . '"', $temp);
                        $temp = str_replace("my_template_group='site'", 'my_template_group="' . $group_name . '"', $temp);
                        $temp = str_replace("{stylesheet=channel/channel_css}", "{stylesheet=" . $group_name . "/site_css}", $temp);
                        $temp = str_replace("{stylesheet=site/site_css}", "{stylesheet=" . $group_name . "/site_css}", $temp);
                        $temp = str_replace('preload_replace:master_channel_name="channel1"', 'preload_replace:master_channel_name="' . $_POST['channel_name'] . '"', $temp);
                        $temp = preg_replace("#channel/(.+?)#", $group_name . "/\\1", $temp);
                        $temp = addslashes($temp);
                        $sql = str_replace('{template}', $temp, $val['1']);
                        $this->db->query($sql);
                    }
                }
            }
        }
        $cp_message = $success_msg . NBS . NBS . $_POST['channel_title'];
        $this->session->set_flashdata('message_success', $cp_message);
        if ($edit == FALSE or $return === TRUE) {
            $this->functions->redirect(BASE . AMP . 'C=admin_content' . AMP . 'M=channel_management');
        } else {
            $this->functions->redirect(BASE . AMP . 'C=admin_content' . AMP . 'M=channel_edit&channel_id=' . $channel_id);
        }
    }