<?php /*

 Composr
 Copyright (c) ocProducts, 2004-2016

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  ocProducts Ltd
 * @package    wiki
 */

/**
 * Module page class.
 */
class Module_wiki
{
    /**
     * Find details of the module.
     *
     * @return ?array Map of module info (null: module is disabled).
     */
    public function info()
    {
        $info = array();
        $info['author'] = 'Chris Graham';
        $info['organisation'] = 'ocProducts';
        $info['hacked_by'] = null;
        $info['hack_version'] = null;
        $info['version'] = 9;
        $info['update_require_upgrade'] = true;
        $info['locked'] = false;
        return $info;
    }

    /**
     * Uninstall the module.
     */
    public function uninstall()
    {
        $GLOBALS['SITE_DB']->drop_table_if_exists('wiki_children');
        $GLOBALS['SITE_DB']->drop_table_if_exists('wiki_pages');
        $GLOBALS['SITE_DB']->drop_table_if_exists('wiki_posts');

        delete_value('num_wiki_pages');
        delete_value('num_wiki_posts');
        delete_value('num_wiki_files');

        delete_attachments('wiki_page');
        delete_attachments('wiki_post');

        delete_privilege('wiki_manage_tree');
        delete_privilege('wiki_edit_pages');
        delete_privilege('wiki_edit');

        $GLOBALS['SITE_DB']->query_delete('group_category_access', array('module_the_name' => 'wiki_page'));

        $GLOBALS['FORUM_DRIVER']->install_delete_custom_field('points_gained_wiki');
    }

    /**
     * Install the module.
     *
     * @param  ?integer $upgrade_from What version we're upgrading from (null: new install)
     * @param  ?integer $upgrade_from_hack What hack version we're upgrading from (null: new-install/not-upgrading-from-a-hacked-version)
     */
    public function install($upgrade_from = null, $upgrade_from_hack = null)
    {
        require_lang('wiki');

        require_code('lang3');

        if (is_null($upgrade_from)) {
            $GLOBALS['SITE_DB']->create_table('wiki_children', array(
                'parent_id' => '*AUTO_LINK',
                'child_id' => '*AUTO_LINK',
                'the_order' => 'INTEGER',
                'title' => 'SHORT_TEXT'
            ));

            $GLOBALS['SITE_DB']->create_table('wiki_pages', array(
                'id' => '*AUTO',
                'title' => 'SHORT_TRANS',
                'notes' => 'LONG_TEXT',
                'description' => 'LONG_TRANS__COMCODE',
                'add_date' => 'TIME',
                'edit_date' => '?TIME',
                'wiki_views' => 'INTEGER',
                'hide_posts' => 'BINARY',
                'submitter' => 'MEMBER'
            ));

            $GLOBALS['SITE_DB']->create_index('wiki_pages', 'sps', array('submitter'));
            $GLOBALS['SITE_DB']->create_index('wiki_pages', 'sadd_date', array('add_date'));

            $map = array(
                'submitter' => $GLOBALS['FORUM_DRIVER']->get_guest_id() + 1,
                'edit_date' => null,
                'hide_posts' => 0,
                'wiki_views' => 0,
                'add_date' => time(),
                'notes' => '',
            );
            $map += insert_lang_comcode('description', '', 2);
            $map += lang_code_to_default_content('title', 'WIKI_HOME', false, 1);
            $GLOBALS['SITE_DB']->query_insert('wiki_pages', $map);
            require_code('permissions2');
            set_global_category_access('wiki_page', db_get_first_id());

            add_privilege('WIKI', 'wiki_manage_tree', false);

            $GLOBALS['SITE_DB']->create_table('wiki_posts', array(
                'id' => '*AUTO',
                'page_id' => 'AUTO_LINK',
                'the_message' => 'LONG_TRANS__COMCODE',
                'date_and_time' => 'TIME',
                'validated' => 'BINARY',
                'wiki_views' => 'INTEGER',
                'member_id' => 'MEMBER',
                'edit_date' => '?TIME'
            ));

            $GLOBALS['SITE_DB']->create_index('wiki_posts', 'posts_on_page', array('page_id'));
            $GLOBALS['SITE_DB']->create_index('wiki_posts', 'cdate_and_time', array('date_and_time'));
            $GLOBALS['SITE_DB']->create_index('wiki_posts', 'svalidated', array('validated'));

            $GLOBALS['FORUM_DRIVER']->install_create_custom_field('points_gained_wiki', 20, /*locked=*/1, /*viewable=*/0, /*settable=*/0, /*required=*/0, '', 'integer');

            $GLOBALS['SITE_DB']->create_index('wiki_posts', 'ftjoin_spm', array('the_message'));
            $GLOBALS['SITE_DB']->create_index('wiki_pages', 'ftjoin_spt', array('title'));
            $GLOBALS['SITE_DB']->create_index('wiki_pages', 'ftjoin_spd', array('description'));
        }

        if ((!is_null($upgrade_from)) && ($upgrade_from < 9)) {
            $GLOBALS['SITE_DB']->rename_table('seedy_children', 'wiki_children');
            $GLOBALS['SITE_DB']->rename_table('seedy_pages', 'wiki_pages');
            $GLOBALS['SITE_DB']->rename_table('seedy_posts', 'wiki_posts');

            $GLOBALS['SITE_DB']->alter_table_field('wiki_pages', 'seedy_views', 'INTEGER', 'wiki_views');

            $GLOBALS['SITE_DB']->alter_table_field('wiki_posts', 'seedy_views', 'INTEGER', 'wiki_views');
            $GLOBALS['SITE_DB']->alter_table_field('wiki_posts', 'the_user', 'MEMBER', 'member_id');

            $GLOBALS['SITE_DB']->add_table_field('wiki_pages', 'edit_date', '?TIME');

            rename_config_option('is_on_seedy', 'is_on_wiki');
            rename_config_option('points_cedi', 'points_wiki');
            rename_config_option('cedi_show_stats_count_pages', 'wiki_show_stats_count_pages');
            rename_config_option('cedi_show_stats_count_posts', 'wiki_show_stats_count_posts');

            rename_privilege('seedy_manage_tree', 'wiki_manage_tree');
            rename_privilege('seedy_edit_pages', 'wiki_edit_pages');
            rename_privilege('seedy_edit', 'wiki_edit');

            $GLOBALS['SITE_DB']->query_update('group_category_access', array('module_the_name' => 'wiki_page'), array('module_the_name' => 'seedy_page'));
            $GLOBALS['SITE_DB']->query_update('group_privileges', array('module_the_name' => 'wiki_page'), array('module_the_name' => 'seedy_page'));
            $GLOBALS['SITE_DB']->query_update('group_privileges', array('the_page' => 'wiki'), array('the_page' => 'cedi'));
            $GLOBALS['SITE_DB']->query_update('group_page_access', array('page_name' => 'wiki'), array('page_name' => 'cedi'));
            $GLOBALS['SITE_DB']->query_update('group_page_access', array('page_name' => 'cms_wiki'), array('page_name' => 'cms_cedi'));

            $GLOBALS['SITE_DB']->query_update('notifications_enabled', array('l_notification_code' => 'wiki'), array('l_notification_code' => 'cedi'));

            $GLOBALS['SITE_DB']->query_update('attachment_refs', array('r_referer_type' => 'wiki_post'), array('r_referer_type' => 'cedi_post'));
            $GLOBALS['SITE_DB']->query_update('attachment_refs', array('r_referer_type' => 'wiki_page'), array('r_referer_type' => 'cedi_page'));

            $GLOBALS['SITE_DB']->query_update('translate', array('text_original' => 'cms_points_gained_wiki'), array('text_original' => 'cms_points_gained_seedy'));

            if (addon_installed('catalogues')) {
                foreach (array('catalogues', 'catalogue_categories', 'catalogue_fields', 'catalogue_entries') as $table) {
                    $GLOBALS['SITE_DB']->query_update($table, array('c_name' => '_wiki_post'), array('c_name' => '_seedy_post'));
                }
            }
            $GLOBALS['SITE_DB']->query_update('catalogue_entry_linkage', array('content_type' => 'wiki_page'), array('content_type' => 'cedi_page'));
            $GLOBALS['SITE_DB']->query_update('catalogue_entry_linkage', array('content_type' => 'wiki_post'), array('content_type' => 'cedi_post'));

            $GLOBALS['SITE_DB']->drop_table_if_exists('seedy_changes');

            $GLOBALS['SITE_DB']->query_update('privilege_list', array('p_section' => 'WIKI'), array('p_section' => 'SEEDY'));

            $GLOBALS['SITE_DB']->delete_index_if_exists('wiki_posts', 'seedy_views');
            $GLOBALS['SITE_DB']->delete_index_if_exists('wiki_pages', 'seedy_views');
            $GLOBALS['SITE_DB']->delete_index_if_exists('wiki_posts', 'spos');
        }

        if ((is_null($upgrade_from)) || ($upgrade_from < 9)) {
            $GLOBALS['SITE_DB']->create_index('wiki_pages', '#wiki_search__combined', array('title', 'description'));

            $GLOBALS['SITE_DB']->create_index('wiki_posts', 'wiki_views', array('wiki_views'));
            $GLOBALS['SITE_DB']->create_index('wiki_pages', 'wiki_views', array('wiki_views'));
            $GLOBALS['SITE_DB']->create_index('wiki_posts', 'spos', array('member_id'));
        }
    }

