Ejemplo n.º 1
0
 /**
  * Index function
  *
  * @access	public
  * @return	void
  */
 function index($message = '')
 {
     $this->load->helper('html');
     $this->load->helper('search');
     $vars['cp_page_title'] = $this->lang->line('search_results');
     $this->cp->set_variable('cp_page_title', $vars['cp_page_title']);
     // Saved search
     if ($search = $this->input->get('saved')) {
         $search = base64_decode(rawurldecode($search));
     } else {
         $search = $this->input->get_post('cp_search_keywords', TRUE);
     }
     if (!$this->cp_search->_check_index()) {
         // Save the search
         $search = rawurlencode(base64_encode($search));
         if ($this->input->get('ajax')) {
             // Force a js redirect
             $url = str_replace('&', '&', BASE) . '&C=search&M=build_index&saved=' . $search;
             echo '<script type="text/javascript">window.location="' . $url . '";</script>';
             exit;
         }
         // Degrade 'nicely'
         $this->functions->redirect(BASE . AMP . 'C=search' . AMP . 'M=build_index' . AMP . 'saved=' . $search);
     }
     $vars['keywords'] = sanitize_search_terms($search);
     $vars['can_rebuild'] = $this->cp->allowed_group('can_access_utilities');
     $vars['search_data'] = $this->cp_search->generate_results($search);
     $vars['num_rows'] = count($vars['search_data']);
     if ($this->input->get('ajax')) {
         echo $this->load->view('search/sidebar', $vars, TRUE);
         exit;
     }
     $this->javascript->compile();
     $this->load->view('search/results', $vars);
 }