    /**
     * Find entry-points available within this module.
     *
     * @param  boolean $check_perms Whether to check permissions.
     * @param  ?MEMBER $member_id The member to check permissions as (null: current user).
     * @param  boolean $support_crosslinks Whether to allow cross links to other modules (identifiable via a full-page-link rather than a screen-name).
     * @param  boolean $be_deferential Whether to avoid any entry-point (or even return null to disable the page in the Sitemap) if we know another module, or page_group, is going to link to that entry-point. Note that "!" and "browse" entry points are automatically merged with container page nodes (likely called by page-groupings) as appropriate.
     * @return ?array A map of entry points (screen-name=>language-code/string or screen-name=>[language-code/string, icon-theme-image]) (null: disabled).
     */
    public function get_entry_points($check_perms = true, $member_id = null, $support_crosslinks = true, $be_deferential = false)
    {
        $ret = array(
            'browse' => array('WIKI_HOME', 'menu/rich_content/wiki'),
            'random' => array('RANDOM_PAGE', 'menu/rich_content/wiki/random_page'),
        );
        if (addon_installed('actionlog')) {
            require_lang('actionlog');
            $ret['revisions'] = array('REVISIONS', 'buttons/revisions');
        }
        return $ret;
    }

    public $title;
    public $id;
    public $chain;
    public $page;
    public $current_title;
    public $title_to_use;
    public $title_to_use_2;
    public $db_posts;
    public $num_posts;

    /**
     * Module pre-run function. Allows us to know metadata for <head> before we start streaming output.
     *
     * @return ?Tempcode Tempcode indicating some kind of exceptional output (null: none).
     */
    public function pre_run()
    {
        $type = get_param_string('type', 'browse');

        require_lang('wiki');
        require_code('wiki');

        set_feed_url('?mode=wiki&select=');

        if ($type == 'browse') {
            // Find our page by whatever means
            $find = get_param_string('find', '');
            if ($find != '') { // Allow quick 'find' remapping to a real ID
                $id = $GLOBALS['SITE_DB']->query_select_value_if_there('wiki_pages', 'id', array($GLOBALS['SITE_DB']->translate_field_ref('title') => $find));
                if (is_null($id)) {
                    $this->title = get_screen_title('ERROR_OCCURRED');
                    $add_access = (has_submit_permission('low', get_member(), get_ip_address(), 'cms_wiki'));
                    require_lang('zones');
                    $add_url = $add_access ? build_url(array('page' => 'cms_wiki', 'type' => 'add_page', 'id' => $find, 'redirect' => get_self_url(true, true)), get_module_zone('cms_wiki')) : new Tempcode();
                    return do_template('MISSING_SCREEN', array('_GUID' => 'ba778c816860a9594983ed9ef03d0c42', 'TITLE' => $this->title, 'ADD_URL' => $add_url, 'PAGE' => $find));
                }
                $chain = wiki_derive_chain($id);
            } else {
                list($id, $chain) = get_param_wiki_chain('id', strval(db_get_first_id()));
            }
            $pages = $GLOBALS['SITE_DB']->query_select('wiki_pages', array('*'), array('id' => $id), '', 1);

            // Display title
            if (!array_key_exists(0, $pages)) {
                return warn_screen(get_screen_title('WIKI'), do_lang_tempcode('MISSING_RESOURCE', 'wiki_page'));
            }
            $page = $pages[0];
            $current_title = get_translated_text($page['title']);
            $title_to_use = do_lang_tempcode('WIKI_PAGE', escape_html($current_title));
            $title_to_use_2 = do_lang('WIKI_PAGE', $current_title);
            if ((get_value('no_awards_in_titles') !== '1') && (addon_installed('awards'))) {
                require_code('awards');
                $awards = find_awards_for('wiki_page', strval($page['id']));
            } else {
                $awards = array();
            }
            $this->title = get_screen_title($title_to_use, false, null, null, $awards);

            if (!has_category_access(get_member(), 'wiki_page', strval($page['id']))) {
                access_denied('CATEGORY_ACCESS');
            }

            seo_meta_load_for('wiki_page', strval($id), $title_to_use_2);

            // Build up navigation tree
            $breadcrumbs = wiki_breadcrumbs($chain, $current_title, has_privilege(get_member(), 'open_virtual_roots'), true, true);

            $where_map = array('page_id' => $id);
            if ((!has_privilege(get_member(), 'see_unvalidated')) && (addon_installed('unvalidated'))) {
                $where_map['validated'] = 1;
            }
            $db_posts = $GLOBALS['SITE_DB']->query_select('wiki_posts', array('*'), $where_map, 'ORDER BY date_and_time', intval(get_option('general_safety_listing_limit')));
            $num_posts = count($db_posts);

            $description_comcode = get_translated_text($page['description']);

            set_extra_request_metadata(array(
                'identifier' => '_SEARCH:wiki:browse:' . strval($page['id']),
                'description' => (strlen($description_comcode) < 200) ? $description_comcode : '',
                'numposts' => strval($num_posts),
            ), $page, 'wiki_page', strval($id));

            breadcrumb_set_parents($breadcrumbs);

            // Redefined canonical URL
            global $CANONICAL_URL, $NON_CANONICAL_PARAMS;
            $non_canonical = array();
            if (is_array($NON_CANONICAL_PARAMS)) {
                foreach (array_keys($NON_CANONICAL_PARAMS) as $n) {
                    $non_canonical[$n] = null;
                }
            }
            $CANONICAL_URL = get_self_url(true, false, $non_canonical + array('type' => 'browse', 'id' => $id, 'find' => null));

            $this->id = $id;
            $this->chain = $chain;
            $this->page = $page;
            $this->current_title = $current_title;
            $this->title_to_use = $title_to_use;
            $this->title_to_use_2 = $title_to_use_2;
            $this->db_posts = $db_posts;
            $this->num_posts = $num_posts;
        }

        if ($type == 'revisions') {
            breadcrumb_set_parents(array(array('_SELF:_SELF:browse', do_lang_tempcode('WIKI'))));

            $this->title = get_screen_title('actionlog:REVISIONS');
        }

        if ($type == 'post') {
            $_chain = get_param_wiki_chain('id', strval(db_get_first_id()));
            $chain = $_chain[1];

            $posting = is_null(get_param_integer('post_id', null));

            $breadcrumbs = wiki_breadcrumbs($chain, null, true, true);
            $breadcrumbs[] = array('', do_lang_tempcode($posting ? 'MAKE_POST' : 'SAVE'));
            breadcrumb_set_parents($breadcrumbs);

            if ($posting) {
                $this->title = get_screen_title('WIKI_MAKE_POST');
            } else {
                $this->title = get_screen_title('WIKI_EDIT_POST');
            }

            $this->chain = $chain;
        }

        if ($type == '_post') {
            $posting = is_null(post_param_integer('post_id', null));

            if ($posting) {
                $this->title = get_screen_title('WIKI_MAKE_POST');
            } else {
                $this->title = get_screen_title('WIKI_EDIT_POST');
            }
        }

        if ($type == 'mg' || $type == 'do') {
            $this->title = get_screen_title('MERGE_WIKI_POSTS');
        }

        if ($type == 'move' || $type == '_move') {
            $this->title = get_screen_title('WIKI_MOVE_POST');
        }

        return null;
    }