Ejemplo n.º 2
0
 /**
  * Index function
  *
  * @access	public
  * @return	void
  */
 function index()
 {
     ee()->load->helper('html');
     ee()->load->helper('search');
     $vars['cp_page_title'] = lang('search_results');
     ee()->view->cp_page_title = $vars['cp_page_title'];
     // Saved search
     if ($search = ee()->input->get('saved')) {
         $search = base64_decode(rawurldecode($search));
     } else {
         $search = ee()->input->get_post('cp_search_keywords', TRUE);
     }
     if (!ee()->cp_search->_check_index()) {
         // Save the search
         $search = rawurlencode(base64_encode($search));
         if (AJAX_REQUEST) {
             // Force a js redirect
             $url = cp_url('search/build_index', array('saved' => $search));
             $url = str_replace('&amp;', '&', $url);
             echo '<script type="text/javascript">window.location="' . $url . '";</script>';
             exit;
         }
         // Degrade 'nicely'
         ee()->functions->redirect(cp_url('search/build_index', array('saved' => $search)));
     }
     $vars['keywords'] = sanitize_search_terms($search);
     $vars['can_rebuild'] = ee()->cp->allowed_group('can_access_utilities');
     $vars['search_data'] = ee()->cp_search->generate_results($search);
     $vars['num_rows'] = count($vars['search_data']);
     if (AJAX_REQUEST) {
         echo ee()->load->view('search/sidebar', $vars, TRUE);
         exit;
     }
     ee()->cp->render('search/results', $vars);
 }
    function add_items($channel_id = '', $message = '', $extra_sql = '', $search_url = '', $form_url = '', $action = '', $extra_fields_search = '', $extra_fields_entries = '', $heading = '')
    {
        ee()->lang->loadfile('content');
        ee()->load->helper('url');
        $channel_id = '';
        $extra_sql = array();
        ee()->db->select('entry_id');
        $query = ee()->db->get('simple_commerce_items');
        if ($query->num_rows() > 0) {
            $extra_sql['where'] = " AND exp_channel_titles.entry_id NOT IN ('";
            foreach ($query->result_array() as $row) {
                $extra_sql['where'] .= $row['entry_id'] . "','";
            }
            $extra_sql['where'] = substr($extra_sql['where'], 0, -2) . ') ';
        }
        ee()->load->library('api');
        // $action, $extra_fields_*, and $heading are used by move_comments
        $vars['message'] = $message;
        $action = $action ? $action : ee()->input->get_post('action');
        // Security check
        if (!ee()->cp->allowed_group('can_access_edit')) {
            show_error(lang('unauthorized_access'));
        }
        ee()->load->library('pagination');
        ee()->load->library('table');
        ee()->load->helper(array('form', 'text', 'url', 'snippets'));
        ee()->api->instantiate('channel_categories');
        ee()->load->model('channel_model');
        ee()->load->model('channel_entries_model');
        ee()->load->model('category_model');
        ee()->load->model('status_model');
        // Load the search helper so we can filter the keywords
        ee()->load->helper('search');
        ee()->view->cp_page_title = lang('edit');
        ee()->cp->add_js_script('ui', 'datepicker');
        ee()->javascript->output(array(ee()->javascript->hide(".paginationLinks .first"), ee()->javascript->hide(".paginationLinks .previous")));
        ee()->javascript->output('
			$(".toggle_all").toggle(
				function(){
					$("input.toggle").each(function() {
						this.checked = true;
					});
				}, function (){
					var checked_status = this.checked;
					$("input.toggle").each(function() {
						this.checked = false;
					});
				}
			);
		');
        ee()->jquery->tablesorter('.mainTable', '{
			headers: {
			2: {sorter: false},
			3: {
				// BLARG!!! This should be human readable sorted...
			},
			5: {dateFormat: "mm/dd/yy"},
			8: {sorter: false}
		},
			widgets: ["zebra"]
		}');
        ee()->javascript->output('
			$("#custom_date_start_span").datepicker({
				dateFormat: "yy-mm-dd",
				prevText: "<<",
				nextText: ">>",
				onSelect: function(date) {
					$("#custom_date_start").val(date);
					dates_picked();
				}
			});
			$("#custom_date_end_span").datepicker({
				dateFormat: "yy-mm-dd",
				prevText: "<<",
				nextText: ">>",
				onSelect: function(date) {
					$("#custom_date_end").val(date);
					dates_picked();
				}
			});

			$("#custom_date_start, #custom_date_end").focus(function(){
				if ($(this).val() == "yyyy-mm-dd")
				{
					$(this).val("");
				}
			});

			$("#custom_date_start, #custom_date_end").keypress(function(){
				if ($(this).val().length >= 9)
				{
					dates_picked();
				}
			});

			function dates_picked()
			{
				if ($("#custom_date_start").val() != "yyyy-mm-dd" && $("#custom_date_end").val() != "yyyy-mm-dd")
				{
					// populate dropdown box
					focus_number = $("#date_range").children().length;
					$("#date_range").append("<option id=\\"custom_date_option\\">" + $("#custom_date_start").val() + " to " + $("#custom_date_end").val() + "</option>");
					document.getElementById("date_range").options[focus_number].selected=true;

					// hide custom date picker again
					$("#custom_date_picker").slideUp("fast");
				}
			}
		');
        ee()->javascript->change("#date_range", "\n\t\t\tif (\$('#date_range').val() == 'custom_date')\n\t\t\t{\n\t\t\t\t// clear any current dates, remove any custom options\n\t\t\t\t\$('#custom_date_start').val('yyyy-mm-dd');\n\t\t\t\t\$('#custom_date_end').val('yyyy-mm-dd');\n\t\t\t\t\$('#custom_date_option').remove();\n\n\t\t\t\t// drop it down\n\t\t\t\t\$('#custom_date_picker').slideDown('fast');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\$('#custom_date_picker').hide();\n\t\t\t}\n\t\t");
        ee()->javascript->output('
		$(".paginationLinks a.page").click(function() {
			current_rownum = $("#perpage").val()*$(this).text()-$("#perpage").val();
			current_perpage = $("#perpage").val();

			$.getJSON("' . BASE . '&C=javascript&M=json&perpage="+$("#perpage").val()+"&rownum="+($("#perpage").val()*$(this).text()-$("#perpage").val())' . ', {ajax: "true"}, doPagination);
			return false;
		});

		var current_rownum = 0;
		var current_perpage = 20;
		var total_entries = 60; // needs to be set via PHP
		var next_page = current_perpage;

		function doPagination(e){
			var entries = "";
			for (var i = 0; i < e.length; i++) {
				entries += "<tr>";
				entries += "<td>" + e[i].id + "</td>";
				entries += "<td><a href=\\"#\\">" + e[i].title + "</a></td>";
				entries += "<td><a href=\\"#\\">Live Look</a></td>";
				entries += "<td>(" + e[i].comment_count + ")&nbsp;&nbsp;&nbsp;<a href=\\"#\\">View</a></td>";
				entries += "<td><div class=\'smallLinks\'><a href=\\"mailto:" + e[i].author_email + "\\">" + e[i].author + "</a></div></td>";
				entries += "<td>" + e[i].entry_date + "</td>";
				entries += "<td>" + e[i].channel_name + "</td>";

				if (e[i].status == "Open")
				{
					entries += "<td><span style=\\"color:#339900;\\">" + e[i].status + "</span></td>";
				}
				else
				{
					entries += "<td><span style=\\"color:#cc0000;\\">" + e[i].status + "</span></td>";
				}

				entries += "<td><input class=\'checkbox\' type=\'checkbox\' name=\'toggle[]\' value=\'" + e[i].id + "\' /></td>";
				entries += "</tr>";
			}

			$(".mainTable tbody").html(entries);
			$(".mainTable").trigger("update");
			var current_sort = $(".mainTable").get(0).config.sortList;
			$(".mainTable").trigger("sorton", [current_sort]);

			// add or remove first and last links
			(current_rownum >= current_perpage) ? $(".paginationLinks .first").show() : $(".paginationLinks .first").hide() ;
			(current_rownum >= current_perpage) ? $(".paginationLinks .previous").show() : $(".paginationLinks .previous").hide() ;
			(current_rownum >= (total_entries - current_perpage)) ? $(".paginationLinks .last").hide() : $(".paginationLinks .last").show() ;
			(current_rownum >= (total_entries - current_perpage)) ? $(".paginationLinks .next").hide() : $(".paginationLinks .next").show() ;
			// readjust page numbers for links
		}

		$(".paginationLinks .first").click(function() {
			current_perpage = $("#perpage").val();
			current_rownum = 0;
			$.getJSON("' . BASE . '&C=javascript&M=json&per_page="+current_perpage+"&rownum="+current_rownum, {ajax: "true"}, doPagination);
			return false;
		});

		$(".paginationLinks .previous").click(function() {
			current_perpage = $("#perpage").val();
			current_rownum = Number(current_rownum) - Number($("#perpage").val());
			$.getJSON("' . BASE . '&C=javascript&M=json&per_page="+current_perpage+"&rownum="+current_rownum, {ajax: "true"}, doPagination);
			return false;
		});

		$(".paginationLinks .next").click(function() {
			current_perpage = $("#perpage").val();
			current_rownum = Number(current_rownum) + Number($("#perpage").val());
			$.getJSON("' . BASE . '&C=javascript&M=json&per_page="+current_perpage+"&rownum="+current_rownum, {ajax: "true"}, doPagination);
			return false;
		});

		$(".paginationLinks .last").click(function() {
			current_perpage = $("#perpage").val();
			current_rownum = total_entries;
			$.getJSON("' . BASE . '&C=edit&M=json_entries&per_page="+current_perpage+"&rownum="+current_rownum, {ajax: "true"}, doPagination);
			return false;
		});

	');
        $cp_theme = !ee()->session->userdata('cp_theme') ? ee()->config->item('cp_theme') : ee()->session->userdata('cp_theme');
        $turn_on_robot = FALSE;
        // Fetch channel ID numbers assigned to the current user
        $allowed_channels = ee()->functions->fetch_assigned_channels();
        if (empty($allowed_channels)) {
            show_error(lang('no_channels'));
        }
        //  Fetch Color Library - We use this to assist with our status colors
        if (file_exists(APPPATH . 'config/colors.php')) {
            include APPPATH . 'config/colors.php';
        } else {
            $colors = '';
        }
        // We need to determine which channel to show entries from
        // if the channel_id combined
        if ($channel_id == '') {
            $channel_id = ee()->input->get_post('channel_id');
        }
        if ($channel_id == 'null' or $channel_id === FALSE or !is_numeric($channel_id)) {
            $channel_id = '';
        }
        $cat_group = '';
        $cat_id = ee()->input->get_post('cat_id');
        $status = ee()->input->get_post('status');
        $order = ee()->input->get_post('order');
        $date_range = ee()->input->get_post('date_range');
        $total_channels = count($allowed_channels);
        // If we have more than one channel we'll write the JavaScript menu switching code
        if ($total_channels > 1) {
            ee()->javascript->output($this->filtering_menus());
        }
        // Do we have a message to show?
        // Note: a message is displayed on this page after editing or submitting a new entry
        if (ee()->input->get_post("U") == 'mu') {
            $vars['message'] = lang('multi_entries_updated');
        }
        // Declare the "filtering" form
        $vars['search_form'] = $search_url != '' ? $search_url : 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=simple_commerce' . AMP . 'method=add_items';
        // If we have more than one channel we'll add the "onchange" method to
        // the form so that it'll automatically switch categories and statuses
        if ($total_channels > 1) {
            $vars['channel_select']['onchange'] = 'changemenu(this.selectedIndex);';
        }
        // Design note:	 Because the JavaScript code dynamically switches the information inside the
        // pull-down menus we can't show any particular menu in a "selected" state unless there is only
        // one channel.	 Each channel is fully independent, so it can have its own categories, statuses, etc.
        // Channel selection pull-down menu
        // Fetch the names of all channels and write each one in an <option> field
        $fields = array('channel_title', 'channel_id', 'cat_group');
        $where = array();
        // If the user is restricted to specific channels, add that to the query
        if (ee()->session->userdata['group_id'] != 1) {
            $where[] = array('channel_id' => $allowed_channels);
        }
        $query = ee()->channel_model->get_channels(ee()->config->item('site_id'), $fields, $where);
        if ($query->num_rows() == 1) {
            $channel_id = $query->row('channel_id');
            $cat_group = $query->row('cat_group');
        } elseif ($channel_id != '') {
            foreach ($query->result_array() as $row) {
                if ($row['channel_id'] == $channel_id) {
                    $channel_id = $row['channel_id'];
                    $cat_group = $row['cat_group'];
                }
            }
        }
        $vars['channel_selected'] = ee()->input->get_post('channel_id');
        $vars['channel_select_options'] = array('null' => lang('filter_by_channel'));
        if ($query->num_rows() > 1) {
            $vars['channel_select_options']['all'] = lang('all');
        }
        foreach ($query->result_array() as $row) {
            $vars['channel_select_options'][$row['channel_id']] = $row['channel_title'];
        }
        // Category pull-down menu
        $vars['category_selected'] = $cat_id;
        $vars['category_select_options'][''] = lang('filter_by_category');
        if ($total_channels > 1) {
            $vars['category_select_options']['all'] = lang('all');
        }
        $vars['category_select_options']['none'] = lang('none');
        if ($cat_group != '') {
            foreach (ee()->api_channel_categories->cat_array as $key => $val) {
                if (!in_array($val['0'], explode('|', $cat_group))) {
                    unset(ee()->api_channel_categories->cat_array[$key]);
                }
            }
            $i = 1;
            $new_array = array();
            foreach (ee()->api_channel_categories->cat_array as $ckey => $cat) {
                if ($ckey - 1 < 0 or !isset(ee()->api_channel_categories->cat_array[$ckey - 1])) {
                    $vars['category_select_options']['NULL_' . $i] = '-------';
                }
                $vars['category_select_options'][$cat['1']] = str_replace("!-!", "&nbsp;", $cat['2']);
                if (isset(ee()->api_channel_categories->cat_array[$ckey + 1]) && ee()->api_channel_categories->cat_array[$ckey + 1]['0'] != $cat['0']) {
                    $vars['category_select_options']['NULL_' . $i] = '-------';
                }
                $i++;
            }
        }
        // Authors list
        $vars['author_selected'] = ee()->input->get_post('author_id');
        $query = ee()->member_model->get_authors();
        $vars['author_select_options'][''] = lang('filter_by_author');
        foreach ($query->result_array() as $row) {
            $vars['author_select_options'][$row['member_id']] = $row['screen_name'] == '' ? $row['username'] : $row['screen_name'];
        }
        // Status pull-down menu
        $vars['status_selected'] = $status;
        $vars['status_select_options'][''] = lang('filter_by_status');
        $vars['status_select_options']['all'] = lang('all');
        $sel_1 = '';
        $sel_2 = '';
        if ($cat_group != '') {
            $sel_1 = $status == 'open' ? 1 : '';
            $sel_2 = $status == 'closed' ? 1 : '';
        }
        if ($cat_group != '') {
            $rez = ee()->db->query("SELECT status_group FROM exp_channels WHERE channel_id = '{$channel_id}'");
            $query = ee()->db->query("SELECT status FROM exp_statuses WHERE group_id = '" . ee()->db->escape_str($rez->row('status_group')) . "' ORDER BY status_order");
            if ($query->num_rows() > 0) {
                foreach ($query->result_array() as $row) {
                    $status_name = ($row['status'] == 'closed' or $row['status'] == 'open') ? lang($row['status']) : $row['status'];
                    $vars['status_select_options'][$row['status']] = $status_name;
                }
            }
        } else {
            $vars['status_select_options']['open'] = lang('open');
            $vars['status_select_options']['closed'] = lang('closed');
        }
        // Date range pull-down menu
        $vars['date_selected'] = $date_range;
        $vars['date_select_options'][''] = lang('date_range');
        $vars['date_select_options']['1'] = lang('today');
        $vars['date_select_options']['7'] = lang('past_week');
        $vars['date_select_options']['31'] = lang('past_month');
        $vars['date_select_options']['182'] = lang('past_six_months');
        $vars['date_select_options']['365'] = lang('past_year');
        $vars['date_select_options']['custom_date'] = lang('any_date');
        // Display order pull-down menu
        $vars['order_selected'] = $order;
        $vars['order_select_options'][''] = lang('order');
        $vars['order_select_options']['asc'] = lang('ascending');
        $vars['order_select_options']['desc'] = lang('descending');
        $vars['order_select_options']['alpha'] = lang('alpha');
        // Results per page pull-down menu
        if (!($perpage = ee()->input->get_post('perpage'))) {
            $perpage = ee()->input->cookie('perpage');
        }
        if ($perpage == '') {
            $perpage = 50;
        }
        ee()->functions->set_cookie('perpage', $perpage, 60 * 60 * 24 * 182);
        $vars['perpage_selected'] = $perpage;
        $vars['perpage_select_options']['10'] = '10 ' . lang('results');
        $vars['perpage_select_options']['25'] = '25 ' . lang('results');
        $vars['perpage_select_options']['50'] = '50 ' . lang('results');
        $vars['perpage_select_options']['75'] = '75 ' . lang('results');
        $vars['perpage_select_options']['100'] = '100 ' . lang('results');
        $vars['perpage_select_options']['150'] = '150 ' . lang('results');
        if (isset($_POST['keywords'])) {
            $keywords = sanitize_search_terms($_POST['keywords']);
        } elseif (isset($_GET['keywords'])) {
            $keywords = sanitize_search_terms(base64_decode($_GET['keywords']));
        } else {
            $keywords = '';
        }
        if (substr(strtolower($keywords), 0, 3) == 'ip:') {
            $keywords = str_replace('_', '.', $keywords);
        }
        // Because of the auto convert we prepare a specific variable with the converted ascii
        // characters while leaving the $keywords variable intact for display and URL purposes
        $search_keywords = ee()->config->item('auto_convert_high_ascii') == 'y' ? ascii_to_entities($keywords) : $keywords;
        $vars['exact_match'] = ee()->input->get_post('exact_match');
        $vars['keywords'] = array('name' => 'keywords', 'value' => stripslashes($keywords), 'id' => 'keywords', 'maxlength' => 200);
        $search_in = ee()->input->get_post('search_in') != '' ? ee()->input->get_post('search_in') : 'title';
        $vars['search_in_selected'] = $search_in;
        $vars['search_in_options']['title'] = lang('title_only');
        $vars['search_in_options']['body'] = lang('title_and_body');
        if (isset(ee()->installed_modules['comment'])) {
            $vars['search_in_options']['everywhere'] = lang('title_body_comments');
            $vars['search_in_options']['comments'] = $this->lang->line('comments');
        }
        //	 Build the main query
        if ($search_url != '') {
            $pageurl = BASE . AMP . $search_url;
        } else {
            $pageurl = BASE . AMP . 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=simple_commerce' . AMP . 'method=add_items';
        }
        $sql_a = "SELECT ";
        if ($search_in == 'comments') {
            $sql_b = "DISTINCT(exp_comments.comment_id) ";
        } else {
            $sql_b = ($cat_id == 'none' or $cat_id != "") ? "DISTINCT(exp_channel_titles.entry_id) " : "exp_channel_titles.entry_id ";
        }
        $sql = "FROM exp_channel_titles\n\t\t\t\tLEFT JOIN exp_channels ON exp_channel_titles.channel_id = exp_channels.channel_id ";
        if ($keywords != '') {
            if ($search_in != 'title') {
                $sql .= "LEFT JOIN exp_channel_data ON exp_channel_titles.entry_id = exp_channel_data.entry_id ";
            }
            if ($search_in == 'everywhere' or $search_in == 'comments') {
                $sql .= "LEFT JOIN exp_comments ON exp_channel_titles.entry_id = exp_comments.entry_id ";
            }
        } elseif ($search_in == 'comments') {
            $sql .= "LEFT JOIN exp_comments ON exp_channel_titles.entry_id = exp_comments.entry_id ";
        }
        $sql .= "LEFT JOIN exp_members ON exp_members.member_id = exp_channel_titles.author_id ";
        if ($cat_id == 'none' or $cat_id != "") {
            $sql .= "LEFT JOIN exp_category_posts ON exp_channel_titles.entry_id = exp_category_posts.entry_id\n\t\t\t\t\t LEFT JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id ";
        }
        if (is_array($extra_sql) && isset($extra_sql['tables'])) {
            $sql .= ' ' . $extra_sql['tables'] . ' ';
        }
        // Limit to channels assigned to user
        $sql .= " WHERE exp_channels.site_id = '" . ee()->db->escape_str(ee()->config->item('site_id')) . "' AND exp_channel_titles.channel_id IN (";
        foreach ($allowed_channels as $val) {
            $sql .= "'" . $val . "',";
        }
        $sql = substr($sql, 0, -1) . ')';
        if (!ee()->cp->allowed_group('can_edit_other_entries') and !ee()->cp->allowed_group('can_view_other_entries')) {
            $sql .= " AND exp_channel_titles.author_id = " . ee()->session->userdata('member_id');
        }
        if (is_array($extra_sql) && isset($extra_sql['where'])) {
            $sql .= ' ' . $extra_sql['where'] . ' ';
        }
        if ($keywords != '') {
            $pageurl .= AMP . 'keywords=' . base64_encode($keywords);
            if ($search_in == 'comments') {
                // When searching in comments we do not want to search the entry title.
                // However, by removing this we would have to make the rest of the query creation code
                // below really messy so we simply check for an empty title, which should never happen.
                // That makes this check pointless and allows us some cleaner code. -Paul
                $sql .= " AND (exp_channel_titles.title = '' ";
            } else {
                if ($vars['exact_match'] != 'yes') {
                    $sql .= " AND (exp_channel_titles.title LIKE '%" . ee()->db->escape_like_str($search_keywords) . "%' ";
                } else {
                    $pageurl .= AMP . 'exact_match=yes';
                    $sql .= " AND (exp_channel_titles.title = '" . ee()->db->escape_str($search_keywords) . "' OR exp_channel_titles.title LIKE '" . ee()->db->escape_like_str($search_keywords) . " %' OR exp_channel_titles.title LIKE '% " . ee()->db->escape_like_str($search_keywords) . " %' ";
                }
            }
            $pageurl .= AMP . 'search_in=' . $search_in;
            if ($search_in == 'body' or $search_in == 'everywhere') {
                // ---------------------------------------
                //	 Fetch the searchable field names
                // ---------------------------------------
                $fields = array();
                $xql = "SELECT DISTINCT(field_group) FROM exp_channels";
                if ($channel_id != '') {
                    $xql .= " WHERE channel_id = '" . ee()->db->escape_str($channel_id) . "' ";
                }
                $query = ee()->db->query($xql);
                if ($query->num_rows() > 0) {
                    $fql = "SELECT field_id FROM exp_channel_fields WHERE group_id IN (";
                    foreach ($query->result_array() as $row) {
                        $fql .= "'" . $row['field_group'] . "',";
                    }
                    $fql = substr($fql, 0, -1) . ')';
                    $query = ee()->db->query($fql);
                    if ($query->num_rows() > 0) {
                        foreach ($query->result_array() as $row) {
                            $fields[] = $row['field_id'];
                        }
                    }
                }
                foreach ($fields as $val) {
                    if ($exact_match != 'yes') {
                        $sql .= " OR exp_channel_data.field_id_" . $val . " LIKE '%" . ee()->db->escape_like_str($search_keywords) . "%' ";
                    } else {
                        $sql .= "  OR (exp_channel_data.field_id_" . $val . " LIKE '" . ee()->db->escape_like_str($search_keywords) . " %' OR exp_channel_data.field_id_" . $val . " LIKE '% " . ee()->db->escape_like_str($search_keywords) . " %' OR exp_channel_data.field_id_" . $val . " = '" . ee()->db->escape_str($search_keywords) . "') ";
                    }
                }
            }
            if ($search_in == 'everywhere' or $search_in == 'comments') {
                if ($search_in == 'comments' && (substr(strtolower($search_keywords), 0, 3) == 'ip:' or substr(strtolower($search_keywords), 0, 4) == 'mid:')) {
                    if (substr(strtolower($search_keywords), 0, 3) == 'ip:') {
                        $sql .= " OR (exp_comments.ip_address = '" . ee()->db->escape_str(str_replace('_', '.', substr($search_keywords, 3))) . "') ";
                    } elseif (substr(strtolower($search_keywords), 0, 4) == 'mid:') {
                        $sql .= " OR (exp_comments.author_id = '" . ee()->db->escape_str(substr($search_keywords, 4)) . "') ";
                    }
                } else {
                    $sql .= " OR (exp_comments.comment LIKE '%" . ee()->db->escape_like_str($keywords) . "%') ";
                    // No ASCII conversion here!
                }
            }
            $sql .= ")";
        }
        if ($channel_id) {
            $pageurl .= AMP . 'channel_id=' . $channel_id;
            $sql .= " AND exp_channel_titles.channel_id = {$channel_id}";
        }
        if ($date_range) {
            $pageurl .= AMP . 'date_range=' . $date_range;
            $date_range = time() - $date_range * 60 * 60 * 24;
            $sql .= " AND exp_channel_titles.entry_date > {$date_range}";
        }
        if (is_numeric($cat_id)) {
            $pageurl .= AMP . 'cat_id=' . $cat_id;
            $sql .= " AND exp_category_posts.cat_id = '{$cat_id}'\n\t\t\t\t\t  AND exp_category_posts.entry_id = exp_channel_titles.entry_id ";
        }
        if ($cat_id == 'none') {
            $pageurl .= AMP . 'cat_id=' . $cat_id;
            $sql .= " AND exp_category_posts.entry_id IS NULL ";
        }
        if ($status && $status != 'all') {
            $pageurl .= AMP . 'status=' . $status;
            $sql .= " AND exp_channel_titles.status = '{$status}'";
        }
        $end = " ORDER BY ";
        if ($order) {
            $pageurl .= AMP . 'order=' . $order;
            switch ($order) {
                case 'asc':
                    $end .= "entry_date asc";
                    break;
                case 'desc':
                    $end .= "entry_date desc";
                    break;
                case 'alpha':
                    $end .= "title asc";
                    break;
                default:
                    $end .= "entry_date desc";
            }
        } else {
            $end .= "entry_date desc";
        }
        // ------------------------------
        //	 Are there results?
        // ------------------------------
        $query = ee()->db->query($sql_a . $sql_b . $sql);
        // No result?  Show the "no results" message
        $vars['total_count'] = $query->num_rows();
        if ($vars['total_count'] == 0) {
            ee()->javascript->compile();
            $vars['heading'] = 'edit_channel_entries';
            $vars['search_form_hidden'] = array();
            ee()->load->view('edit_rip', $vars, TRUE);
            return;
        }
        // Get the current row number and add the LIMIT clause to the SQL query
        if (!($rownum = ee()->input->get_post('rownum'))) {
            $rownum = 0;
        }
        // --------------------------------------------
        //	 Run the query again, fetching ID numbers
        // --------------------------------------------
        if ($search_in == 'comments') {
            $rownum = ee()->input->get('current_page') ? ee()->input->get('current_page') : 0;
        } else {
            $pageurl .= AMP . 'perpage=' . $perpage;
            $vars['form_hidden']['pageurl'] = base64_encode($pageurl);
            // for pagination
        }
        $query = ee()->db->query($sql_a . $sql_b . $sql . $end . " LIMIT " . $rownum . ", " . $perpage);
        // Filter comments
        if ($search_in == 'comments') {
            $comment_array = array();
            foreach ($query->result_array() as $row) {
                $comment_array[] = $row['comment_id'];
            }
            if ($keywords == '') {
                $pageurl .= AMP . 'keywords=' . base64_encode($keywords) . AMP . 'search_in=' . $search_in;
            }
            return ee()->view_comments('', '', '', FALSE, array_unique($comment_array), $vars['total_count'], $pageurl);
        }
        // --------------------------------------------
        //	 Fetch the channel information we need later
        // --------------------------------------------
        $sql = "SELECT channel_id, channel_name FROM exp_channels ";
        $sql .= "WHERE site_id = '" . ee()->db->escape_str(ee()->config->item('site_id')) . "' ";
        $w_array = array();
        $result = ee()->db->query($sql);
        if ($result->num_rows() > 0) {
            foreach ($result->result_array() as $rez) {
                $w_array[$rez['channel_id']] = $rez['channel_name'];
            }
        }
        // --------------------------------------------
        //	 Fetch the status highlight colors
        // --------------------------------------------
        $cql = "SELECT exp_channels.channel_id, exp_channels.channel_name, exp_statuses.status, exp_statuses.highlight\n\t\t\t\t FROM  exp_channels, exp_statuses, exp_status_groups\n\t\t\t\t WHERE exp_status_groups.group_id = exp_channels.status_group\n\t\t\t\t AND   exp_status_groups.group_id = exp_statuses.group_id\n\t\t\t\t AND\texp_statuses.highlight != ''\n\t\t\t\t AND\texp_status_groups.site_id = '" . ee()->db->escape_str(ee()->config->item('site_id')) . "' ";
        // Limit to channels assigned to user
        $sql .= " AND exp_channels.channel_id IN (";
        foreach ($allowed_channels as $val) {
            $sql .= "'" . $val . "',";
        }
        $sql = substr($sql, 0, -1) . ')';
        $result = ee()->db->query($cql);
        $c_array = array();
        if ($result->num_rows() > 0) {
            foreach ($result->result_array() as $rez) {
                $c_array[$rez['channel_id'] . '_' . $rez['status']] = str_replace('#', '', $rez['highlight']);
            }
        }
        // information for entries table
        $vars['entries_form'] = $form_url != '' ? $form_url : 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=simple_commerce' . AMP . 'method=add_item';
        $vars['form_hidden'] = $extra_fields_entries;
        $vars['search_form_hidden'] = $extra_fields_search ? $extra_fields_search : array();
        // table headings
        $table_headings = array('#', lang('title'), lang('view'));
        // comments module installed?  If so, add it to the list of headings.
        if (isset(ee()->installed_modules['comment'])) {
            $table_headings[] .= lang('comments');
        }
        $table_headings = array_merge($table_headings, array(lang('author'), lang('date'), lang('channel'), lang('status'), form_checkbox('select_all', 'true', FALSE, 'class="toggle_all"')));
        $vars['table_headings'] = $table_headings;
        // Build and run the full SQL query
        $sql = "SELECT ";
        $sql .= ($cat_id == 'none' or $cat_id != "") ? "DISTINCT(exp_channel_titles.entry_id), " : "exp_channel_titles.entry_id, ";
        $sql .= "exp_channel_titles.channel_id,\n\t\t\t\texp_channel_titles.title,\n\t\t\t\texp_channel_titles.author_id,\n\t\t\t\texp_channel_titles.status,\n\t\t\t\texp_channel_titles.entry_date,\n\t\t\t\texp_channel_titles.comment_total,\n\t\t\t\texp_channels.live_look_template,\n\t\t\t\texp_members.username,\n\t\t\t\texp_members.email,\n\t\t\t\texp_members.screen_name";
        $sql .= " FROM exp_channel_titles\n\t\t\t\t  LEFT JOIN exp_channels ON exp_channel_titles.channel_id = exp_channels.channel_id\n\t\t\t\t  LEFT JOIN exp_members ON exp_members.member_id = exp_channel_titles.author_id ";
        if ($cat_id != 'none' and $cat_id != "") {
            $sql .= "INNER JOIN exp_category_posts ON exp_channel_titles.entry_id = exp_category_posts.entry_id\n\t\t\t\t\t INNER JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id ";
        }
        $sql .= "WHERE exp_channel_titles.entry_id IN (";
        foreach ($query->result_array() as $row) {
            $sql .= $row['entry_id'] . ',';
        }
        $sql = substr($sql, 0, -1) . ') ' . $end;
        $query = ee()->db->query($sql);
        // load the site's templates
        $templates = array();
        $tquery = ee()->db->query("SELECT exp_template_groups.group_name, exp_templates.template_name, exp_templates.template_id\n\t\t\t\t\t\t\tFROM exp_template_groups, exp_templates\n\t\t\t\t\t\t\tWHERE exp_template_groups.group_id = exp_templates.group_id\n\t\t\t\t\t\t\tAND exp_templates.site_id = '" . ee()->db->escape_str(ee()->config->item('site_id')) . "'");
        if ($tquery->num_rows() > 0) {
            foreach ($tquery->result_array() as $row) {
                $templates[$row['template_id']] = $row['group_name'] . '/' . $row['template_name'];
            }
        }
        // Grab all autosaved entries
        // Removed for here
        $vars['autosave_show'] = FALSE;
        // Loop through the main query result and set up data structure for table
        $vars['entries'] = array();
        foreach ($query->result_array() as $row) {
            // Entry ID number
            $vars['entries'][$row['entry_id']][] = $row['entry_id'];
            // Channel entry title (view entry)
            $output = '<a href="' . BASE . AMP . 'C=content_publish' . AMP . 'M=entry_form' . AMP . 'channel_id=' . $row['channel_id'] . AMP . 'entry_id=' . $row['entry_id'] . '">' . $row['title'] . '</a>';
            $vars['entries'][$row['entry_id']][] = $output;
            // "View"
            if ($row['live_look_template'] != 0 && isset($templates[$row['live_look_template']])) {
                $qm = ee()->config->item('force_query_string') == 'y' ? '' : '?';
                $view_link = anchor(ee()->functions->fetch_site_index() . $qm . 'URL=' . ee()->functions->create_url($templates[$row['live_look_template']] . '/' . $row['entry_id']), lang('view'), '', TRUE);
            } else {
                $view_link = '--';
            }
            $vars['entries'][$row['entry_id']][] = $view_link;
            // Comment count
            $show_link = TRUE;
            if ($row['author_id'] == ee()->session->userdata('member_id')) {
                if (!ee()->cp->allowed_group('can_edit_own_comments') and !ee()->cp->allowed_group('can_delete_own_comments') and !ee()->cp->allowed_group('can_moderate_comments')) {
                    $show_link = FALSE;
                }
            } else {
                if (!ee()->cp->allowed_group('can_edit_all_comments') and !ee()->cp->allowed_group('can_delete_all_comments') and !ee()->cp->allowed_group('can_moderate_comments')) {
                    $show_link = FALSE;
                }
            }
            if (isset(ee()->installed_modules['comment'])) {
                //	Comment Link
                if ($show_link !== FALSE) {
                    $res = ee()->db->query("SELECT COUNT(*) AS count FROM exp_comments WHERE entry_id = '" . $row['entry_id'] . "'");
                    ee()->db->query_count--;
                    $view_url = BASE . AMP . 'C=content_edit' . AMP . 'M=view_comments' . AMP . 'channel_id=' . $row['channel_id'] . AMP . 'entry_id=' . $row['entry_id'];
                }
                $view_link = $show_link == FALSE ? '<div class="lightLinks">--</div>' : '<div class="lightLinks">(' . $res->row('count') . ')' . NBS . anchor($view_url, lang('view')) . '</div>';
                $vars['entries'][$row['entry_id']][] = $view_link;
            }
            // Username
            $name = $row['screen_name'] != '' ? $row['screen_name'] : $row['username'];
            $vars['entries'][$row['entry_id']][] = mailto($row['email'], $name);
            // Date
            $date_fmt = ee()->session->userdata('time_format') != '' ? ee()->session->userdata('time_format') : ee()->config->item('time_format');
            if ($date_fmt == 'us') {
                $datestr = '%m/%d/%y %h:%i %a';
            } else {
                $datestr = '%Y-%m-%d %H:%i';
            }
            $vars['entries'][$row['entry_id']][] = ee()->localize->format_date($datestr, $row['entry_date']);
            // Channel
            $vars['entries'][$row['entry_id']][] = isset($w_array[$row['channel_id']]) ? '<div class="smallNoWrap">' . $w_array[$row['channel_id']] . '</div>' : '';
            // Status
            $status_name = ($row['status'] == 'open' or $row['status'] == 'closed') ? lang($row['status']) : $row['status'];
            $color_info = '';
            if (isset($c_array[$row['channel_id'] . '_' . $row['status']]) and $c_array[$row['channel_id'] . '_' . $row['status']] != '') {
                $color = $c_array[$row['channel_id'] . '_' . $row['status']];
                $prefix = (is_array($colors) and !array_key_exists(strtolower($color), $colors)) ? '#' : '';
                // There are custom colours, override the class above
                $color_info = 'style="color:' . $prefix . $color . ';"';
            }
            $vars['entries'][$row['entry_id']][] = '<span class="status_' . $row['status'] . '"' . $color_info . '>' . $status_name . '</span>';
            // Delete checkbox
            $vars['entries'][$row['entry_id']][] = form_checkbox('toggle[]', $row['entry_id'], '', ' class="toggle" id="delete_box_' . $row['entry_id'] . '"');
        }
        // End foreach
        // Pass the relevant data to the paginate class
        $config['base_url'] = $pageurl;
        $config['total_rows'] = $vars['total_count'];
        $config['per_page'] = $perpage;
        $config['page_query_string'] = TRUE;
        $config['query_string_segment'] = 'rownum';
        $config['full_tag_open'] = '<p id="paginationLinks">';
        $config['full_tag_close'] = '</p>';
        $config['prev_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_prev_button.gif" width="13" height="13" alt="&lt;" />';
        $config['next_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_next_button.gif" width="13" height="13" alt="&gt;" />';
        $config['first_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_first_button.gif" width="13" height="13" alt="&lt; &lt;" />';
        $config['last_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_last_button.gif" width="13" height="13" alt="&gt; &gt;" />';
        ee()->pagination->initialize($config);
        $vars['pagination'] = ee()->pagination->create_links();
        $vars['heading'] = $heading ? $heading : 'edit_channel_entries';
        $vars['action_options'] = '';
        if ($action == '') {
            $vars['action_options'] = array('add' => lang('add_items'));
        } elseif (is_array($action)) {
            $vars['action_options'] = $action;
        }
        ee()->javascript->compile();
        return ee()->load->view('edit_rip', $vars, TRUE);
    }
Ejemplo n.º 4
0
 /**
  * search_products function.
  * 
  * @access public
  * @param string $term
  * @param string $type
  * @return JSON product array
  */
 public function search_products($term, $type = '')
 {
     $this->EE->load->helper('search');
     $products = array();
     $term = "%" . sanitize_search_terms($term) . "%";
     if (strlen($term) < 2) {
         return $products;
     }
     $site_id = $this->config->item('site_id');
     $sql = " SELECT \n    \t\t             * \n    \t\t         FROM \n    \t\t             " . $this->EE->db->dbprefix . "br_product \n    \t\t         WHERE \n    \t\t             enabled >= 0 \n    \t\t         AND \n    \t\t             site_id = " . $site_id . " \n    \t\t         AND \n    \t\t             (\n    \t\t                 title LIKE '" . $term . "'\n    \t\t                     OR \n    \t\t                 detail LIKE '" . $term . "'\n    \t\t                     OR \n    \t\t                 sku LIKE '" . $term . "'\n    \t\t             ) ";
     // restrict the product types allowed
     // in a bundle search
     if ($type == 'bundle') {
         $types = array(1, 4, 5, 7);
         $sql .= " AND type_id IN (" . join(",", $types) . ")";
     }
     $sql .= " order by title desc";
     $query = $this->EE->db->query($sql);
     foreach ($query->result_array() as $row) {
         $products[] = $row;
     }
     return $products;
 }
Ejemplo n.º 5
0
 /**
  * Sanitize Search Terms
  *
  * Filters a search string for security
  *
  * @access	public
  * @param	string
  * @return	string
  */
 public function sanitize_search_terms($str)
 {
     if (APP_VER < 2.0) {
         return $GLOBALS['REGX']->keyword_clean($str);
     } else {
         ee()->load->helper('search');
         return sanitize_search_terms($str);
     }
 }
Ejemplo n.º 6
0
 function filter_settings($ajax = FALSE)
 {
     // Load the search helper so we can filter the keywords
     $this->EE->load->helper('search');
     $keywords = '';
     if ($this->EE->input->post('keywords')) {
         $keywords = $this->EE->input->get_post('keywords');
     } elseif ($this->EE->input->get('keywords')) {
         $keywords = base64_decode($this->EE->input->get('keywords'));
     }
     $channel_id = $this->EE->input->get_post('channel_id') && $this->EE->input->get_post('channel_id') != 'null' ? $this->EE->input->get_post('channel_id') : '';
     $filter_on['status'] = $this->EE->input->get_post('status');
     $filter_on['order'] = $this->EE->input->get_post('order');
     $filter_on['date_range'] = $this->EE->input->get_post('date_range');
     $filter_on['name'] = $this->EE->input->get('name') ? sanitize_search_terms(base64_decode($this->EE->input->get('name'))) : $this->EE->input->post('name');
     $filter_on['keywords'] = $keywords;
     $filter_on['search_in'] = $this->EE->input->get_post('search_in');
     $filter_on['channel_id'] = $this->EE->input->get_post('channel_id');
     $filter_on['date_range'] = $this->EE->input->get_post('date_range');
     $filter_on['ip_address'] = $this->EE->input->get('ip_address') ? sanitize_search_terms(base64_decode($this->EE->input->post('ip_address'))) : $this->EE->input->post('ip_address');
     $filter_on['email'] = $this->EE->input->get('email') ? base64_decode($this->EE->input->post('email')) : $this->EE->input->post('email');
     $filter_on['entry_id'] = $this->EE->input->get_post('entry_id');
     $filter_on['comment_id'] = $this->EE->input->get_post('comment_id');
     $filter_on['limit'] = $this->perpage;
     //  Because you can specify some extra gets- let's translate that back to search_in/keywords
     if ($this->EE->input->get('entry_id')) {
         $filter_on['search_in'] = 'entry_title';
         $this->EE->db->select('title');
         $this->EE->db->where('entry_id', $this->EE->input->get('entry_id'));
         $query = $this->EE->db->get('channel_titles');
         $row = $query->row();
         $filter_on['keywords'] = $row->title;
     } elseif ($this->EE->input->get('name')) {
         $filter_on['search_in'] = 'name';
         $filter_on['keywords'] = base64_decode($this->EE->input->get('name'));
     } elseif ($this->EE->input->get('email')) {
         $filter_on['search_in'] = 'email';
         $filter_on['keywords'] = base64_decode($this->EE->input->get('email'));
     } elseif ($this->EE->input->get('ip_address')) {
         $filter_on['search_in'] = 'ip_address';
         $filter_on['keywords'] = base64_decode($this->EE->input->get('ip_address'));
     }
     //  Create the get variables for non-js pagination
     // Post variables: search_in, keywords*, channel_id, status, date_range
     // Get variables: entry_id, channel_id, name, email*, ip_address* and status
     $url = array('search_in' => $filter_on['search_in']);
     $filter_on['search_form_hidden'] = array();
     foreach ($filter_on as $name => $value) {
         if ($this->EE->input->post($name) && $this->EE->input->post($name) != '') {
             $v = $name == 'keywords' ? base64_encode($this->EE->input->post($name)) : $this->EE->input->post($name);
             $url[$name] = $name . '=' . $v;
         } elseif ($this->EE->input->get($name)) {
             $url[$name] = $name . '=' . $this->EE->input->get($name);
         }
     }
     if (!isset($url['keywords'])) {
         unset($url['search_in']);
     }
     $this->search_url = implode(AMP, $url);
     return $filter_on;
 }
    /**
     *  View Referrers
     */
    function view()
    {
        ee()->load->library('pagination');
        ee()->load->library('javascript');
        ee()->load->library('table');
        ee()->load->helper('form');
        ee()->cp->set_breadcrumb(BASE . AMP . 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=referrer', ee()->lang->line('referrers'));
        $vars['cp_page_title'] = ee()->lang->line('view_referrers');
        ee()->jquery->tablesorter('.mainTable', '{
			headers: {5: {sorter: false}},
			widgets: ["zebra"]
		}');
        ee()->javascript->output(array('$(".toggle_all").toggle(
					function(){
						$("input.toggle").each(function() {
							this.checked = true;
						});
					}, function (){
						var checked_status = this.checked;
						$("input.toggle").each(function() {
							this.checked = false;
						});
					}
				);'));
        ee()->cp->add_to_foot('<script type="text/javascript">function showHide(entryID, htmlObj, linkType) {

				extTextDivID = ("extText" + (entryID));
				extLinkDivID = ("extLink" + (entryID));

				if (linkType == "close")
				{
					document.getElementById(extTextDivID).style.display = "none";
					document.getElementById(extLinkDivID).style.display = "block";
					htmlObj.blur();
				}
				else
				{
					document.getElementById(extTextDivID).style.display = "block";
					document.getElementById(extLinkDivID).style.display = "none";
					htmlObj.blur();
				}

				}
				</script>');
        $vars['referrers'] = array();
        // used to pass referrer info into view, but initialized here in case there are no results.
        $rownum = ee()->input->get_post('rownum') != '' ? ee()->input->get_post('rownum') : 0;
        $perpage = 10;
        $search_str = '';
        $search_sql = '';
        $vars['search']['name'] = 'search';
        if (isset($_GET['search']) or isset($_POST['search'])) {
            $search_str = isset($_POST['search']) ? stripslashes($_POST['search']) : base64_decode($_GET['search']);
        }
        if ($search_str != '') {
            // Load the search helper so we can filter the keywords
            ee()->load->helper('search');
            $s = preg_split("/\\s+/", sanitize_search_terms($search_str));
            foreach ($s as $part) {
                if (substr($part, 0, 1) == '-') {
                    $search_sql .= "CONCAT_WS(' ', ref_from, ref_to, ref_ip, ref_agent) NOT LIKE '%" . ee()->db->escape_like_str(substr($part, 1)) . "%' AND ";
                } else {
                    $search_sql .= "CONCAT_WS(' ', ref_from, ref_to, ref_ip, ref_agent) LIKE '%" . ee()->db->escape_like_str($part) . "%' AND ";
                }
            }
            $sql = "WHERE (" . substr($search_sql, 0, -4) . ")";
            $vars['search']['value'] = sanitize_search_terms($search_str);
        } else {
            $sql = "";
        }
        $query = ee()->db->query("SELECT COUNT(*) AS count FROM exp_referrers " . $sql);
        $vars['num_referrers'] = $query->row('count');
        if ($query->row('count') == 0) {
            $vars['message'] = isset($vars['search']['value']) ? ee()->lang->line('referrer_no_results') : ee()->lang->line('no_referrers');
            return ee()->load->view('view', $vars, TRUE);
            exit;
        }
        $sites_query = ee()->db->query("SELECT site_id, site_label FROM exp_sites");
        $sites = array();
        foreach ($sites_query->result_array() as $row) {
            $sites[$row['site_id']] = $row['site_label'];
        }
        $query = ee()->db->query("SELECT * FROM exp_referrers " . $sql . " ORDER BY ref_id desc LIMIT {$rownum}, {$perpage}");
        $site_url = ee()->config->item('site_url');
        foreach ($query->result_array() as $row) {
            // From
            $row['ref_from'] = str_replace('http://', '', $row['ref_from']);
            if (strlen($row['ref_from']) > 40) {
                $from_pieces = explode('/', $row['ref_from']);
                $new_from = $from_pieces['0'] . '/';
                for ($p = 1; $p < count($from_pieces); $p++) {
                    if (strlen($from_pieces[$p]) + strlen($new_from) <= 40) {
                        $new_from .= $p == count($from_pieces) - 1 ? $from_pieces[$p] : $from_pieces[$p] . '/';
                    } else {
                        $new_from .= '&#8230;';
                        break;
                    }
                }
            } else {
                $new_from = $row['ref_from'];
            }
            $vars['referrers'][$row['ref_id']]['from_link'] = ee()->functions->fetch_site_index() . QUERY_MARKER . 'URL=' . urlencode($row['ref_from']);
            $vars['referrers'][$row['ref_id']]['from_url'] = $new_from;
            // To
            $vars['referrers'][$row['ref_id']]['to_link'] = ee()->functions->fetch_site_index() . QUERY_MARKER . 'URL=' . urlencode($row['ref_to']);
            $vars['referrers'][$row['ref_id']]['to_url'] = '/' . ltrim(str_replace($site_url, '', $row['ref_to']), '/');
            // Date
            $vars['referrers'][$row['ref_id']]['date'] = ($row['ref_date'] != '' and $row['ref_date'] != 0) ? ee()->localize->human_time($row['ref_date']) : '-';
            // IP
            $vars['referrers'][$row['ref_id']]['referrer_ip'] = ($row['ref_ip'] != '' and $row['ref_ip'] != 0) ? $row['ref_ip'] : '-';
            // Agent
            $agent = $row['ref_agent'] != '' ? $row['ref_agent'] : '-';
            if (strlen($agent) > 11) {
                $agent2 = '<span class="defaultBold">' . ee()->lang->line('ref_user_agent') . '</span>:' . NBS . "<a href=\"javascript:void(0);\" name=\"ext{$row['ref_id']}\" onclick=\"showHide({$row['ref_id']},this,'close');return false;\">[-]</a>" . NBS . NBS . $agent;
                $agent = "<div id='extLink{$row['ref_id']}'><span class='defaultBold'>" . ee()->lang->line('ref_user_agent') . '</span>:' . NBS . "<a href=\"javascript:void(0);\" name=\"ext{$row['ref_id']}\" onclick=\"showHide({$row['ref_id']},this,'open');return false;\">[+]</a>" . NBS . NBS . preg_replace("/(.+?)\\s+.*/", "\\1", $agent) . "</div>";
                $agent .= '<div id="extText' . $row['ref_id'] . '" style="display: none; padding:0;">' . $agent2 . '</div>';
            }
            $vars['referrers'][$row['ref_id']]['user_agent'] = $agent;
            // Site
            $vars['referrers'][$row['ref_id']]['site'] = $sites[$row['site_id']];
            // Toggle checkbox
            $vars['referrers'][$row['ref_id']]['toggle'] = array('name' => 'toggle[]', 'id' => 'delete_box_' . $row['ref_id'], 'value' => $row['ref_id'], 'class' => 'toggle');
        }
        // Pass the relevant data to the paginate class
        $config['base_url'] = BASE . AMP . 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=referrer' . AMP . 'method=view';
        $config['total_rows'] = $vars['num_referrers'];
        $config['per_page'] = $perpage;
        $config['page_query_string'] = TRUE;
        $config['query_string_segment'] = 'rownum';
        $config['full_tag_open'] = '<p id="paginationLinks">';
        $config['full_tag_close'] = '</p>';
        $config['prev_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_prev_button.gif" width="13" height="13" alt="&lt;" />';
        $config['next_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_next_button.gif" width="13" height="13" alt="&gt;" />';
        $config['first_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_first_button.gif" width="13" height="13" alt="&lt; &lt;" />';
        $config['last_link'] = '<img src="' . ee()->cp->cp_theme_url . 'images/pagination_last_button.gif" width="13" height="13" alt="&gt; &gt;" />';
        ee()->pagination->initialize($config);
        $vars['pagination'] = ee()->pagination->create_links();
        ee()->javascript->compile();
        return ee()->load->view('view', $vars, TRUE);
    }
Ejemplo n.º 8
0
 /**
  * Do Search
  */
 function do_search()
 {
     $this->EE->lang->loadfile('search');
     // Get hidden meta vars
     if (isset($_POST['meta'])) {
         $this->_get_meta_vars();
     }
     /** ----------------------------------------
     		/**  Profile Exception
     		/** ----------------------------------------*/
     // This is an exception to the normal search routine.
     // It permits us to search for all posts by a particular user's screen name
     // We look for the "mbr" $_GET variable.  If it exsists it will
     // trigger our exception
     if ($this->EE->input->get_post('mbr')) {
         $this->_meta['result_page'] = $this->EE->input->get_post('result_path') != '' ? $this->EE->input->get_post('result_path') : 'search/results';
         $_POST['keywords'] = '';
         $_POST['exact_match'] = 'y';
         $_POST['exact_keyword'] = 'n';
     }
     // RP can be used in a query string,
     // so we need to clean it a bit
     $this->_meta['result_page'] = str_replace(array('=', '&'), '', $this->_meta['result_page']);
     /** ----------------------------------------
     		/**  Pulldown Addition - Any, All, Exact
     		/** ----------------------------------------*/
     if (isset($this->_meta['where']) && $this->_meta['where'] == 'exact') {
         $_POST['exact_keyword'] = 'y';
     }
     /** ----------------------------------------
     		/**  Do we have a search results page?
     		/** ----------------------------------------*/
     // The search results template is specified as a parameter in the search form tag.
     // If the parameter is missing we'll issue an error since we don't know where to
     // show the results
     if (!isset($this->_meta['result_page']) or $this->_meta['result_page'] == '') {
         return $this->EE->output->show_user_error('general', array(lang('search_path_error')));
     }
     /** ----------------------------------------
     		/**  Is the current user allowed to search?
     		/** ----------------------------------------*/
     if ($this->EE->session->userdata('can_search') == 'n' and $this->EE->session->userdata('group_id') != 1) {
         return $this->EE->output->show_user_error('general', array(lang('search_not_allowed')));
     }
     /** ----------------------------------------
     		/**  Flood control
     		/** ----------------------------------------*/
     if ($this->EE->session->userdata['search_flood_control'] > 0 and $this->EE->session->userdata['group_id'] != 1) {
         $cutoff = time() - $this->EE->session->userdata['search_flood_control'];
         $sql = "SELECT search_id FROM exp_search WHERE site_id = '" . $this->EE->db->escape_str($this->EE->config->item('site_id')) . "' AND search_date > '{$cutoff}' AND ";
         if ($this->EE->session->userdata['member_id'] != 0) {
             $sql .= "(member_id='" . $this->EE->db->escape_str($this->EE->session->userdata('member_id')) . "' OR ip_address='" . $this->EE->db->escape_str($this->EE->input->ip_address()) . "')";
         } else {
             $sql .= "ip_address='" . $this->EE->db->escape_str($this->EE->input->ip_address()) . "'";
         }
         $query = $this->EE->db->query($sql);
         $text = str_replace("%x", $this->EE->session->userdata['search_flood_control'], lang('search_time_not_expired'));
         if ($query->num_rows() > 0) {
             return $this->EE->output->show_user_error('general', array($text));
         }
     }
     /** ----------------------------------------
     		/**  Did the user submit any keywords?
     		/** ----------------------------------------*/
     // We only require a keyword if the member name field is blank
     if (!isset($_GET['mbr']) or !is_numeric($_GET['mbr'])) {
         if (!isset($_POST['member_name']) or $_POST['member_name'] == '') {
             if (!isset($_POST['keywords']) or $_POST['keywords'] == "") {
                 return $this->EE->output->show_user_error('general', array(lang('search_no_keywords')));
             }
         }
     }
     /** ----------------------------------------
     		/**  Strip extraneous junk from keywords
     		/** ----------------------------------------*/
     if ($_POST['keywords'] != "") {
         // Load the search helper so we can filter the keywords
         $this->EE->load->helper('search');
         $this->keywords = sanitize_search_terms($_POST['keywords']);
         /** ----------------------------------------
         			/**  Is the search term long enough?
         			/** ----------------------------------------*/
         if (strlen($this->keywords) < $this->min_length) {
             $text = lang('search_min_length');
             $text = str_replace("%x", $this->min_length, $text);
             return $this->EE->output->show_user_error('general', array($text));
         }
         // Load the text helper
         $this->EE->load->helper('text');
         $this->keywords = $this->EE->config->item('auto_convert_high_ascii') == 'y' ? ascii_to_entities($this->keywords) : $this->keywords;
         /** ----------------------------------------
         			/**  Remove "ignored" words
         			/** ----------------------------------------*/
         if ((!isset($_POST['exact_keyword']) or $_POST['exact_keyword'] != 'y') && @(include_once APPPATH . 'config/stopwords.php')) {
             $parts = explode('"', $this->keywords);
             $this->keywords = '';
             foreach ($parts as $num => $part) {
                 // The odd breaks contain quoted strings.
                 if ($num % 2 == 0) {
                     foreach ($ignore as $badword) {
                         $part = preg_replace("/\\b" . preg_quote($badword, '/') . "\\b/i", "", $part);
                     }
                 }
                 $this->keywords .= $num != 0 ? '"' . $part : $part;
             }
             if (trim($this->keywords) == '') {
                 return $this->EE->output->show_user_error('general', array(lang('search_no_stopwords')));
             }
         }
         /** ----------------------------------------
         			/**  Log Search Terms
         			/** ----------------------------------------*/
         $this->EE->functions->log_search_terms($this->keywords);
     }
     if (isset($_POST['member_name']) and $_POST['member_name'] != "") {
         $_POST['member_name'] = $this->EE->security->xss_clean($_POST['member_name']);
     }
     /** ----------------------------------------
     		/**  Build and run query
     		/** ----------------------------------------*/
     $original_keywords = $this->keywords;
     $mbr = !isset($_GET['mbr']) ? '' : $_GET['mbr'];
     $sql = $this->build_standard_query();
     /** ----------------------------------------
     		/**  No query results?
     		/** ----------------------------------------*/
     if ($sql == FALSE) {
         if (isset($this->_meta['no_results_page']) and $this->_meta['no_results_page'] != '') {
             $hash = $this->EE->functions->random('md5');
             $data = array('search_id' => $hash, 'search_date' => time(), 'member_id' => $this->EE->session->userdata('member_id'), 'keywords' => $original_keywords != '' ? $original_keywords : $mbr, 'ip_address' => $this->EE->input->ip_address(), 'total_results' => 0, 'per_page' => 0, 'query' => '', 'custom_fields' => '', 'result_page' => '', 'site_id' => $this->EE->config->item('site_id'));
             $this->EE->db->query($this->EE->db->insert_string('exp_search', $data));
             return $this->EE->functions->redirect($this->EE->functions->create_url($this->EE->functions->extract_path("='" . $this->_meta['no_results_page'] . "'")) . '/' . $hash . '/');
         } else {
             return $this->EE->output->show_user_error('off', array(lang('search_no_result')), lang('search_result_heading'));
         }
     }
     /** ----------------------------------------
     		/**  If we have a result, cache it
     		/** ----------------------------------------*/
     $hash = $this->EE->functions->random('md5');
     $sql = str_replace("\\", "\\\\", $sql);
     // This fixes a bug that occurs when a different table prefix is used
     $sql = str_replace('exp_', 'MDBMPREFIX', $sql);
     $data = array('search_id' => $hash, 'search_date' => time(), 'member_id' => $this->EE->session->userdata('member_id'), 'keywords' => $original_keywords != '' ? $original_keywords : $mbr, 'ip_address' => $this->EE->input->ip_address(), 'total_results' => $this->num_rows, 'per_page' => (isset($_POST['RES']) and is_numeric($_POST['RES']) and $_POST['RES'] < 999) ? $_POST['RES'] : 50, 'query' => addslashes(serialize($sql)), 'custom_fields' => addslashes(serialize($this->fields)), 'result_page' => $this->_meta['result_page'], 'site_id' => $this->EE->config->item('site_id'));
     $this->EE->db->query($this->EE->db->insert_string('exp_search', $data));
     /** ----------------------------------------
     		/**  Redirect to search results page
     		/** ----------------------------------------*/
     // Load the string helper
     $this->EE->load->helper('string');
     $path = $this->EE->functions->remove_double_slashes($this->EE->functions->create_url(trim_slashes($this->_meta['result_page'])) . '/' . $hash . '/');
     return $this->EE->functions->redirect($path);
 }
Ejemplo n.º 9
0
 /**
  * Render the search results
  * @param  string $keywords (Optional) Search keyword from elsewhere
  * @return string           Parsed search results
  */
 public function search_results($keywords = '')
 {
     // Check for pagination
     if (ee()->input->get_post('keywords') === FALSE && $keywords == '') {
         if (!isset($this->seg_parts['1']) or strlen($this->seg_parts['1']) < 20) {
             return $this->return_data = '';
         }
         ee()->db->where('wiki_search_id', $this->seg_parts['1']);
         $query = ee()->db->get('wiki_search');
         if ($query->num_rows() > 0) {
             // Retrieve information about the search
             $paginate_sql = $query->row('wiki_search_query');
             $paginate_hash = $query->row('wiki_search_id');
             $keywords = $query->row('wiki_search_keywords');
         }
     }
     /** ----------------------------------------
     		/**  Work Up the Keywords A Bit, Know What I'm Saying?
     		/** ----------------------------------------*/
     $keywords = ee()->input->get_post('keywords') !== FALSE ? ee()->input->get_post('keywords') : $keywords;
     // Load the search helper so we can filter the keywords
     ee()->load->helper('search');
     $keywords = ee()->functions->encode_ee_tags(sanitize_search_terms($keywords), TRUE);
     if ($keywords == '') {
         $this->redirect('', 'index');
     } elseif (strlen($keywords) < $this->min_length_keywords) {
         return ee()->output->show_user_error('general', array(str_replace("%x", $this->min_length_keywords, lang('search_min_length'))));
     }
     $this->return_data = str_replace(array('{wiki:page}', '{keywords}'), array($this->_fetch_template('wiki_special_search_results.html'), stripslashes($keywords)), $this->return_data);
     // Start work on pagination
     ee()->load->library('pagination');
     $pagination = ee()->pagination->create();
     $this->return_data = $pagination->prepare($this->return_data);
     /** ----------------------------------------
     		/**  Parse Results Tag Pair
     		/** ----------------------------------------*/
     if (!preg_match("/\\{wiki:search_results(.*?)\\}(.*?)\\{\\/wiki:search_results\\}/s", $this->return_data, $match)) {
         return $this->return_data = '';
     }
     /** ----------------------------------------
     		/**  Parameters
     		/** ----------------------------------------*/
     $parameters = ee()->functions->assign_parameters($match[1], array('limit' => 20, 'paginate' => 'bottom', 'switch' => ''));
     /* ----------------------------------------
     		/*  Date Formats
     		/*	- Those GMT dates are not typical for results, but I thought it might
     		/*  be the case that there will be dynamic RSS/Atom searches in the
     		/*  future so I added them just in case.
     		/* ----------------------------------------*/
     $dates = $this->parse_dates($this->return_data);
     /** ----------------------------------------
     		/**  Our Query
     		/** ----------------------------------------*/
     if ($pagination->paginate === TRUE && isset($paginate_sql)) {
         $sql = $paginate_sql;
     } else {
         $sql = "FROM exp_wiki_revisions r, exp_members m, exp_wiki_page p\n\t\t\t\tWHERE p.page_id = r.page_id\n\t\t\t\t\tAND p.last_updated = r.revision_date\n\t\t\t\t\tAND p.wiki_id = '" . ee()->db->escape_str($this->wiki_id) . "'\n\t\t\t\t\tAND (";
         /** -------------------------------------
         			/**  Get our keywords into search terms
         			/** -------------------------------------*/
         $terms = array();
         $keywords = stripslashes($keywords);
         $nsql = '';
         if (stristr(strtolower($keywords), 'namespace:')) {
             $namespaces = array('Category' => 'category');
             $nquery = ee()->db->query("SELECT namespace_label, namespace_name FROM exp_wiki_namespaces");
             if ($nquery->num_rows() > 0) {
                 foreach ($nquery->result_array() as $row) {
                     $namespaces[$row['namespace_label']] = $row['namespace_name'];
                 }
             }
             foreach ($namespaces as $key => $val) {
                 if (preg_match("/namespace:\\s*(\\-)*\\s*[\\'\"]?(" . preg_quote($key, '/') . ")[\\'\"]?/", $keywords, $nmatch)) {
                     $keywords = str_replace($nmatch['0'], '', $keywords);
                     $compare = $nmatch['1'] == "-" ? '!=' : '=';
                     $nsql = "AND p.page_namespace {$compare} '" . $namespaces[$nmatch['2']] . "' \n";
                 }
             }
         }
         // in case they searched with only "namespace:namespace_label" and no keywords
         if (trim($keywords) == '') {
             return ee()->output->show_user_error('general', array(lang('no_search_terms')));
         }
         if (preg_match_all("/\\-*\"(.*?)\"/", $keywords, $matches)) {
             for ($m = 0; $m < count($matches['1']); $m++) {
                 $terms[] = trim(str_replace('"', '', $matches['0'][$m]));
                 $keywords = str_replace($matches['0'][$m], '', $keywords);
             }
         }
         if (trim($keywords) != '') {
             $terms = array_merge($terms, preg_split("/\\s+/", trim($keywords)));
         }
         $not_and = count($terms) > 2 ? ') AND (' : 'AND';
         rsort($terms);
         /** -------------------------------------
         			/**  Log Search Terms
         			/** -------------------------------------*/
         ee()->functions->log_search_terms(implode(' ', $terms), 'wiki');
         /** -------------------------------------
         			/**  Search in content and article title
         			/** -------------------------------------*/
         $mysql_function = substr($terms['0'], 0, 1) == '-' ? 'NOT LIKE' : 'LIKE';
         $search_term = substr($terms['0'], 0, 1) == '-' ? substr($terms['0'], 1) : $terms['0'];
         $connect = $mysql_function == 'LIKE' ? 'OR' : 'AND';
         $sql .= "\n(r.page_content {$mysql_function} '%" . ee()->db->escape_like_str($search_term) . "%' ";
         $sql .= "{$connect} p.page_name {$mysql_function} '%" . ee()->db->escape_like_str($search_term) . "%') ";
         for ($i = 1; $i < count($terms); $i++) {
             $mysql_criteria = ($mysql_function == 'NOT LIKE' or substr($terms[$i], 0, 1) == '-') ? $not_and : 'AND';
             $mysql_function = substr($terms[$i], 0, 1) == '-' ? 'NOT LIKE' : 'LIKE';
             $search_term = substr($terms[$i], 0, 1) == '-' ? substr($terms[$i], 1) : $terms[$i];
             $connect = $mysql_function == 'LIKE' ? 'OR' : 'AND';
             $sql .= "{$mysql_criteria} (r.page_content {$mysql_function} '%" . ee()->db->escape_like_str($search_term) . "%' ";
             $sql .= "{$connect} p.page_name {$mysql_function} '%" . ee()->db->escape_like_str($search_term) . "%') ";
         }
         // close it up, and add our namespace clause
         $sql .= "\n) \n{$nsql}";
         $sql .= "AND m.member_id = r.revision_author\n\t\t\t\t\t AND r.revision_status = 'open'\n\t\t\t\t\t ORDER BY r.revision_date";
     }
     $query = ee()->db->query("SELECT COUNT(*) AS count " . $sql);
     if ($query->row('count') == 0) {
         $this->return_data = $this->_deny_if('results', $this->return_data);
         $this->return_data = $this->_allow_if('no_results', $this->return_data);
         $this->return_data = str_replace($match['0'], '', $this->return_data);
         return;
     } else {
         $this->return_data = $this->_allow_if('results', $this->return_data);
         $this->return_data = $this->_deny_if('no_results', $this->return_data);
     }
     /** ----------------------------------------
     		/**  Store Pagination Hash and Query and do Garbage Collection
     		/** ----------------------------------------*/
     if ($query->row('count') > $parameters['limit'] && $pagination->current_page === 1) {
         $paginate_hash = ee()->functions->random('md5');
         ee()->db->insert('wiki_search', array('wiki_search_id' => $paginate_hash, 'search_date' => time(), 'wiki_search_query' => $sql, 'wiki_search_keywords' => $keywords));
         // Clear old search results
         ee()->db->where('search_date <', time() - $this->cache_expire * 3600);
         ee()->db->delete('wiki_search');
     }
     /** ----------------------------------------
     		/**  Rerun Query This Time With Our Data
     		/** ----------------------------------------*/
     if ($pagination->paginate === TRUE) {
         $base_paginate = $this->base_url . $this->special_ns . ':Search_results/';
         if (isset($paginate_hash)) {
             $base_paginate .= $paginate_hash . '/';
         }
         $pagination->basepath = $base_paginate;
         $pagination->position = $parameters['paginate'];
         $pagination->build($query->row('count'), $parameters['limit']);
         $pagination_sql = " LIMIT {$pagination->offset}, {$parameters['limit']}";
     } else {
         $pagination_sql = " LIMIT " . $parameters['limit'];
     }
     $query = ee()->db->query("SELECT r.*, m.member_id, m.screen_name, m.email, m.url, p.page_namespace, p.page_name AS topic " . $sql . $pagination_sql);
     /** ----------------------------------------
     		/**  Global Last Updated
     		/** ----------------------------------------*/
     $this->return_data = ee()->TMPL->parse_date_variables($this->return_data, array('last_updated' => $query->row('revision_date')));
     $this->return_data = ee()->TMPL->parse_date_variables($this->return_data, array('gmt_last_updated' => $query->row('revision_date')), FALSE);
     /** ----------------------------------------
     		/**  Parsing of the Results
     		/** ----------------------------------------*/
     $results = $this->parse_results($match, $query, $parameters, $dates, $pagination);
     $results = $pagination->render($results);
     $this->return_data = str_replace($match['0'], $results, $this->return_data);
 }
 function search()
 {
     // Load native EE helper to sanitize search term
     $this->EE->load->helper('search');
     // Set the return location
     $return = $this->EE->TMPL->fetch_param('return') ? $this->EE->TMPL->fetch_param('return') : 'catalog/result';
     // Get the product search collection
     $term = $this->EE->TMPL->fetch_param('term') ? $this->EE->TMPL->fetch_param('term') : $this->EE->input->post('search', TRUE);
     $term = sanitize_search_terms($term);
     $hits = $this->_search_index($term);
     $hash = sha1(time() . $term);
     $i = 0;
     $product = array();
     foreach ($hits as $hit) {
         $tmp = $this->EE->product_model->get_products($hit["product_id"]);
         // Check to make sure that a product is returned
         if (isset($tmp[0])) {
             if ($tmp[0]["site_id"] == $this->site_id) {
                 $product[$i] = $tmp[0];
                 $product[$i]["score"] = round(100 * $hit["score"], 2);
                 $product[$i]["row_count"] = $i + 1;
                 $i++;
             }
         }
     }
     // Count the products but set
     // a reasonable search result
     // limit
     $count = count($product);
     if ($count > $this->_config["result_limit"]) {
         $lim = $count - 1;
         for ($i = $this->_config["result_limit"]; $i <= $count; $i++) {
             unset($product[$i]);
         }
         $count = $this->_config["result_limit"];
     }
     $vars[0] = array('search_hash' => $hash, 'search_term' => $term, 'total_results' => count($product), 'results' => $product, 'no_results' => array(), 'result_filter_set' => '');
     save_to_cache('search_' . $hash, serialize($vars));
     $this->EE->product_model->log_search($term, $hash, count($product), $this->EE->session->userdata["member_id"]);
     $this->EE->functions->redirect($this->EE->functions->create_url($return . '/id/' . $hash));
 }
Ejemplo n.º 11
0
 /**
  * Sanitize Search Terms
  *
  * Filters a search string for security
  *
  * @access	public
  * @param	string
  * @return	string
  */
 public function sanitize_search_terms($str)
 {
     ee()->load->helper('search');
     return sanitize_search_terms($str);
 }
Ejemplo n.º 12
0
	/** -------------------------------------
	/**  Search Some Content!
	/** -------------------------------------*/
	function search_results($keywords='')
	{
		/** ----------------------------------------
		/**  Check for Pagination
		/** ----------------------------------------*/
		
		$search_paginate = FALSE;
		
		if ($this->EE->input->get_post('keywords') === FALSE && $keywords == '')
		{
			if ( ! isset($this->seg_parts['1']) OR strlen($this->seg_parts['1']) < 20)
			{
				return $this->return_data = '';
			}
								
			$this->EE->db->where('wiki_search_id', $this->seg_parts['1']);
			$query = $this->EE->db->get('wiki_search');
								 
			if ($query->num_rows() > 0)
			{
				$search_paginate = TRUE;
				$paginate_sql	 = $query->row('wiki_search_query') ;
				$paginate_hash	 = $query->row('wiki_search_id') ; 
				$keywords		 = $query->row('wiki_search_keywords') ;
			}
		}
		
		/** ----------------------------------------
		/**  Work Up the Keywords A Bit, Know What I'm Saying?
		/** ----------------------------------------*/
		
		$keywords = ($this->EE->input->get_post('keywords') !== FALSE) ? $this->EE->input->get_post('keywords') : $keywords;
		
		// Load the search helper so we can filter the keywords
		$this->EE->load->helper('search');
		
		$keywords = $this->EE->functions->encode_ee_tags(sanitize_search_terms($keywords), TRUE);
		
		if ($keywords == '')
		{
			$this->redirect('', 'index');
		}
		elseif(strlen($keywords) < $this->min_length_keywords)
		{
			return $this->EE->output->show_user_error('general', array(str_replace("%x", $this->min_length_keywords, $this->EE->lang->line('search_min_length'))));
		}
		
		$this->return_data = str_replace(array('{wiki:page}', '{keywords}'), 
										 array($this->_fetch_template('wiki_special_search_results.html'), stripslashes($keywords)), 
										 $this->return_data);
		
		/** ----------------------------------------
		/**  Parse Results Tag Pair
		/** ----------------------------------------*/
		
		if ( ! preg_match("/\{wiki:search_results(.*?)\}(.*?)\{\/wiki:search_results\}/s", $this->return_data, $match))
		{
			return $this->return_data = '';
		}
		
		/** ----------------------------------------
		/**  Parameters
		/** ----------------------------------------*/
		
		$parameters['limit']	= 20;
		$parameters['switch1']	= '';
		$parameters['switch2']	= '';
		$parameters['paginate']	= 'bottom';
		
		if (trim($match['1']) != '' && ($params = $this->EE->functions->assign_parameters($match['1'])) !== FALSE)
		{
			$parameters['limit'] = (isset($params['limit']) && is_numeric($params['limit'])) ? $params['limit'] : $parameters['limit'];
			$parameters['paginate']	= (isset($params['paginate'])) ? $params['paginate'] : $parameters['paginate'];
			
			if (isset($params['switch']))
			{
				if (strpos($params['switch'], '|') !== FALSE)
				{
					$x = explode("|", $params['switch']);
					
					$parameters['switch1'] = $x['0'];
					$parameters['switch2'] = $x['1'];
				}
				else
				{
					$parameters['switch1'] = $params['switch'];
				}
			}	
		}
		
		
		/* ----------------------------------------
		/*  Date Formats
		/*	- Those GMT dates are not typical for results, but I thought it might 
		/*  be the case that there will be dynamic RSS/Atom searches in the 
		/*  future so I added them just in case.
		/* ----------------------------------------*/
		
		$dates = $this->parse_dates($this->return_data);
		
		// Secure Forms check
	  	// If the hash is not found we'll simply reload the page.
	  
		if ($this->EE->config->item('secure_forms') == 'y' && $search_paginate === FALSE)
		{
			if ($this->EE->security->secure_forms_check($this->EE->input->post('XID')) == FALSE)
			{
				$this->redirect('', $this->EE->input->get_post('title'));
			}
		}
		
		/** ----------------------------------------
		/**  Our Query
		/** ----------------------------------------*/
		
		if ($search_paginate === TRUE)
		{
			$sql = $paginate_sql;
		}
		else
		{
			$sql =	"FROM exp_wiki_revisions r, exp_members m, exp_wiki_page p
					 WHERE p.page_id = r.page_id
					 AND p.last_updated = r.revision_date
					 AND p.wiki_id = '".$this->EE->db->escape_str($this->wiki_id)."'
					 AND (";
		
			/** -------------------------------------
			/**  Get our keywords into search terms
			/** -------------------------------------*/
			
			$terms = array();
			$keywords = stripslashes($keywords);
			$nsql = '';
			
			if (stristr(strtolower($keywords), 'namespace:'))
			{
				$namespaces = array('Category' => 'category');

				$nquery = $this->EE->db->query("SELECT namespace_label, namespace_name FROM exp_wiki_namespaces");

				if ($nquery->num_rows() > 0)
				{
					foreach ($nquery->result_array() as $row)
					{
						$namespaces[$row['namespace_label']] = $row['namespace_name'];
					}
				}

				foreach ($namespaces as $key => $val)
				{
					if (preg_match("/namespace:\s*(\-)*\s*[\'\"]?(".preg_quote($key, '/').")[\'\"]?/", $keywords, $nmatch))
					{
						$keywords = str_replace($nmatch['0'], '', $keywords);
						
						$compare = ($nmatch['1'] == "-") ? '!=' : '=';
						$nsql = "AND p.page_namespace {$compare} '".$namespaces[$nmatch['2']]."' \n";
					}
				}				
			}
			
			// in case they searched with only "namespace:namespace_label" and no keywords
			if (trim($keywords) == '')
			{
				return $this->EE->output->show_user_error('general', array($this->EE->lang->line('no_search_terms')));				
			}
			
			if (preg_match_all("/\-*\"(.*?)\"/", $keywords, $matches))
			{
				for($m=0; $m < count($matches['1']); $m++)
				{
					$terms[] = trim(str_replace('"','',$matches['0'][$m]));
					$keywords = str_replace($matches['0'][$m],'', $keywords);
				}	
			}

			if (trim($keywords) != '')
			{
				$terms = array_merge($terms, preg_split("/\s+/", trim($keywords)));
  			}
  			
  			$not_and = (count($terms) > 2) ? ') AND (' : 'AND';
  			rsort($terms);
			
			/** -------------------------------------
			/**  Log Search Terms
			/** -------------------------------------*/
			
			$this->EE->functions->log_search_terms(implode(' ', $terms), 'wiki');
			
			/** -------------------------------------
			/**  Search in content and article title
			/** -------------------------------------*/
			$mysql_function	= (substr($terms['0'], 0,1) == '-') ? 'NOT LIKE' : 'LIKE';	
			$search_term	= (substr($terms['0'], 0,1) == '-') ? substr($terms['0'], 1) : $terms['0'];
			$connect		= ($mysql_function == 'LIKE') ? 'OR' : 'AND';

			$sql .= "\n(r.page_content {$mysql_function} '%".$this->EE->db->escape_like_str($search_term)."%' ";
			$sql .= "{$connect} p.page_name {$mysql_function} '%".$this->EE->db->escape_like_str($search_term)."%') ";

			for ($i=1; $i < count($terms); $i++) 
			{
				$mysql_criteria	= ($mysql_function == 'NOT LIKE' OR substr($terms[$i], 0,1) == '-') ? $not_and : 'AND';
				$mysql_function	= (substr($terms[$i], 0,1) == '-') ? 'NOT LIKE' : 'LIKE';
				$search_term	= (substr($terms[$i], 0,1) == '-') ? substr($terms[$i], 1) : $terms[$i];
				$connect		= ($mysql_function == 'LIKE') ? 'OR' : 'AND';
				
				$sql .= "{$mysql_criteria} (r.page_content {$mysql_function} '%".$this->EE->db->escape_like_str($search_term)."%' ";
				$sql .= "{$connect} p.page_name {$mysql_function} '%".$this->EE->db->escape_like_str($search_term)."%') ";
			}
			
			// close it up, and add our namespace clause
			$sql .= "\n) \n{$nsql}";

			$sql .= "AND m.member_id = r.revision_author
					 AND r.revision_status = 'open'
					 ORDER BY r.revision_date";
		}

		$query = $this->EE->db->query("SELECT COUNT(*) AS count ".$sql);
								
		if ($query->row('count')  == 0)
		{
			$this->return_data = $this->_deny_if('results', $this->return_data);
			$this->return_data = $this->_allow_if('no_results', $this->return_data);
			$this->return_data = str_replace($match['0'], '', $this->return_data);
			return;
		}
		else
		{
			$this->return_data = $this->_allow_if('results', $this->return_data);
			$this->return_data = $this->_deny_if('no_results', $this->return_data);
		}
		
		/** ----------------------------------------
		/**  Store Pagination Hash and Query and do Garbage Collection
		/** ----------------------------------------*/
		
		if ($query->row('count')  > $parameters['limit'] && $search_paginate === FALSE)
		{
			$paginate_hash = $this->EE->functions->random('md5');
			$search_data = array('wiki_search_id' => $paginate_hash, 'search_date' => time(), 'wiki_search_query' => $sql, 'wiki_search_keywords' => $keywords);
			
			$this->EE->db->insert('wiki_search', $search_data);

			// Clear old search results
			$expire = time() - ($this->cache_expire * 3600);
			
			$this->EE->db->where('search_date <', $expire);
			$this->EE->db->delete('wiki_search');			
		}
		
		$base_paginate = $this->base_url.$this->special_ns.':Search_results/';
		
		if (isset($paginate_hash))
		{
			$base_paginate .= $paginate_hash.'/';
		}
		
		$this->pagination($query->row('count') , $parameters['limit'], $base_paginate);
		
		/** ----------------------------------------
		/**  Rerun Query This Time With Our Data
		/** ----------------------------------------*/
		
		if ($this->paginate === TRUE)
		{
			// Now that the Paginate code is removed, we run this again
			preg_match("/\{wiki:search_results(.*?)\}(.*?)\{\/wiki:search_results\}/s", $this->return_data, $match);
		}
		else
		{
			$this->pagination_sql .= " LIMIT ".$parameters['limit'];
		}
		
		$query = $this->EE->db->query("SELECT r.*, m.member_id, m.screen_name, m.email, m.url, p.page_namespace, p.page_name AS topic ".$sql.$this->pagination_sql);
		
		/** ----------------------------------------
		/**  Global Last Updated
		/** ----------------------------------------*/
		
		if (isset($dates['last_updated']))
		{
			foreach($dates['last_updated'] as $key => $value)
			{
				$temp_date = $value['0'];
						
				foreach ($value['1'] as $dvar)
				{
					$temp_date = str_replace($dvar, $this->EE->localize->convert_timestamp($dvar, $results->row('revision_date') , TRUE), $temp_date);		
				}
							
				$this->return_data = str_replace($key, $temp_date, $this->return_data);
			}
		}
		
		if (isset($dates['gmt_last_updated']))
		{
			foreach($dates['gmt_last_updated'] as $key => $value)
			{
				$temp_date = $value['0'];
						
				foreach ($value['1'] as $dvar)
				{
					$temp_date = str_replace($dvar, $this->EE->localize->convert_timestamp($dvar, $results->row('revision_date') , FALSE), $temp_date);		
				}
							
				$this->return_data = str_replace($key, $temp_date, $this->return_data);
			}
		}
		
		/** ----------------------------------------
		/**  Parsing of the Results
		/** ----------------------------------------*/
		
		$results = $this->parse_results($match, $query, $parameters, $dates);
		
		$this->return_data = str_replace($match['0'], $results, $this->return_data);
	}
Ejemplo n.º 13
0
 /**
  * Fetch Get/Post variables
  *
  * GET/POST variables are just a wee bit different when a jquery datatables
  * request is made.  In order to keep stupid IE from caching the ajax request,
  * we add a time= variable to the request.  So here, we can safely assume that
  * a request from datatables will have $_['GET']['time'] in it.
  * There are just a coupla differences, so we construct our array of get/post
  * vars and return 'er/
  *
  * @return 	array
  */
 private function _fetch_get_post_vars()
 {
     $this->load->helper('search');
     $ret = array('author_id' => $this->input->get_post('author_id'), 'cat_id' => $this->input->get_post('cat_id'), 'dir_id' => $this->input->get_post('dir_id') != 'all' && $this->input->get_post('dir_id') != 'null' ? $this->input->get_post('dir_id') : FALSE, 'date_range' => $this->input->get_post('date_range'), 'file_type' => $this->input->get_post('file_type'), 'keywords' => NULL, 'offset' => ($offset = $this->input->get('offset')) ? $offset : 0, 'order' => ($order = $this->input->get('offset')) ? $order : 0, 'per_page' => ($per_page = $this->input->get('per_page')) ? $per_page : $this->per_page, 'status' => $this->input->get_post('status') != 'all' ? $this->input->get_post('status') : '', 'search_in' => $this->input->get_post('search_in'), 'search_type' => $this->input->get_post('search_type'), 'type' => ($type = $this->input->get_post('type')) ? $type : 'all', 'date_range' => $this->input->get_post('date_range'), 'date_start' => (($date_start = $this->input->get_post('custom_date_start')) != 'yyyy-mm-dd' and $date_start !== FALSE) ? $date_start : FALSE, 'date_end' => (($date_end = $this->input->get_post('custom_date_end')) != 'yyyy-mm-dd' and $date_end !== FALSE) ? $date_end : FALSE);
     if ($this->input->post('keywords')) {
         $ret['keywords'] = sanitize_search_terms($this->input->post('keywords'));
     } elseif ($this->input->get('keywords')) {
         $ret['keywords'] = sanitize_search_terms(base64_decode($this->input->get('keywords')));
     }
     return $ret;
 }
Ejemplo n.º 14
0
 /**
  * Edit table datasource
  *
  * Must remain public so that it can be called from the
  * table library!
  *
  * @access	public
  */
 public function _table_datasource($tbl_settings, $defaults)
 {
     // Get filter information
     // ----------------------------------------------------------------
     $keywords = (string) $this->input->post('keywords');
     $channel_id = (string) $this->input->get_post('channel_id');
     if ($channel_id == 'null') {
         $channel_id = NULL;
     }
     if (!$keywords) {
         $keywords = (string) $this->input->get('keywords');
         if ($keywords) {
             $keywords = base64_decode($keywords);
         }
     }
     if ($keywords) {
         $this->load->helper('search');
         $keywords = sanitize_search_terms($keywords);
         if (substr(strtolower($keywords), 0, 3) == 'ip:') {
             $keywords = str_replace('_', '.', $keywords);
         }
     }
     // Because of the auto convert we prepare a specific variable with the converted ascii
     // characters while leaving the $keywords variable intact for display and URL purposes
     $this->load->helper('text');
     $search_keywords = $this->config->item('auto_convert_high_ascii') == 'y' ? ascii_to_entities($keywords) : $keywords;
     $perpage = $this->input->get_post('perpage');
     $perpage = $perpage ? $perpage : $defaults['perpage'];
     $rownum = $tbl_settings['offset'];
     // We want the filter to work based on both get and post
     $filter_data = array('channel_id' => $channel_id, 'keywords' => $keywords, 'cat_id' => $this->input->get_post('cat_id'), 'status' => $this->input->get_post('status'), 'order' => $this->input->get_post('order'), 'date_range' => $this->input->get_post('date_range'), 'author_id' => $this->input->get_post('author_id'), 'exact_match' => $this->input->get_post('exact_match'), 'cat_id' => $this->input->get_post('cat_id') != 'all' ? $this->input->get_post('cat_id') : '', 'search_in' => $this->input->get_post('search_in') ? $this->input->get_post('search_in') : 'title', 'rownum' => $rownum, 'perpage' => $perpage, 'search_keywords' => $search_keywords);
     $channels = $defaults['channels'];
     $order = $tbl_settings['sort'];
     $columns = $tbl_settings['columns'];
     // -------------------------------------------
     // 'edit_entries_additional_where' hook.
     //  - Add additional where, where_in, where_not_in
     //
     $_hook_wheres = $this->extensions->call('edit_entries_additional_where', $filter_data);
     if ($this->extensions->end_script === TRUE) {
         return;
     }
     //
     // -------------------------------------------
     $filter_data['_hook_wheres'] = is_array($_hook_wheres) ? $_hook_wheres : array();
     $this->load->model('search_model');
     $filter_result = $this->search_model->get_filtered_entries($filter_data, $order);
     $rows = $filter_result['results'];
     $total = $filter_result['total_count'];
     unset($filter_result);
     $filter_url = $this->_create_return_filter($filter_data);
     // Gather up ids for a single quick query down the line
     $entry_ids = array();
     foreach ($rows as $row) {
         $entry_ids[] = $row['entry_id'];
     }
     // Load the site's templates
     // ----------------------------------------------------------------
     $templates = array();
     $tquery = $this->db->query("SELECT exp_template_groups.group_name, exp_templates.template_name, exp_templates.template_id\n\t\t\t\t\t\t\tFROM exp_template_groups, exp_templates\n\t\t\t\t\t\t\tWHERE exp_template_groups.group_id = exp_templates.group_id\n\t\t\t\t\t\t\tAND exp_templates.site_id = '" . $this->db->escape_str($this->config->item('site_id')) . "'");
     foreach ($tquery->result_array() as $row) {
         $templates[$row['template_id']] = $row['group_name'] . '/' . $row['template_name'];
     }
     // Comment count
     // ----------------------------------------------------------------
     $show_link = TRUE;
     $comment_counts = array();
     if (count($entry_ids) and $this->db->table_exists('comments')) {
         $comment_qry = $this->db->select('entry_id, COUNT(*) as count')->where_in('entry_id', $entry_ids)->group_by('entry_id')->get('comments');
         foreach ($comment_qry->result() as $row) {
             $comment_counts[$row->entry_id] = $row->count;
         }
     }
     // Date formatting
     $date_fmt = $this->session->userdata('time_format') != '' ? $this->session->userdata('time_format') : $this->config->item('time_format');
     $datestr = '%m/%d/%y %h:%i %a';
     if ($date_fmt != 'us') {
         $datestr = '%Y-%m-%d %H:%i';
     }
     // Autosave - Grab all autosaved entries
     // ----------------------------------------------------------------
     $this->prune_autosave();
     $this->db->select('entry_id, original_entry_id, channel_id, title, author_id, status, entry_date, dst_enabled, comment_total');
     $autosave = $this->db->get('channel_entries_autosave');
     $autosave_array = array();
     $autosave_show = FALSE;
     if ($autosave->num_rows()) {
         $this->load->helper('snippets');
         $autosave_show = TRUE;
     }
     foreach ($autosave->result() as $entry) {
         if ($entry->original_entry_id) {
             $autosave_array[] = $entry->original_entry_id;
         }
     }
     // Status Highlight Colors
     // ----------------------------------------------------------------
     $status_color_q = $this->db->from('channels AS c, statuses AS s, status_groups AS sg')->select('c.channel_id, c.channel_name, s.status, s.highlight')->where('sg.group_id = c.status_group', NULL, FALSE)->where('sg.group_id = s.group_id', NULL, FALSE)->where('sg.site_id', $this->config->item('site_id'))->where('s.highlight !=', '')->where_in('c.channel_id', array_keys($channels))->get();
     $c_array = array();
     foreach ($status_color_q->result_array() as $rez) {
         $c_array[$rez['channel_id'] . '_' . $rez['status']] = str_replace('#', '', $rez['highlight']);
     }
     $colors = array();
     //  Fetch Color Library
     if (file_exists(APPPATH . 'config/colors.php')) {
         include APPPATH . 'config/colors.php';
     }
     // Generate row data
     // ----------------------------------------------------------------
     foreach ($rows as &$row) {
         $url = $this->publish_base_uri . AMP . "M=entry_form" . AMP . "channel_id={$row['channel_id']}" . AMP . "entry_id={$row['entry_id']}" . AMP . $filter_url;
         $row['title'] = anchor(BASE . AMP . $url, $row['title']);
         $row['view'] = '---';
         $row['channel_name'] = $channels[$row['channel_id']]->channel_title;
         $row['entry_date'] = $this->localize->decode_date($datestr, $row['entry_date'], TRUE);
         $row['_check'] = form_checkbox('toggle[]', $row['entry_id'], '', ' class="toggle" id="delete_box_' . $row['entry_id'] . '"');
         // autosave indicator
         if (in_array($row['entry_id'], $autosave_array)) {
             $row['title'] .= NBS . required();
         }
         // screen name email link
         if (!$row['screen_name']) {
             $row['screen_name'] = $row['username'];
         }
         $row['screen_name'] = mailto($row['email'], $row['screen_name']);
         // live look template
         $llt = $row['live_look_template'];
         if ($llt && isset($templates[$llt])) {
             $url = $this->functions->create_url($templates[$row['live_look_template']] . '/' . $row['entry_id']);
             $row['view'] = anchor($this->cp->masked_url($url), lang('view'));
         }
         // Status
         $color_info = '';
         $color_key = $row['channel_id'] . '_' . $row['status'];
         $status_name = ($row['status'] == 'open' or $row['status'] == 'closed') ? lang($row['status']) : $row['status'];
         if (isset($c_array[$color_key]) and $c_array[$color_key] != '') {
             $color = strtolower($c_array[$color_key]);
             $prefix = isset($colors[$color]) ? '' : '#';
             // There are custom colours, override the class above
             $color_info = 'style="color:' . $prefix . $color . ';"';
         }
         $row['status'] = '<span class="status_' . $row['status'] . '"' . $color_info . '>' . $status_name . '</span>';
         // comment_total link
         if (isset($this->installed_modules['comment'])) {
             $all_or_own = 'all';
             if ($row['author_id'] == $this->session->userdata('member_id')) {
                 $all_or_own = 'own';
             }
             // do not move these to the new allowed_group style - they are ANDs not ORs
             if (!$this->cp->allowed_group('can_edit_' . $all_or_own . '_comments') and !$this->cp->allowed_group('can_delete_' . $all_or_own . '_comments') and !$this->cp->allowed_group('can_moderate_comments')) {
                 $row['comment_total'] = '<div class="lightLinks">--</div>';
             } else {
                 $comment_count = isset($comment_counts[$row['entry_id']]) ? $comment_counts[$row['entry_id']] : 0;
                 $view_url = BASE . AMP . 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=comment' . AMP . 'method=index' . AMP . 'entry_id=' . $row['entry_id'];
                 $row['comment_total'] = '<div class="lightLinks">(' . $comment_count . ')' . NBS . anchor($view_url, lang('view')) . '</div>';
             }
         }
         $row = array_intersect_key($row, $columns);
     }
     // comes out with an added:
     // table_html
     // pagination_html
     return array('rows' => $rows, 'no_results' => lang('no_entries_matching_that_criteria'), 'pagination' => array('per_page' => $filter_data['perpage'], 'total_rows' => $total), 'filter_data' => $filter_data, 'autosave_show' => $autosave_show, 'autosave_array' => $autosave_array);
 }
Ejemplo n.º 15
0
 /**
  * Index function
  *
  * @return	void
  */
 public function index($channel_id = '', $message = '', $extra_sql = '', $search_url = '', $form_url = '', $action = '', $extra_fields_search = '', $extra_fields_entries = '', $heading = '')
 {
     if (!$this->cp->allowed_group('can_access_content')) {
         show_error($this->lang->line('unauthorized_access'));
     }
     $channel_id = '';
     $extra_sql = '';
     // $action, $extra_fields_*, and $heading are used by move_comments
     $vars['message'] = $message;
     $action = $action != '' ? $action : $this->input->get_post('action');
     $this->load->library('pagination');
     $this->load->library('table');
     $this->load->helper(array('form', 'text', 'url', 'snippets'));
     $this->api->instantiate('channel_categories');
     // Load the search helper so we can filter the keywords
     $this->load->helper('search');
     $this->cp->set_variable('cp_page_title', $this->lang->line('edit'));
     $this->cp->add_js_script(array('plugin' => 'dataTables', 'ui' => 'datepicker'));
     // Need perpage for js
     // Results per page pull-down menu
     if (!($perpage = $this->input->get_post('perpage'))) {
         $perpage = $this->input->cookie('perpage');
     }
     if ($perpage == '') {
         $perpage = 50;
     }
     $this->cp->add_js_script(array('file' => 'cp/content_edit'));
     $this->javascript->set_global('lang.selection_required', $this->lang->line('selection_required'));
     $cp_theme = !$this->session->userdata('cp_theme') ? $this->config->item('cp_theme') : $this->session->userdata('cp_theme');
     if ($this->config->item('kill_all_humans') !== 'disable' && (mt_rand(0, 5000) == 42 && $this->session->userdata['group_id'] == 1 or $this->config->item('kill_all_humans'))) {
         $this->load->helper('html');
         $image_properties = array('src' => base_url() . "themes/cp_themes/default/images/" . strrev('tobor_rellik') . ".png", 'alt' => '', 'id' => 'extra', 'width' => '228', 'height' => '157', 'style' => 'z-index: 1000; position: absolute; top: 49px; left: 790px');
         $this->javascript->output(array('$("#mainMenu").append(\'' . img($image_properties) . '\')', $this->javascript->animate("#extra", array("left" => 0), 4000, 'function(){$(\'#extra\').fadeOut(3000)}')));
     }
     // Fetch channel ID numbers assigned to the current user
     $allowed_channels = $this->functions->fetch_assigned_channels();
     if (empty($allowed_channels)) {
         show_error($this->lang->line('no_channels'));
     }
     //  Fetch Color Library - We use this to assist with our status colors
     if (file_exists(APPPATH . 'config/colors' . EXT)) {
         include APPPATH . 'config/colors' . EXT;
     } else {
         $colors = '';
     }
     // We need to determine which channel to show entries from
     // if the channel_id combined
     if ($channel_id == '') {
         $channel_id = $this->input->get_post('channel_id');
     }
     if ($channel_id == 'null' or $channel_id === FALSE or !is_numeric($channel_id)) {
         $channel_id = '';
     }
     $cat_group = '';
     // We want the filter to work based on both get and post
     $filter_data['channel_id'] = $channel_id;
     $filter_data['cat_id'] = $this->input->get_post('cat_id');
     $filter_data['status'] = $this->input->get_post('status');
     $filter_data['order'] = $this->input->get_post('order');
     $filter_data['date_range'] = $this->input->get_post('date_range');
     $total_channels = count($allowed_channels);
     $vars['status'] = $filter_data['status'];
     if (isset($_POST['keywords'])) {
         $keywords = sanitize_search_terms($_POST['keywords']);
     } elseif (isset($_GET['keywords'])) {
         $keywords = sanitize_search_terms(base64_decode($_GET['keywords']));
     } else {
         $keywords = '';
     }
     if (substr(strtolower($keywords), 0, 3) == 'ip:') {
         $keywords = str_replace('_', '.', $keywords);
     }
     $filter_data['keywords'] = $keywords;
     // We need this for the filter, so grab it now
     $cat_form_array = $this->api_channel_categories->category_form_tree($this->nest_categories);
     // If we have channels we'll write the JavaScript menu switching code
     if ($total_channels > 0) {
         $this->filtering_menus($cat_form_array);
     }
     // If we're filtering using ajax, we redirect comment only searches
     // So- pass along the filter in the url
     if (isset($this->installed_modules['comment'])) {
         $comment_url = '&ajax=true';
         $comment_url .= $filter_data['channel_id'] != '' ? '&channel_id=' . $filter_data['channel_id'] : '';
         $comment_url .= $filter_data['keywords'] != '' ? '&keywords=' . base64_encode($filter_data['keywords']) : '';
     }
     if (isset($this->installed_modules['comment'])) {
         $table_columns = 9;
     } else {
         $table_columns = 8;
     }
     $this->javascript->set_global(array('edit.pipe' => $this->pipe_length, 'edit.perPage' => $perpage, 'edit.themeUrl' => $this->cp->cp_theme_url, 'edit.tableColumns' => $table_columns, 'lang.noEntries' => $this->lang->line('no_entries_matching_that_criteria')));
     // Do we have a message to show?
     // Note: a message is displayed on this page after editing or submitting a new entry
     if ($this->input->get_post("U") == 'mu') {
         $vars['message'] = $this->lang->line('multi_entries_updated');
     }
     // Declare the "filtering" form
     $vars['search_form'] = $search_url != '' ? $search_url : 'C=content_edit';
     // Channel selection pull-down menu
     // Fetch the names of all channels and write each one in an <option> field
     $fields = array('channel_title', 'channel_id', 'cat_group');
     $where = array();
     // If the user is restricted to specific channels, add that to the query
     if ($this->session->userdata['group_id'] != 1) {
         $where[] = array('channel_id' => $allowed_channels);
     }
     $query = $this->channel_model->get_channels($this->config->item('site_id'), $fields, $where);
     if ($query->num_rows() == 1) {
         $channel_id = $query->row('channel_id');
         $cat_group = $query->row('cat_group');
     } elseif ($channel_id != '') {
         foreach ($query->result_array() as $row) {
             if ($row['channel_id'] == $channel_id) {
                 $channel_id = $row['channel_id'];
                 $cat_group = $row['cat_group'];
             }
         }
     }
     $vars['channel_selected'] = $this->input->get_post('channel_id');
     $vars['channel_select_options'] = array('null' => $this->lang->line('filter_by_channel'));
     if ($query->num_rows() > 1) {
         $vars['channel_select_options']['all'] = $this->lang->line('all');
     }
     foreach ($query->result_array() as $row) {
         $vars['channel_select_options'][$row['channel_id']] = $row['channel_title'];
     }
     // Category pull-down menu
     $vars['category_selected'] = $filter_data['cat_id'];
     $vars['category_select_options'][''] = $this->lang->line('filter_by_category');
     if ($total_channels > 1) {
         $vars['category_select_options']['all'] = $this->lang->line('all');
     }
     $vars['category_select_options']['none'] = $this->lang->line('none');
     if ($cat_group != '') {
         foreach ($cat_form_array as $key => $val) {
             if (!in_array($val['0'], explode('|', $cat_group))) {
                 unset($cat_form_array[$key]);
             }
         }
         $i = 1;
         $new_array = array();
         foreach ($cat_form_array as $ckey => $cat) {
             if ($ckey - 1 < 0 or !isset($cat_form_array[$ckey - 1])) {
                 $vars['category_select_options']['NULL_' . $i] = '-------';
             }
             $vars['category_select_options'][$cat['1']] = str_replace("!-!", "&nbsp;", $cat['2']);
             if (isset($cat_form_array[$ckey + 1]) && $cat_form_array[$ckey + 1]['0'] != $cat['0']) {
                 $vars['category_select_options']['NULL_' . $i] = '-------';
             }
             $i++;
         }
     }
     // Status pull-down menu
     $vars['status_selected'] = $filter_data['status'];
     $vars['status_select_options'][''] = $this->lang->line('filter_by_status');
     $vars['status_select_options']['all'] = $this->lang->line('all');
     $sel_1 = '';
     $sel_2 = '';
     if ($cat_group != '') {
         $sel_1 = $filter_data['status'] == 'open' ? 1 : '';
         $sel_2 = $filter_data['status'] == 'closed' ? 1 : '';
     }
     if ($cat_group != '') {
         $rez = $this->db->query("SELECT status_group FROM exp_channels WHERE channel_id = '{$channel_id}'");
         $query = $this->db->query("SELECT status FROM exp_statuses WHERE group_id = '" . $this->db->escape_str($rez->row('status_group')) . "' ORDER BY status_order");
         if ($query->num_rows() > 0) {
             foreach ($query->result_array() as $row) {
                 $status_name = ($row['status'] == 'closed' or $row['status'] == 'open') ? $this->lang->line($row['status']) : $row['status'];
                 $vars['status_select_options'][$row['status']] = $status_name;
             }
         }
     } else {
         $vars['status_select_options']['open'] = $this->lang->line('open');
         $vars['status_select_options']['closed'] = $this->lang->line('closed');
     }
     // Date range pull-down menu
     $vars['date_selected'] = $filter_data['date_range'];
     $vars['date_select_options'][''] = $this->lang->line('date_range');
     $vars['date_select_options']['1'] = $this->lang->line('past_day');
     $vars['date_select_options']['7'] = $this->lang->line('past_week');
     $vars['date_select_options']['31'] = $this->lang->line('past_month');
     $vars['date_select_options']['182'] = $this->lang->line('past_six_months');
     $vars['date_select_options']['365'] = $this->lang->line('past_year');
     $vars['date_select_options']['custom_date'] = $this->lang->line('any_date');
     // Display order pull-down menu
     $vars['order_selected'] = $filter_data['order'];
     $vars['order_select_options'][''] = $this->lang->line('order');
     $vars['order_select_options']['asc'] = $this->lang->line('ascending');
     $vars['order_select_options']['desc'] = $this->lang->line('descending');
     $vars['order_select_options']['alpha'] = $this->lang->line('alpha');
     $filter_data['perpage'] = $perpage;
     $this->functions->set_cookie('perpage', $perpage, 60 * 60 * 24 * 182);
     $vars['perpage_selected'] = $perpage;
     $vars['perpage_select_options']['10'] = '10 ' . $this->lang->line('results');
     $vars['perpage_select_options']['25'] = '25 ' . $this->lang->line('results');
     $vars['perpage_select_options']['50'] = '50 ' . $this->lang->line('results');
     $vars['perpage_select_options']['75'] = '75 ' . $this->lang->line('results');
     $vars['perpage_select_options']['100'] = '100 ' . $this->lang->line('results');
     $vars['perpage_select_options']['150'] = '150 ' . $this->lang->line('results');
     // Because of the auto convert we prepare a specific variable with the converted ascii
     // characters while leaving the $keywords variable intact for display and URL purposes
     $search_keywords = $this->config->item('auto_convert_high_ascii') == 'y' ? ascii_to_entities($keywords) : $keywords;
     $filter_data['search_keywords'] = $search_keywords;
     $vars['exact_match'] = $this->input->get_post('exact_match');
     $filter_data['exact_match'] = $vars['exact_match'];
     $vars['keywords'] = array('name' => 'keywords', 'value' => stripslashes($keywords), 'id' => 'keywords', 'maxlength' => 200);
     $filter_data['search_in'] = $this->input->get_post('search_in') != '' ? $this->input->get_post('search_in') : 'title';
     $vars['search_in_selected'] = $filter_data['search_in'];
     $vars['search_in_options']['title'] = $this->lang->line('title_only');
     $vars['search_in_options']['body'] = $this->lang->line('title_and_body');
     if (isset($this->installed_modules['comment'])) {
         $vars['search_in_options']['everywhere'] = $this->lang->line('title_body_comments');
     }
     $filter = $this->create_return_filter($filter_data);
     if ($search_url != '') {
         $pageurl = BASE . AMP . $search_url;
     } else {
         $pageurl = BASE . AMP . 'C=content_edit';
     }
     // Get the current row number and add the LIMIT clause to the SQL query
     if (!($rownum = $this->input->get_post('rownum'))) {
         $rownum = 0;
     }
     $filter_data['rownum'] = $rownum;
     $filter_data['perpage'] = $perpage;
     //	 Are there results?
     $filtered_entries = $this->search_model->get_filtered_entries($filter_data);
     // No result?  Show the "no results" message
     $vars['autosave_show'] = FALSE;
     $vars['total_count'] = $filtered_entries['total_count'];
     $pageurl .= $filtered_entries['pageurl'];
     if ($vars['total_count'] == 0) {
         $this->javascript->compile();
         $vars['heading'] = 'edit_channel_entries';
         $vars['search_form_hidden'] = array();
         $this->load->view('content/edit', $vars);
         return;
     }
     $pageurl .= AMP . 'perpage=' . $perpage;
     $vars['form_hidden']['pageurl'] = base64_encode($pageurl);
     // for pagination
     // Full SQL query results
     $query_results = $filtered_entries['results'];
     // --------------------------------------------
     //	 Fetch the channel information we need later
     // --------------------------------------------
     $sql = "SELECT channel_id, channel_name FROM exp_channels ";
     $sql .= "WHERE site_id = '" . $this->db->escape_str($this->config->item('site_id')) . "' ";
     $w_array = array();
     $result = $this->db->query($sql);
     if ($result->num_rows() > 0) {
         foreach ($result->result_array() as $rez) {
             $w_array[$rez['channel_id']] = $rez['channel_name'];
         }
     }
     // --------------------------------------------
     //	 Fetch the status highlight colors
     // --------------------------------------------
     $cql = "SELECT exp_channels.channel_id, exp_channels.channel_name, exp_statuses.status, exp_statuses.highlight\n\t\t\t\t FROM  exp_channels, exp_statuses, exp_status_groups\n\t\t\t\t WHERE exp_status_groups.group_id = exp_channels.status_group\n\t\t\t\t AND   exp_status_groups.group_id = exp_statuses.group_id\n\t\t\t\t AND\texp_statuses.highlight != ''\n\t\t\t\t AND\texp_status_groups.site_id = '" . $this->db->escape_str($this->config->item('site_id')) . "' ";
     // Limit to channels assigned to user
     $sql .= " AND exp_channels.channel_id IN (";
     foreach ($allowed_channels as $val) {
         $sql .= "'" . $val . "',";
     }
     $sql = substr($sql, 0, -1) . ')';
     $result = $this->db->query($cql);
     $c_array = array();
     if ($result->num_rows() > 0) {
         foreach ($result->result_array() as $rez) {
             $c_array[$rez['channel_id'] . '_' . $rez['status']] = str_replace('#', '', $rez['highlight']);
         }
     }
     // information for entries table
     $vars['entries_form'] = $form_url != '' ? $form_url : 'C=content_edit' . AMP . 'M=multi_edit_form';
     $vars['form_hidden'] = $extra_fields_entries;
     $vars['search_form_hidden'] = $extra_fields_search ? $extra_fields_search : array();
     // table headings
     $table_headings = array('#', lang('title'), lang('view'));
     // comments module installed?  If so, add it to the list of headings.
     if (isset($this->installed_modules['comment'])) {
         $table_headings[] .= $this->lang->line('comments');
     }
     $table_headings = array_merge($table_headings, array(lang('author'), lang('date'), lang('channel'), lang('status'), form_checkbox('select_all', 'true', FALSE, 'class="toggle_all"')));
     $vars['table_headings'] = $table_headings;
     // load the site's templates
     $templates = array();
     $tquery = $this->db->query("SELECT exp_template_groups.group_name, exp_templates.template_name, exp_templates.template_id\n\t\t\t\t\t\t\tFROM exp_template_groups, exp_templates\n\t\t\t\t\t\t\tWHERE exp_template_groups.group_id = exp_templates.group_id\n\t\t\t\t\t\t\tAND exp_templates.site_id = '" . $this->db->escape_str($this->config->item('site_id')) . "'");
     if ($tquery->num_rows() > 0) {
         foreach ($tquery->result_array() as $row) {
             $templates[$row['template_id']] = $row['group_name'] . '/' . $row['template_name'];
         }
     }
     // Grab all autosaved entries
     $this->prune_autosave();
     $this->db->select('entry_id, original_entry_id, channel_id, title, author_id, status, entry_date, dst_enabled, comment_total');
     $autosave = $this->db->get('channel_entries_autosave');
     $autosave_array = array();
     foreach ($autosave->result() as $entry) {
         if ($entry->original_entry_id) {
             $autosave_array[] = $entry->original_entry_id;
         }
     }
     $vars['autosave_show'] = $autosave->num_rows() > 0 ? TRUE : FALSE;
     // Loop through the main query result and set up data structure for table
     $vars['entries'] = array();
     $comment_totals = array();
     $i = 0;
     foreach ($query_results as $row) {
         // Entry ID number
         $id_column = $i++;
         if (!isset($row['original_entry_id'])) {
             $vars['entries'][$id_column][] = $row['entry_id'];
         } elseif ($row['original_entry_id'] == 0) {
             $row['entry_id'] = 0;
             $vars['entries'][$id_column][] = $row['original_entry_id'];
         }
         // Channel entry title (view entry)
         $output = anchor(BASE . AMP . 'C=content_publish' . AMP . 'M=entry_form' . AMP . 'channel_id=' . $row['channel_id'] . AMP . 'entry_id=' . $row['entry_id'] . $filter, $row['title']);
         $output .= isset($autosave_array[$row['entry_id']]) ? NBS . required() : '';
         $vars['entries'][$id_column][] = $output;
         // "View"
         if ($row['live_look_template'] != 0 && isset($templates[$row['live_look_template']])) {
             $qm = $this->config->item('force_query_string') == 'y' ? '' : '?';
             $url = $this->functions->create_url($templates[$row['live_look_template']] . '/' . $id_column);
             $view_link = anchor($this->functions->fetch_site_index() . QUERY_MARKER . 'URL=' . $url, $this->lang->line('view'));
         } else {
             $view_link = '--';
         }
         $vars['entries'][$id_column][] = $view_link;
         // Comment count
         $show_link = TRUE;
         if ($row['author_id'] == $this->session->userdata('member_id')) {
             if (!$this->cp->allowed_group('can_edit_own_comments') and !$this->cp->allowed_group('can_delete_own_comments') and !$this->cp->allowed_group('can_moderate_comments')) {
                 $show_link = FALSE;
             }
         } else {
             if (!$this->cp->allowed_group('can_edit_all_comments') and !$this->cp->allowed_group('can_delete_all_comments') and !$this->cp->allowed_group('can_moderate_comments')) {
                 $show_link = FALSE;
             }
         }
         if (isset($this->cp->installed_modules['comment'])) {
             $view_url = BASE . AMP . 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=comment	' . AMP . 'method=index' . AMP . 'entry_id=' . $id_column;
             $view_link = $show_link === FALSE ? '<div class="lightLinks">--</div>' : '<div class="lightLinks">(0)' . NBS . anchor($view_url, $this->lang->line('view')) . '</div>';
             $vars['entries'][$id_column][] = $view_link;
             // Setup an array of entry IDs here so we can do an aggregate query to
             // get an accurate count of total comments for each entry.
             $comment_totals[] = $id_column;
         }
         // Username
         $name = $row['screen_name'] != '' ? $row['screen_name'] : $row['username'];
         $vars['entries'][$id_column][] = mailto($row['email'], $name);
         // Date
         $date_fmt = $this->session->userdata('time_format') != '' ? $this->session->userdata('time_format') : $this->config->item('time_format');
         if ($date_fmt == 'us') {
             $datestr = '%m/%d/%y %h:%i %a';
         } else {
             $datestr = '%Y-%m-%d %H:%i';
         }
         $vars['entries'][$id_column][] = $this->localize->decode_date($datestr, $row['entry_date'], TRUE);
         // Channel
         $vars['entries'][$id_column][] = isset($w_array[$row['channel_id']]) ? '<div class="smallNoWrap">' . $w_array[$row['channel_id']] . '</div>' : '';
         // Status
         $status_name = ($row['status'] == 'open' or $row['status'] == 'closed') ? $this->lang->line($row['status']) : $row['status'];
         $color_info = '';
         if (isset($c_array[$row['channel_id'] . '_' . $row['status']]) and $c_array[$row['channel_id'] . '_' . $row['status']] != '') {
             $color = $c_array[$row['channel_id'] . '_' . $row['status']];
             $prefix = (is_array($colors) and !array_key_exists(strtolower($color), $colors)) ? '#' : '';
             // There are custom colours, override the class above
             $color_info = 'style="color:' . $prefix . $color . ';"';
         }
         $vars['entries'][$id_column][] = '<span class="status_' . $row['status'] . '"' . $color_info . '>' . $status_name . '</span>';
         // Delete checkbox
         $vars['entries'][$id_column][] = form_checkbox('toggle[]', $id_column, '', ' class="toggle" id="delete_box_' . $id_column . '"');
     }
     if (isset($this->cp->installed_modules['comment'])) {
         // Get the total number of comments for each entry
         $this->db->select('comment_id, entry_id, channel_id, COUNT(*) as count');
         $this->db->where_in('entry_id', $comment_totals);
         $this->db->group_by('entry_id');
         $comment_query = $this->db->get('comments');
         foreach ($comment_query->result() as $row) {
             if ($show_link !== FALSE) {
                 $view_url = BASE . AMP . 'C=addons_modules' . AMP . 'M=show_module_cp' . AMP . 'module=comment' . AMP . 'method=index' . AMP . 'entry_id=' . $row->entry_id;
             }
             $view_link = $show_link === FALSE ? '<div class="lightLinks">--</div>' : '<div class="lightLinks">(' . $row->count . ')' . NBS . anchor($view_url, $this->lang->line('view')) . '</div>';
             $vars['entries'][$row->entry_id][3] = $view_link;
         }
     }
     // Pass the relevant data to the paginate class
     $config['base_url'] = $pageurl;
     $config['total_rows'] = $vars['total_count'];
     $config['per_page'] = $perpage;
     $config['page_query_string'] = TRUE;
     $config['query_string_segment'] = 'rownum';
     $config['full_tag_open'] = '<p id="paginationLinks">';
     $config['full_tag_close'] = '</p>';
     $config['prev_link'] = '<img src="' . $this->cp->cp_theme_url . 'images/pagination_prev_button.gif" width="13" height="13" alt="&lt;" />';
     $config['next_link'] = '<img src="' . $this->cp->cp_theme_url . 'images/pagination_next_button.gif" width="13" height="13" alt="&gt;" />';
     $config['first_link'] = '<img src="' . $this->cp->cp_theme_url . 'images/pagination_first_button.gif" width="13" height="13" alt="&lt; &lt;" />';
     $config['last_link'] = '<img src="' . $this->cp->cp_theme_url . 'images/pagination_last_button.gif" width="13" height="13" alt="&gt; &gt;" />';
     $this->pagination->initialize($config);
     $vars['pagination'] = $this->pagination->create_links();
     $vars['heading'] = $heading ? $heading : 'edit_channel_entries';
     $vars['action_options'] = array();
     if (is_array($action)) {
         $vars['action_options'] = $action;
     } elseif ($action == '' or !$this->input->post('toggle')) {
         $vars['action_options'] = array('edit' => $this->lang->line('edit_selected'), 'delete' => $this->lang->line('delete_selected'), '------' => '------', 'add_categories' => $this->lang->line('add_categories'), 'remove_categories' => $this->lang->line('remove_categories'));
     }
     $this->javascript->set_global('autosave_map', $autosave_array);
     $this->javascript->compile();
     $this->load->view('content/edit', $vars);
 }
 /** 
  * Sanitize earch terms
  * 
  * @access private
  * @param string $keywords
  * @param boolean $exact_keyword
  * @return boolean
  */
 private function _sanitize_search_terms($keywords, $exact_keyword = false)
 {
     /** ----------------------------------------
     		/**  Strip extraneous junk from keywords
     		/** ----------------------------------------*/
     if ($keywords != "") {
         // Load the search helper so we can filter the keywords
         $this->EE->load->helper('search');
         $keywords = sanitize_search_terms($keywords);
         /** ----------------------------------------
         			/**  Is the search term long enough?
         			/** ----------------------------------------*/
         if (strlen($keywords) < $this->min_length) {
             $text = $this->EE->lang->line('search_min_length');
             $text = str_replace("%x", $this->min_length, $text);
             return $this->EE->output->show_user_error('general', array($text));
         }
         // Load the text helper
         $this->EE->load->helper('text');
         $keywords = $this->EE->config->item('auto_convert_high_ascii') == 'y' ? ascii_to_entities($keywords) : $keywords;
         /** ----------------------------------------
         			/**  Remove "ignored" words
         			/** ----------------------------------------*/
         if (!$exact_keyword) {
             $parts = explode('"', $keywords);
             $keywords = '';
             foreach ($parts as $num => $part) {
                 // The odd breaks contain quoted strings.
                 if ($num % 2 == 0) {
                     foreach ($this->_ignore as $badword) {
                         $part = preg_replace("/\\b" . preg_quote($badword, '/') . "\\b/i", "", $part);
                     }
                 }
                 $keywords .= $num != 0 ? '"' . $part : $part;
             }
             if (trim($keywords) == '') {
                 return $this->EE->output->show_user_error('general', array($this->EE->lang->line('search_no_stopwords')));
             }
         }
     }
     // finally, double spaces
     $keywords = str_replace("  ", " ", $keywords);
     return $keywords;
 }