    /**
     * Execute the module.
     *
     * @return Tempcode The result of execution.
     */
    public function run()
    {
        $type = get_param_string('type', 'browse');

        require_css('wiki');

        // Decide what to do
        if ($type == 'findpost') {
            $post_id = get_param_integer('id');
            $page_id = $GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'page_id', array('id' => $post_id));
            $redirect = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => $page_id), '_SELF', null, false, false, false, 'post_' . strval($post_id));
            return redirect_screen(get_screen_title('WIKI'), $redirect);
        }
        if ($type == 'browse') {
            return $this->page();
        }
        if ($type == 'random') {
            return $this->random();
        }
        if ($type == 'revisions') {
            return $this->revisions();
        }
        if ($type == 'mg') {
            return $this->do_wiki_merge_interface();
        }
        if ($type == 'do') {
            return $this->do_wiki_merge();
        }
        if ($type == 'move') {
            return $this->move();
        }
        if ($type == '_move') {
            return $this->_move();
        }
        if ($type == 'post') {
            return $this->post();
        }
        if ($type == '_post') {
            return $this->_post();
        }

        return new Tempcode();
    }

    /**
     * Redirect to a random page.
     *
     * @return Tempcode The UI
     */
    public function random()
    {
        attach_message(do_lang_tempcode('TAKEN_RANDOM_WIKI_PAGE'), 'inform');

        $num_pages = $GLOBALS['SITE_DB']->query_select_value('wiki_pages', 'MAX(id)');
        if ($num_pages <= db_get_first_id()) {
            $id = $num_pages;
        } else {
            $pages = array();
            do { // Loop. picking random pages between 0 and max-id till we find one that exists
                $id = mt_rand(db_get_first_id(), $num_pages);
                $pages = $GLOBALS['SITE_DB']->query_select('wiki_pages', array('*'), array('id' => $id), '', 1);
            } while (!array_key_exists(0, $pages));
        }
        $redir_url = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => $id), '_SELF');
        return redirect_screen(get_screen_title('RANDOM_PAGE'), $redir_url, '');
    }

    /**
     * The UI to show a page.
     *
     * @return Tempcode The UI
     */
    public function page()
    {
        $id = $this->id;
        $chain = $this->chain;
        $page = $this->page;
        $current_title = $this->current_title;
        $title_to_use = $this->title_to_use;
        $title_to_use_2 = $this->title_to_use_2;
        $db_posts = $this->db_posts;
        $num_posts = $this->num_posts;

        require_code('feedback');

        // We will use Conversr styling
        require_lang('cns');

        if (get_option('wiki_enable_content_posts') == '0') {
            $page['hide_posts'] = 1;
        }

        // Views
        if ((get_db_type() != 'xml') && (get_value('no_view_counts') !== '1') && (is_null(get_bot_type()))) {
            $page['wiki_views']++;
            if (!$GLOBALS['SITE_DB']->table_is_locked('wiki_pages')) {
                $GLOBALS['SITE_DB']->query_update('wiki_pages', array('wiki_views' => $page['wiki_views']), array('id' => $id), '', 1, null, false, true);
            }
        }

        // Description
        $description = get_translated_tempcode('wiki_pages', $page, 'description');
        $description_comcode = get_translated_text($page['description']);

        // Child Links
        $num_children = 0;
        $children = array();
        if (get_option('wiki_enable_children') == '1') {
            $children_rows = $GLOBALS['SITE_DB']->query_select('wiki_children c LEFT JOIN ' . get_table_prefix() . 'wiki_pages p ON c.child_id=p.id', array('child_id', 'c.title', 'hide_posts', 'description'), array('c.parent_id' => $id), 'ORDER BY c.the_order');
            foreach ($children_rows as $myrow) {
                $child_id = $myrow['child_id'];

                if (!has_category_access(get_member(), 'wiki_page', strval($child_id))) {
                    continue;
                }

                if (get_option('wiki_enable_content_posts') == '0') {
                    $myrow['hide_posts'] = 1;
                }

                $child_title = $myrow['title'];

                $child_description = get_translated_text($myrow['description']);

                $my_child_posts = $GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'COUNT(*)', array('page_id' => $child_id));
                $my_child_children = $GLOBALS['SITE_DB']->query_select_value('wiki_children', 'COUNT(*)', array('parent_id' => $child_id));

                $url = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => wiki_derive_chain($child_id)), '_SELF');
                $children[] = array(
                    'URL' => $url,
                    'CHILD' => $child_title,

                    'MY_CHILD_POSTS' => integer_format($my_child_posts),
                    'MY_CHILD_CHILDREN' => integer_format($my_child_children),
                    'BODY_CONTENT' => (trim($child_description) != '') ? strval(strlen($child_description)) : '0',
                    'HIDE_POSTS' => $myrow['hide_posts'] == 1,
                );

                $num_children++;
            }
        }

        $staff_access = has_privilege(get_member(), 'edit_lowrange_content', 'cms_wiki', array('wiki_page', $id));

        // Main text (posts)
        $posts = new Tempcode();
        $include_expansion = (strpos($description_comcode, '[attachment') !== false);
        foreach ($db_posts as $myrow) {
            // Work out posters details
            $poster = $myrow['member_id'];
            $username = $GLOBALS['FORUM_DRIVER']->get_username($poster);
            if (is_null($username)) {
                $username = do_lang('UNKNOWN');
            }

            $post_id = $myrow['id'];

            // Date post was made
            $post_date_raw = $myrow['date_and_time'];
            $post_date = get_timezoned_date($myrow['date_and_time']);

            // Rating
            actualise_rating(true, 'wiki_post', strval($post_id), build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => $chain), '_SELF'), $current_title);
            $rating_array = get_rating_simple_array(build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => $chain), '_SELF'), $current_title, 'wiki_post', strval($post_id), 'WIKI_RATING_FORM', $poster);
            if (!is_null($rating_array)) {
                $rating = do_template('WIKI_RATING', $rating_array);
            } else {
                $rating = new Tempcode();
            }

            // Display the post then ;)
            $post_comcode = get_translated_text($myrow['the_message']);
            $include_expansion_here = (strpos($post_comcode, '[attachment') !== false);
            if ($include_expansion_here) {
                $include_expansion = true;
            }
            $post = get_translated_tempcode('wiki_posts', $myrow, 'the_message');
            if ((has_edit_permission('low', get_member(), $poster, 'cms_wiki', array('wiki_page', $id))) && (($id != db_get_first_id()) || (has_privilege(get_member(), 'feature')))) {
                $edit_url = build_url(array('page' => '_SELF', 'type' => 'post', 'id' => $chain, 'post_id' => $post_id), '_SELF');
                $extra = do_template('BUTTON_SCREEN_ITEM', array('_GUID' => '37404e2e5cf7e4cb806f796e9df90898', 'REL' => 'edit', 'IMMEDIATE' => false, 'URL' => $edit_url, 'FULL_TITLE' => do_lang_tempcode('EDIT'), 'TITLE' => do_lang_tempcode('EDIT'), 'IMG' => 'buttons__edit'));
                $move_url = build_url(array('page' => '_SELF', 'type' => 'move', 'id' => $chain, 'post_id' => $post_id), '_SELF');
                $extra->attach(do_template('BUTTON_SCREEN_ITEM', array('_GUID' => 'b4325cd1bac924cc83771d4c3c41be8b', 'REL' => 'move', 'IMMEDIATE' => false, 'URL' => $move_url, 'FULL_TITLE' => do_lang_tempcode('MOVE'), 'TITLE' => do_lang_tempcode('MOVE'), 'IMG' => 'buttons__move')));
            } else {
                $extra = new Tempcode();
            }
            $poster_url = is_guest($poster) ? '' : $GLOBALS['FORUM_DRIVER']->member_profile_url($poster, false, true);
            $rate_url = get_self_url(true);
            $posts->attach(do_template('WIKI_POST', array(
                '_GUID' => 'a29b107abfaf7689c8392676c63093f5',
                'INCLUDE_EXPANSION' => $include_expansion_here,
                'UNVALIDATED' => ($myrow['validated'] == 0) ? do_lang_tempcode('UNVALIDATED') : new Tempcode(),
                'STAFF_ACCESS' => $staff_access,
                'RATE_URL' => $rate_url . '#post_' . strval($post_id),
                'RATING' => $rating,
                'ID' => strval($myrow['id']),
                'POSTER_URL' => $poster_url,
                'POSTER' => $username,
                'POST_DATE_RAW' => strval($post_date_raw),
                'POST_DATE' => $post_date,
                'POST' => $post,
                'BUTTONS' => $extra,
            )));
        }

        if ($num_posts >= intval(get_option('general_safety_listing_limit'))) {
            attach_message(do_lang_tempcode('TOO_MANY_WIKI_POSTS'), 'warn');
        }

        $buttons = $this->_render_screen_buttons($chain, $id, $include_expansion, $num_posts < intval(get_option('general_safety_listing_limit')));

        return do_template('WIKI_PAGE_SCREEN', array(
            '_GUID' => '1840d6934be3344c4f93a159fc737a45',
            'TAGS' => get_loaded_tags('wiki_pages'),
            'HIDE_POSTS' => $page['hide_posts'] == 1,
            'ID' => strval($id),
            'CHAIN' => $chain,
            'VIEWS' => integer_format($page['wiki_views']),
            'STAFF_ACCESS' => $staff_access,
            'DESCRIPTION' => $description,
            'TITLE' => $this->title,
            'CHILDREN' => $children,
            'POSTS' => $posts,
            'NUM_POSTS' => integer_format($num_posts),
            'BUTTONS' => $buttons,
        ));
    }

    /**
     * Show the buttons on the Wiki+ page viewing screen.
     *
     * @param  SHORT_TEXT $chain The ID chain being used to get to this page
     * @param  AUTO_LINK $id The ID of the page we are showing the menu on
     * @param  boolean $include_expansion Whether to include the expansion/contraction button
     * @param  boolean $may_post Whether posting is generally allowed (may be passed false if too many posts)
     * @return Tempcode The button Tempcode
     */
    public function _render_screen_buttons($chain, $id, $include_expansion, $may_post = true)
    {
        $page_url = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => $chain), '_SELF');

        /*if ((addon_installed('search')) && (has_actual_page_access(get_member(),'search'))) { // Not enough space
            $search_url = build_url(array('page' => 'search', 'type' => 'browse', 'id' => 'wiki_posts', 'search_under' => $id), get_module_zone('search'));
            $search_button = do_template('BUTTON_SCREEN', array('_GUID' => 'ad8783a0af3a35f21022b30397f1b03e', 'IMMEDIATE' => false, 'REL' => 'search', 'URL' => $search_url, 'TITLE' => do_lang_tempcode('SEARCH'), 'IMG' => 'buttons__search'));
        } else */
        $search_button = new Tempcode();

        if (addon_installed('actionlog')) {
            $revisions_url = build_url(array('page' => '_SELF', 'type' => 'revisions', 'id' => $chain), '_SELF');
            $revisions_button = do_template('BUTTON_SCREEN', array('_GUID' => '99ad7faac817326510583a69ac719d58', 'IMMEDIATE' => false, 'REL' => 'revisions', 'URL' => $revisions_url, 'TITLE' => do_lang_tempcode('actionlog:REVISIONS'), 'IMG' => 'buttons__revisions'));
        }

        if ((get_option('wiki_enable_children') == '1') && (has_privilege(get_member(), 'wiki_manage_tree', 'cms_wiki', array('wiki_page', $id))) && (has_actual_page_access(get_member(), 'cms_wiki'))) {
            $tree_url = build_url(array('page' => 'cms_wiki', 'type' => 'edit_tree', 'id' => $chain, 'redirect' => get_self_url(true, true)), get_module_zone('cms_wiki'));
            $tree_button = do_template('BUTTON_SCREEN', array('_GUID' => 'e6edc9f39b6b0aff86cffbaa98c51827', 'REL' => 'edit', 'IMMEDIATE' => false, 'URL' => $tree_url, 'TITLE' => do_lang_tempcode('__WIKI_EDIT_TREE'), 'IMG' => 'buttons__edit_tree'));
        } else {
            $tree_button = new Tempcode();
        }

        if ((has_edit_permission('cat_low', get_member(), null, 'cms_wiki', array('wiki_page', $id))) && (has_actual_page_access(get_member(), 'cms_wiki'))) {
            $edit_url = build_url(array('page' => 'cms_wiki', 'type' => 'edit_page', 'id' => $chain, 'redirect' => get_self_url(true, true)), get_module_zone('cms_wiki'));
            $edit_button = do_template('BUTTON_SCREEN', array('_GUID' => '5d8783a0af3a35f21022b30397f1b03e', 'REL' => 'edit', 'IMMEDIATE' => false, 'URL' => $edit_url, 'TITLE' => do_lang_tempcode('_WIKI_EDIT_PAGE'), 'IMG' => 'buttons__edit'));
        } else {
            $edit_button = new Tempcode();
        }

        if (($may_post) && (has_submit_permission('low', get_member(), get_ip_address(), 'cms_wiki', array('wiki_page', $id))) && (($id != db_get_first_id()) || (has_privilege(get_member(), 'feature')))) {
            $post_url = build_url(array('page' => '_SELF', 'type' => 'post', 'id' => $chain), '_SELF');
            $post_button = do_template('BUTTON_SCREEN', array('_GUID' => 'c26462f34a64c4bf80c1fb7c40102eb0', 'IMMEDIATE' => false, 'URL' => $post_url, 'TITLE' => do_lang_tempcode('MAKE_POST'), 'IMG' => 'buttons__new_reply'));
        } else {
            $post_button = new Tempcode();
        }

        $tpl = new Tempcode();
        $tpl->attach($search_button);
        if (addon_installed('actionlog')) {
            $tpl->attach($revisions_button);
        }
        $tpl->attach($post_button);
        $tpl->attach($tree_button);
        $tpl->attach($edit_button);
        return $tpl;
    }

    /**
     * The UI to show revisions.
     * More details are shown in the actionlog, which is linked from here.
     *
     * @return Tempcode The UI
     */
    public function revisions()
    {
        $_id = get_param_string('id', null);
        $id = null;
        if (!is_null($_id)) {
            list($id,) = get_param_wiki_chain('id');
        }

        $_fields_titles = array(
            do_lang_tempcode('PAGE'),
            do_lang_tempcode('MEMBER'),
            do_lang_tempcode('DATE'),
            do_lang_tempcode('ACTION'),
        );

        require_code('revisions_engine_database');
        $revision_engine = new RevisionEngineDatabase();
        return $revision_engine->ui_browse_revisions(
            $this->title,
            $_fields_titles,
            array('wiki_page', 'wiki_post'),
            array($this, '_render_revision'),
            null,
            ($id === null) ? null : strval($id),
            null,
            'wiki_page'
        );
    }

    /**
     * Render a revision.
     *
     * @param array $revision A revision map.
     * @return ?Tempcode A rendered revision row (null: won't render).
     */
    public function _render_revision($revision)
    {
        $_id = get_param_string('id', null);
        $id = null;
        if (!is_null($_id)) {
            list($id,) = get_param_wiki_chain('id');
        }

        $page_id = intval($revision['r_category_id']);

        $l = $GLOBALS['SITE_DB']->query_select_value_if_there('wiki_pages', 'title', array('id' => $page_id));
        if (is_null($l)) {
            return null;
        }

        $chain = is_null($id) ? wiki_derive_chain($page_id) : $_id;
        $view_link = span(breadcrumb_segments_to_tempcode(wiki_breadcrumbs($chain, get_translated_text($l), true)), '', 'breadcrumbs');

        $member_link = $GLOBALS['FORUM_DRIVER']->member_profile_hyperlink($revision['log_member_id']);

        $date = get_timezoned_date($revision['log_time']);

        $action = do_lang_tempcode($revision['log_action']);
        $do_actionlog = has_actual_page_access(get_member(), 'admin_actionlog');
        if ($do_actionlog) {
            $actionlog_url = build_url(array('page' => 'admin_actionlog', 'type' => 'view', 'id' => is_null($revision['r_actionlog_id']) ? $revision['r_moderatorlog_id'] : $revision['r_actionlog_id'], 'mode' => is_null($revision['r_actionlog_id']) ? 'cns' : 'cms'), get_module_zone('admin_actionlog'));
            $action = hyperlink($actionlog_url, $action, false, false, strval($revision['r_actionlog_id']));
        }

        $_revision = array(
            $view_link,
            $member_link,
            escape_html($date),
            $action,
        );
        require_code('templates_results_table');
        return results_entry($_revision, false);
    }

    /**
     * Get markers of posts from the POST/GET.
     *
     * @return array A list of markers.
     */
    public function get_markers()
    {
        $markers = array();
        foreach (array_keys($_REQUEST) as $key) {
            if (substr($key, 0, 5) == 'mark_') {
                $markers[] = intval(substr($key, 5));
            }
        }
        return $markers;
    }

    /**
     * The UI for merging Wiki+ posts.
     *
     * @return Tempcode The UI.
     */
    public function do_wiki_merge_interface()
    {
        $_redir_url = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => get_param_string('id', false, true)), '_SELF');
        $redir_url = $_redir_url->evaluate();
        $merge_url = build_url(array('page' => '_SELF', 'type' => 'do', 'id' => get_param_string('id', false, true), 'redirect' => $redir_url), '_SELF', null, true);

        $merged = '';
        $markers = $this->get_markers();
        if (count($markers) == 0) {
            warn_exit(do_lang_tempcode('NOTHING_SELECTED'));
        }
        foreach ($markers as $id) {
            $rows = $GLOBALS['SITE_DB']->query_select('wiki_posts', array('*'), array('id' => $id), '', 1);
            if (!array_key_exists(0, $rows)) {
                continue;
            }
            $myrow = $rows[0];

            if (!has_category_access(get_member(), 'wiki_page', strval($myrow['page_id']))) {
                access_denied('CATEGORY_ACCESS');
            }
            check_edit_permission('low', null, array('wiki_page', $myrow['page_id']), 'cms_wiki');

            if ($merged != '') {
                $merged .= "\n\n";
            }
            $merged .= get_translated_text($myrow['the_message']);
        }

        require_code('form_templates');

        $posting_form = get_posting_form(do_lang('MERGE_WIKI_POSTS'), 'menu___generic_admin__merge', $merged, $merge_url, new Tempcode(), new Tempcode());

        return do_template('POSTING_SCREEN', array('_GUID' => '4372327fb689ef70a9ac5d275dd454f1', 'POSTING_FORM' => $posting_form, 'HIDDEN' => '', 'TITLE' => $this->title, 'TEXT' => do_lang_tempcode('WIKI_MERGE_TEXT')));
    }

    /**
     * The actualiser for merging Wiki+ posts.
     *
     * @return Tempcode The UI.
     */
    public function do_wiki_merge()
    {
        check_edit_permission('low', null, array('wiki_page', get_param_string('id', false, true)), 'cms_wiki');

        require_code('comcode_check');

        @ignore_user_abort(true);

        $page_id = get_param_integer('id');

        $page_title = $GLOBALS['SITE_DB']->query_select_value('wiki_pages', 'page_title', array('id' => $page_id));

        $message = post_param_string('post');
        check_comcode($message, null, false, null, true);
        $map = array(
            'edit_date' => null,
            'member_id' => get_member(),
            'date_and_time' => time(),
            'page_id' => $page_id,
            'validated' => 1,
            'wiki_views' => 0,
        );
        if (multi_lang_content()) {
            $map['the_message'] = 0;
        } else {
            $map['the_message'] = '';
            $map['the_message__text_parsed'] = '';
            $map['the_message__source_user'] = get_member();
        }
        $post_id = $GLOBALS['SITE_DB']->query_insert('wiki_posts', $map, true);
        require_code('attachments2');
        $map = array();
        $map += insert_lang_comcode_attachments('the_message', 2, $message, 'wiki_post', strval($post_id));
        $GLOBALS['SITE_DB']->query_update('wiki_posts', $map, array('id' => $post_id), '', 1);

        @ignore_user_abort(false);

        $markers = $this->get_markers();
        foreach ($markers as $id) {
            wiki_delete_post($id);
        }

        log_it('MERGE_WIKI_POSTS', strval($page_id), $page_title);

        // Show it worked / Refresh
        $url = get_param_string('redirect');
        return redirect_screen($this->title, $url, do_lang_tempcode('SUCCESS'));
    }

    /**
     * The UI for moving a Wiki+ post.
     *
     * @return Tempcode The UI.
     */
    public function move()
    {
        $_id = get_param_wiki_chain('id');
        $id = $_id[0];
        $post_id = get_param_integer('post_id');

        $original_poster = $GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'member_id', array('id' => $post_id));

        $true_page_id = $GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'page_id', array('id' => $post_id));
        if (!has_category_access(get_member(), 'wiki_page', strval($true_page_id))) {
            access_denied('CATEGORY_ACCESS');
        }
        check_edit_permission('low', $original_poster, array('wiki_page', $true_page_id), 'cms_wiki');

        $_redir_url = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => get_param_string('id', false, true)), '_SELF');
        $redir_url = $_redir_url->evaluate();
        $move_url = build_url(array('page' => '_SELF', 'type' => '_move', 'id' => get_param_string('id', false, true), 'redirect' => $redir_url), '_SELF');

        require_code('form_templates');

        $fields = form_input_tree_list(do_lang_tempcode('DESTINATION'), '', 'target', null, 'choose_wiki_page', array(), true, strval($id));

        $hidden = form_input_hidden('source', strval($post_id));

        return do_template('FORM_SCREEN', array(
            '_GUID' => 'f231626424aa83d75df571a818665152',
            'SKIP_WEBSTANDARDS' => true,
            'TITLE' => $this->title,
            'URL' => $move_url,
            'TEXT' => do_lang_tempcode('SELECT_TARGET_POST_DESTINATION'),
            'FIELDS' => $fields,
            'HIDDEN' => $hidden,
            'SUBMIT_ICON' => 'buttons__move',
            'SUBMIT_NAME' => do_lang_tempcode('MOVE'),
        ));
    }

    /**
     * The actualiser for moving a Wiki+ post.
     *
     * @return Tempcode The UI.
     */
    public function _move()
    {
        $post_id = post_param_integer('source');
        $target = post_param_integer('target');
        $_id = get_param_wiki_chain('id');
        $id = $_id[0];

        $true_page_id = $GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'page_id', array('id' => $post_id));
        if (!has_category_access(get_member(), 'wiki_page', strval($true_page_id))) {
            access_denied('CATEGORY_ACCESS');
        }

        $original_poster = $GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'member_id', array('id' => $post_id));
        check_edit_permission('low', $original_poster, array('wiki_page', $true_page_id), 'cms_wiki');

        // Check user info
        $member = get_member();
        if ($target == db_get_first_id()) {
            check_privilege('feature');
        }

        if ($id == $target) {
            return warn_screen($this->title, do_lang_tempcode('INVALID_OPERATION'));
        } else {
            $GLOBALS['SITE_DB']->query_update('wiki_posts', array('page_id' => $target), array('id' => $post_id), '', 1);

            if (addon_installed('actionlog')) {
                require_code('revisions_engine_database');
                $revision_engine = new RevisionEngineDatabase();
                $revision_engine->recategorise_old_revisions('wiki_post', strval($post_id), strval($target));
            }

            log_it('WIKI_MOVE_POST', strval($post_id), strval($target));

            // Show it worked / Refresh
            $url = get_param_string('redirect');
            return redirect_screen($this->title, $url, do_lang_tempcode('SUCCESS'));
        }
    }

    /**
     * The UI for making a Wiki+ post.
     *
     * @return Tempcode The UI.
     */
    public function post()
    {
        $post_id = get_param_integer('post_id', null);
        $mode = ($post_id === null) ? 'post' : 'edit';

        require_code('form_templates');

        $specialisation = new Tempcode();

        $parsed = null;

        if ($mode == 'post') {
            url_default_parameters__enable();
        }

        if ($mode == 'edit') {
            $rows = $GLOBALS['SITE_DB']->query_select('wiki_posts', array('*'), array('id' => $post_id), '', 1);
            if (!array_key_exists(0, $rows)) {
                warn_exit(do_lang_tempcode('MISSING_RESOURCE', 'wiki_post'));
            }
            $myrow = $rows[0];

            $_id = get_param_wiki_chain('id', strval($myrow['page_id']));
            $id = $_id[0];

            if (!has_category_access(get_member(), 'wiki_page', strval($myrow['page_id']))) {
                access_denied('CATEGORY_ACCESS');
            }

            $original_poster = $myrow['member_id'];
            check_edit_permission('low', $original_poster, array('wiki_page', $myrow['page_id']), 'cms_wiki');

            // If we are editing, we need to retrieve the message
            $message = get_translated_text($myrow['the_message']);
            $parsed = get_translated_tempcode('wiki_posts', $myrow, 'the_message');

            require_code('content2');
            $specialisation->attach(metadata_get_fields('wiki_post', strval($post_id)));

            if (has_delete_permission('low', get_member(), $original_poster, 'cms_wiki', array('wiki_page', $myrow['page_id']))) {
                $specialisation->attach(do_template('FORM_SCREEN_FIELD_SPACER', array('_GUID' => '569be0b840914473a0928606a045f838', 'TITLE' => do_lang_tempcode('ACTIONS'))));
                $specialisation->attach(form_input_tick(do_lang_tempcode('DELETE'), do_lang_tempcode('DESCRIPTION_DELETE'), 'delete', false));
            }

            $submit_name = do_lang_tempcode('SAVE');

            $validated = $myrow['validated'];

            list($warning_details, $ping_url) = handle_conflict_resolution();

            if (has_privilege(get_member(), 'bypass_validation_lowrange_content', 'cms_wiki', array('wiki_page', $myrow['page_id']))) {
                $specialisation->attach(form_input_tick(do_lang_tempcode('VALIDATED'), do_lang_tempcode($GLOBALS['FORUM_DRIVER']->is_super_admin(get_member()) ? 'DESCRIPTION_VALIDATED_SIMPLE' : 'DESCRIPTION_VALIDATED', 'wiki_post'), 'validated', $validated == 1));
            }
        } else {
            $_id = get_param_wiki_chain('id');
            $id = $_id[0];

            if ($GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'COUNT(*)', array('page_id' => $id)) >= intval(get_option('general_safety_listing_limit'))) {
                warn_exit(do_lang_tempcode('TOO_MANY_WIKI_POSTS'));
            }

            check_submit_permission('low', array('wiki_page', $id), 'cms_wiki');

            $message = '';

            $submit_name = do_lang_tempcode('MAKE_POST');

            $validated = 1;

            list($warning_details, $ping_url) = array(null, null);

            require_code('content2');
            $specialisation->attach(metadata_get_fields('wiki_post', null));

            if (has_privilege(get_member(), 'bypass_validation_lowrange_content', 'cms_wiki')) {
                $specialisation->attach(form_input_tick(do_lang_tempcode('VALIDATED'), do_lang_tempcode($GLOBALS['FORUM_DRIVER']->is_super_admin(get_member()) ? 'DESCRIPTION_VALIDATED_SIMPLE' : 'DESCRIPTION_VALIDATED', 'wiki_post'), 'validated', $validated == 1));
            }
        }

        $hidden_fields = new Tempcode();

        require_code('fields');
        if (has_tied_catalogue('wiki_post')) {
            append_form_custom_fields('wiki_post', ($mode == 'edit') ? strval($post_id) : null, $specialisation, $hidden_fields);
        }

        $text = new Tempcode();

        list($page_id,) = get_param_wiki_chain('id', strval(db_get_first_id()));
        require_lang('notifications');
        if (addon_installed('actionlog')) {
            require_code('revisions_engine_database');
            $revision_engine = new RevisionEngineDatabase(false);
            $notify = ($revision_engine->find_most_recent_category_change('wiki_post', strval($page_id)) < time() - 60 * 10);
        } else {
            $notify = true;
        }
        $radios = form_input_radio_entry('send_notification', '0', !$notify, do_lang_tempcode('NO'));
        $radios->attach(form_input_radio_entry('send_notification', '1', $notify, do_lang_tempcode('YES')));
        $specialisation->attach(form_input_radio(do_lang_tempcode('SEND_NOTIFICATION'), do_lang_tempcode('DESCRIPTION_SEND_NOTIFICATION'), 'send_notification', $radios));

        if (addon_installed('captcha')) {
            require_code('captcha');
            if (use_captcha()) {
                $specialisation->attach(form_input_captcha());
                $text->attach(paragraph(do_lang_tempcode('FORM_TIME_SECURITY')));
            }
        }

        if (addon_installed('points')) {
            $login_url = build_url(array('page' => 'login', 'type' => 'browse', 'redirect' => get_self_url(true, true)), get_module_zone('login'));
            $_login_url = escape_html($login_url->evaluate());
            if ((is_guest()) && ((get_forum_type() != 'cns') || (has_actual_page_access(get_member(), 'join')))) {
                $text->attach(paragraph(do_lang_tempcode('NOT_LOGGED_IN_NO_CREDIT', $_login_url)));
            }
        }

        // Awards?
        if (addon_installed('awards')) {
            require_code('awards');
            $specialisation->attach(get_award_fields('wiki_post', ($post_id === null) ? null : strval($post_id)));
        } else {
            $awards = array();
        }

        $message = post_param_string('message', $message);

        $chain = $this->chain;

        $breadcrumbs = breadcrumb_segments_to_tempcode(wiki_breadcrumbs($chain, null, true, true));

        $_redir_url = build_url(array('page' => '_SELF', 'type' => 'browse', 'id' => get_param_string('id', strval($id), true)), '_SELF');
        $redir_url = $_redir_url->evaluate();
        $post_url = build_url(array('page' => '_SELF', 'type' => '_post', 'id' => get_param_string('id', strval(db_get_first_id()), false), 'redirect' => $redir_url), '_SELF');

        $hidden_fields->attach(form_input_hidden('post_id', ($post_id === null) ? '' : strval($post_id)));

        $javascript = (function_exists('captcha_ajax_check') ? captcha_ajax_check() : '');

        $posting_form = get_posting_form($submit_name, ($mode == 'edit') ? 'menu___generic_admin__edit_this' : 'menu___generic_admin__add_one', $message, $post_url, $hidden_fields, new Tempcode(), null, '', $specialisation, $parsed, $javascript);

        if ($mode == 'post') {
            url_default_parameters__disable();
        }

        return do_template('WIKI_POSTING_SCREEN', array('_GUID' => 'efdea6198cba136eb6809937c2322458', 'PING_URL' => $ping_url, 'WARNING_DETAILS' => $warning_details, 'TEXT' => $text, 'TITLE' => $this->title, 'POSTING_FORM' => $posting_form));
    }

    /**
     * The actualiser for making a Wiki+ post.
     *
     * @return Tempcode The UI.
     */
    public function _post()
    {
        if (addon_installed('captcha')) {
            require_code('captcha');
            enforce_captcha();
        }

        $post_id = post_param_integer('post_id', null);
        $mode = ($post_id === null) ? 'post' : 'edit';

        require_code('uploads');

        $_id = get_param_wiki_chain('id');
        $id = $_id[0];
        if ($mode == 'edit') {
            $delete = post_param_integer('delete', 0);
        } else {
            if ($GLOBALS['SITE_DB']->query_select_value('wiki_posts', 'COUNT(*)', array('id' => $id)) >= intval(get_option('general_safety_listing_limit'))) {
                warn_exit(do_lang_tempcode('TOO_MANY_WIKI_POSTS'));
            }
        }

        // Post Text
        $message = post_param_string('post');

        $validated = post_param_integer('validated', 0);

        if ($id == db_get_first_id()) {
            check_privilege('feature');
        }

        // Do it
        if ($mode == 'post') {
            require_code('antispam');
            inject_action_spamcheck();
            if (!has_privilege(get_member(), 'bypass_validation_lowrange_content', 'cms_wiki', array('wiki_page', $id))) {
                $validated = 0;
            }
            if (!has_category_access(get_member(), 'wiki_page', strval($id))) {
                access_denied('CATEGORY_ACCESS');
            }

            check_submit_permission('low', null, 'cms_wiki');

            require_code('content2');
            $metadata = actual_metadata_get_fields('wiki_post', null);

            require_code('content2');
            $post_id = wiki_add_post($id, $message, $validated, $metadata['submitter'], true, $metadata['add_time'], $metadata['views']);

            set_url_moniker('wiki_post', strval($post_id));

            if ($validated == 0) {
                require_code('submit');
                $edit_url = build_url(array('page' => 'wiki', 'type' => 'post', 'post_id' => $post_id, 'validated' => 1), '_SELF', null, false, false, true);
                if (addon_installed('unvalidated')) {
                    send_validation_request('WIKI_MAKE_POST', 'wiki_posts', false, strval($post_id), $edit_url);
                }
            }
        } else {
            $rows = $GLOBALS['SITE_DB']->query_select('wiki_posts', array('*'), array('id' => $post_id), '', 1);
            if (!array_key_exists(0, $rows)) {
                warn_exit(do_lang_tempcode('MISSING_RESOURCE', 'wiki_post'));
            }
            $myrow = $rows[0];
            if (!has_category_access(get_member(), 'wiki_page', strval($myrow['page_id']))) {
                access_denied('CATEGORY_ACCESS');
            }

            $original_poster = $myrow['member_id'];

            if (!has_privilege(get_member(), 'bypass_validation_lowrange_content', 'cms_wiki', array('wiki_page', $myrow['page_id']))) {
                $validated = 0;
            }

            if ($delete == 1) {
                check_delete_permission('low', $original_poster, array('wiki_page', $myrow['page_id']), 'cms_wiki');

                wiki_delete_post($post_id);

                require_code('fields');
                if (has_tied_catalogue('wiki_post')) {
                    delete_form_custom_fields('wiki_post', strval($post_id));
                }
            } else {
                check_edit_permission('low', $original_poster, array('wiki_page', $myrow['page_id']), 'cms_wiki');

                require_code('content2');
                $metadata = actual_metadata_get_fields('wiki_post', strval($post_id));

                wiki_edit_post($post_id, $message, $validated, $metadata['submitter'], null, $metadata['edit_time'], $metadata['add_time'], $metadata['views'], true);
            }
        }

        require_code('fields');
        if (has_tied_catalogue('wiki_post')) {
            save_form_custom_fields('wiki_post', strval($post_id));
        }

        if (addon_installed('awards')) {
            require_code('awards');
            handle_award_setting('wiki_post', strval($post_id));
        }

        // Show it worked / Refresh
        $url = get_param_string('redirect');
        return redirect_screen($this->title, $url, do_lang_tempcode('SUCCESS'));
    }
}
