/**
     * rank
     * 
     *	@access		public
     *	@return		string 	tagdata
     */
    public function rank()
    {
        $entry_id = '';
        $cat_id = '';
        $dynamic = !$this->check_no(ee()->TMPL->fetch_param('dynamic'));
        // -------------------------------------------
        //  Grab entries
        // -------------------------------------------
        $sql = "FROM  \t\t{$this->sc->db->channel_titles} AS t\r\n\t\t\t\t   LEFT JOIN \t{$this->sc->db->channels} as c \r\n\t\t\t\t   ON \t\t\tc.{$this->sc->db->channel_id} = t.{$this->sc->db->channel_id}";
        if (ee()->TMPL->fetch_param('category') or $cat_id != '' and $dynamic) {
            $sql .= " LEFT JOIN \texp_category_posts \r\n\t\t\t \t\t\t ON \t\tt.entry_id = exp_category_posts.entry_id\r\n\t\t\t\t\t\t LEFT JOIN \texp_categories \r\n\t\t\t\t\t\t ON \t\texp_category_posts.cat_id = exp_categories.cat_id";
        }
        $sql .= " WHERE \tt.site_id \r\n\t\t\t\t\t IN \t('" . implode("','", ee()->TMPL->site_ids) . "') ";
        // -------------------------------------------
        //	Yes, One Could Potentially Show Nothing...
        // -------------------------------------------
        if (!$this->check_yes(ee()->TMPL->fetch_param('show_unfavorited'))) {
            $sql .= " AND (t.favorites_count_public != 0 \r\n\t\t\t\t\t\t AND t.favorites_count_public != '') ";
        }
        if ($this->check_no(ee()->TMPL->fetch_param('show_favorites'))) {
            $sql .= " AND (t.favorites_count_public = 0 OR t.favorites_count_public = '') ";
        }
        if (ee()->TMPL->fetch_param('favorites_start_on') !== FALSE or ee()->TMPL->fetch_param('favorites_stop_before') !== FALSE) {
            $asql = "SELECT DISTINCT \tentry_id\r\n\t\t\t\t\t   FROM \t\t\texp_favorites\r\n\t\t\t\t\t   WHERE \t\t\tsite_id \r\n\t\t\t\t\t   IN \t\t\t\t('" . implode("','", ee()->TMPL->site_ids) . "')";
            if (ee()->TMPL->fetch_param('favorites_start_on')) {
                $asql .= " AND exp_favorites.entry_date >= '" . ee()->localize->convert_human_date_to_gmt(ee()->TMPL->fetch_param('favorites_start_on')) . "' ";
            }
            if (ee()->TMPL->fetch_param('favorites_stop_before')) {
                $asql .= " AND exp_favorites.entry_date < '" . ee()->localize->convert_human_date_to_gmt(ee()->TMPL->fetch_param('favorites_stop_before')) . "' ";
            }
            $aquery = ee()->db->query($asql);
            if ($aquery->num_rows() == 0) {
                return $this->no_results();
            }
            $entries = array();
            foreach ($aquery->result_array() as $row) {
                $entries[] = $row['entry_id'];
            }
            $sql .= " AND t.entry_id IN ('" . implode("','", $entries) . "')";
            unset($aquery);
            unset($entries);
        }
        // -------------------------------------------
        //	We only select un-expired entries
        // -------------------------------------------
        $timestamp = ee()->TMPL->cache_timestamp != '' ? ee()->TMPL->cache_timestamp : ee()->localize->now;
        if (!$this->check_yes(ee()->TMPL->fetch_param('show_future_entries'))) {
            $sql .= " AND t.entry_date < " . $timestamp . " ";
        }
        if (!$this->check_yes(ee()->TMPL->fetch_param('show_expired'))) {
            $sql .= " AND (t.expiration_date = 0 || t.expiration_date > " . $timestamp . ") ";
        }
        // -------------------------------------------
        // Limit to/exclude specific weblogs
        // -------------------------------------------
        if ($channel = ee()->TMPL->fetch_param($this->sc->channel)) {
            $xql = "SELECT \t{$this->sc->db->channel_id} \r\n\t\t\t\t    FROM \t{$this->sc->db->channels} \r\n\t\t\t\t\tWHERE \tsite_id \r\n\t\t\t\t\tIN \t\t('" . implode("','", ee()->db->escape_str(ee()->TMPL->site_ids)) . "') ";
            $xql .= ee()->functions->sql_andor_string($channel, $this->sc->db->channel_name);
            $query = ee()->db->query($xql);
            if ($query->num_rows() == 0) {
                return $this->no_results();
            } else {
                if ($query->num_rows() == 1) {
                    $sql .= "AND t.{$this->sc->db->channel_id} = '" . $query->row($this->sc->db->channel_id) . "' ";
                } else {
                    $sql .= "AND (";
                    foreach ($query->result_array() as $row) {
                        $sql .= "t.{$this->sc->db->channel_id} = '" . $row[$this->sc->db->channel_id] . "' OR ";
                    }
                    $sql = substr($sql, 0, -3);
                    $sql .= ") ";
                }
            }
        }
        // -------------------------------------------
        //  Limit query by category
        // -------------------------------------------
        if (ee()->TMPL->fetch_param('category')) {
            $sql .= ee()->functions->sql_andor_string(ee()->TMPL->fetch_param('category'), 'exp_categories.cat_id') . " ";
        } else {
            if ($cat_id != '' and $dynamic) {
                $sql .= " AND exp_categories.cat_id = '" . ee()->db->escape_str($cat_id) . "' ";
            }
        }
        // -------------------------------------------
        //	Add status declaration
        // -------------------------------------------
        if ($status = ee()->TMPL->fetch_param('status')) {
            $status = str_replace('Open', 'open', $status);
            $status = str_replace('Closed', 'closed', $status);
            $sstr = ee()->functions->sql_andor_string($status, 't.status');
            if (!stristr($sstr, "'closed'")) {
                $sstr .= " AND t.status != 'closed' ";
            }
            $sql .= $sstr;
        } else {
            $sql .= "AND t.status = 'open' ";
        }
        // -------------------------------------------
        //	Limit by number of hours
        // -------------------------------------------
        if ($days = ee()->TMPL->fetch_param('hours')) {
            $time = ee()->localize->now - $days * 60 * 60;
            $sql .= " AND t.entry_date > {$time}";
        }
        // -------------------------------------------
        //	Order by
        // -------------------------------------------
        if (ee()->TMPL->fetch_param('orderby') == 'random') {
            $sql .= " ORDER BY rand()";
        } else {
            $sql .= " ORDER BY count DESC";
        }
        // ----------------------------------------
        //  Pagination!
        // ----------------------------------------
        if (is_numeric(ee()->TMPL->fetch_param('limit'))) {
            $this->p_limit = ee()->TMPL->fetch_param('limit');
        }
        // ----------------------------------------
        //  Favorites Date Required for Ordering?
        // ----------------------------------------
        $sort = in_array(strtoupper(ee()->TMPL->fetch_param('sort')), array('DESC', 'ASC')) ? strtoupper(ee()->TMPL->fetch_param('sort')) : 'DESC';
        if (ee()->TMPL->fetch_param('orderby') == 'favorites_date') {
            $sql = preg_replace("/ORDER BY.+?(LIMIT|\$)/is", "ORDER BY favorites_date " . $sort . ' \\1', $sql);
            $ugh = !$this->check_yes(ee()->TMPL->fetch_param('show_unfavorited')) ? 'INNER' : 'LEFT';
            $sql = preg_replace("/LEFT JOIN\\s+{$this->sc->db->channels}/is", "{$ugh} JOIN \texp_favorites AS f \r\n\t\t\t\t ON \t\t\t(t.entry_id = f.entry_id\r\n        \t\t AND \t\t\tf.favorites_id \r\n\t\t\t\t IN\t\t\t\t(SELECT MAX(favorites_id) FROM exp_favorites GROUP BY entry_id))\r\n        \t\t LEFT JOIN \t\t{$this->sc->db->channels}", $sql);
        }
        // -------------------------------------------
        //	Run query
        // -------------------------------------------
        $orderby = ee()->TMPL->fetch_param('orderby') != '' ? ee()->TMPL->fetch_param('orderby') : 'count';
        if ($orderby == 'favorites_date') {
            $query = ee()->db->query('SELECT t.entry_id, 
						f.entry_date AS favorites_date, 
						t.favorites_count_public AS count ' . $sql);
        } else {
            $query = ee()->db->query('SELECT t.entry_id, 
						t.favorites_count_public AS count ' . $sql);
        }
        // -------------------------------------------
        //	Create entries array
        // -------------------------------------------
        $entries = array();
        if ($query->num_rows() == 0) {
            return $this->no_results();
        } else {
            foreach ($query->result_array() as $row) {
                $entries[] = $row['entry_id'];
            }
            // -------------------------------------------
            //  Pass params
            // -------------------------------------------
            ee()->TMPL->tagparams['entry_id'] = implode("|", $entries);
            if ($orderby == 'favorites_date' or $orderby == 'count') {
                if ($sort == 'ASC') {
                    $entries = array_reverse($entries);
                }
                ee()->TMPL->tagparams['fixed_order'] = implode("|", $entries);
            }
            ee()->TMPL->tagparams['sort'] = $sort;
        }
        // -------------------------------------------
        //  Invoke weblog class
        // -------------------------------------------
        if (APP_VER < 2.0) {
            if (!class_exists('Weblog')) {
                require PATH_MOD . '/weblog/mod.weblog' . EXT;
            }
            $channel = new Weblog();
        } else {
            if (!class_exists('Channel')) {
                require PATH_MOD . '/channel/mod.channel' . EXT;
            }
            $channel = new Channel();
        }
        // --------------------------------------------
        //  Invoke Pagination for EE 2.4 and Above
        // --------------------------------------------
        if (APP_VER >= '2.4.0') {
            ee()->load->library('pagination');
            $channel->pagination = new Pagination_object('Channel');
            // Used by pagination to determine whether we're coming from the cache
            $channel->pagination->dynamic_sql = FALSE;
        }
        // ----------------------------------------
        //  Pre-process related data
        // ----------------------------------------
        //	TMPL class is coded so that only
        //	one method in the weblog class and one
        //	method in the search class are allowed
        //	to parse related entries tags. This is
        //	no doubt for performance reasons.
        // ----------------------------------------
        ee()->TMPL->tagdata = ee()->TMPL->assign_relationship_data(ee()->TMPL->tagdata);
        ee()->TMPL->var_single = array_merge(ee()->TMPL->var_single, ee()->TMPL->related_markers);
        // ----------------------------------------
        //  Execute needed methods
        // ----------------------------------------
        if (APP_VER < 2.0) {
            $channel->fetch_custom_weblog_fields();
        } else {
            $channel->fetch_custom_channel_fields();
        }
        $channel->fetch_custom_member_fields();
        // --------------------------------------------
        //  Pagination Tags Parsed Out
        // --------------------------------------------
        if (APP_VER >= '2.4.0') {
            $channel->pagination->get_template();
        } else {
            $channel->fetch_pagination_data();
        }
        //	----------------------------------------
        //	 Build Weblog Data Query
        //	----------------------------------------
        $channel->build_sql_query();
        // --------------------------------------------
        //  Transfer Pagination Variables Over to Channel object
        //	- Has to go after the building of the query as EE 2.4 does its Pagination work in there
        // --------------------------------------------
        if (APP_VER >= '2.4.0') {
            $transfer = array('paginate' => 'paginate', 'total_pages' => 'total_pages', 'current_page' => 'current_page', 'offset' => 'offset', 'page_next' => 'page_next', 'page_previous' => 'page_previous', 'page_links' => 'pagination_links', 'total_rows' => 'total_rows', 'per_page' => 'per_page', 'per_page' => 'p_limit', 'offset' => 'p_page');
            foreach ($transfer as $from => $to) {
                $channel->{$to} = $channel->pagination->{$from};
            }
        }
        //	----------------------------------------
        //	Empty?
        //	----------------------------------------
        if (trim($channel->sql) == '') {
            if ($this->check_yes(ee()->TMPL->fetch_param('favorites_count'))) {
                return $this->return_data = str_replace(LD . 'favorites_count' . RD, '0', ee()->TMPL->tagdata);
            } else {
                return $this->no_results();
            }
        }
        // ----------------------------------------
        //  Pagination
        // ----------------------------------------
        $query = ee()->db->query(preg_replace("/SELECT(.*?)\\s+FROM\\s+/is", 'SELECT COUNT(*) AS count FROM ', $channel->sql));
        $this->total_rows = $query->row('count');
        //pagination request but no entries?
        if ($query->row('count') == 0 and strpos(ee()->TMPL->tagdata, 'paginate') !== FALSE) {
            return $this->no_results();
        }
        //$sql_remove = 'SELECT t.entry_id ';
        //get pagination info
        $pagination_data = $this->universal_pagination(array('sql' => $channel->sql, 'total_results' => $this->total_rows, 'tagdata' => ee()->TMPL->tagdata, 'limit' => $this->p_limit, 'uri_string' => ee()->uri->uri_string, 'current_page' => $this->current_page));
        //if we paginated, sort the data
        if ($pagination_data['paginate'] === TRUE) {
            $this->paginate = $pagination_data['paginate'];
            $this->page_next = $pagination_data['page_next'];
            $this->page_previous = $pagination_data['page_previous'];
            $this->p_page = $pagination_data['pagination_page'];
            $this->current_page = $pagination_data['current_page'];
            $channel->sql = str_replace($sql_remove, '', $pagination_data['sql']);
            $this->pagination_links = $pagination_data['pagination_links'];
            $this->basepath = $pagination_data['base_url'];
            $this->total_pages = $pagination_data['total_pages'];
            $this->paginate_data = $pagination_data['paginate_tagpair_data'];
            ee()->TMPL->tagdata = $pagination_data['tagdata'];
        } else {
            $channel->sql .= " LIMIT " . $this->p_limit;
        }
        //	----------------------------------------
        //	 Favorites Specific Rewrites!
        //	----------------------------------------
        if ($this->check_yes(ee()->TMPL->fetch_param('favorites_count'))) {
            /*$query = ee()->db->query(
            			preg_replace(
            				"/SELECT(.*?)\s+FROM\s+/is", 
            				'SELECT COUNT(*) AS count FROM ', 
            				$channel->sql
            			)
            		);*/
            return $this->return_data = str_replace(LD . 'favorites_count' . RD, $this->total_rows, ee()->TMPL->tagdata);
        }
        //	----------------------------------------
        //	 Favorites date
        //	----------------------------------------
        if (stristr(ee()->TMPL->tagdata, LD . 'favorites_date ') or ee()->TMPL->fetch_param('orderby') == 'favorites_date') {
            $channel->favorites_date = TRUE;
            $channel->sql = preg_replace("/\\s+FROM\\s+/s", ", f.entry_date AS favorites_date FROM ", ltrim($channel->sql));
            $channel->sql = preg_replace("/LEFT JOIN\\s+{$this->sc->db->channels}/is", "LEFT JOIN \texp_favorites AS f \r\n\t\t\t\t ON \t\t(t.entry_id = f.entry_id\r\n\t\t\t\t AND \t\tf.favorites_id \r\n\t\t\t\t IN \t\t(SELECT MAX(favorites_id) FROM exp_favorites GROUP BY entry_id))\r\n        \t\t LEFT JOIN \t{$this->sc->db->channels}", $channel->sql);
        }
        $channel->query = ee()->db->query($channel->sql);
        if (APP_VER < 2.0) {
            $channel->query->result = $channel->query->result_array();
        }
        //	----------------------------------------
        //	Empty?
        //	----------------------------------------
        if (!isset($channel->query) or $channel->query->num_rows() == 0) {
            return $this->no_results();
        }
        //	----------------------------------------
        //	typography
        //	----------------------------------------
        if (APP_VER < 2.0) {
            if (!class_exists('Typography')) {
                require PATH_CORE . 'core.typography' . EXT;
            }
            $channel->TYPE = new Typography();
            $channel->TYPE->convert_curly = FALSE;
        } else {
            ee()->load->library('typography');
            ee()->typography->initialize();
            ee()->typography->convert_curly = FALSE;
        }
        $channel->fetch_categories();
        // ----------------------------------------
        //  Parse and return entry data
        // ----------------------------------------
        if (APP_VER < 2.0) {
            $channel->parse_weblog_entries();
        } else {
            $channel->parse_channel_entries();
        }
        // --------------------------------------------
        //  Render the Pagination Data
        // --------------------------------------------
        if (APP_VER >= '2.4.0') {
            $channel->return_data = $channel->pagination->render($channel->return_data);
        } else {
            $channel->add_pagination_data();
        }
        // --------------------------------------------
        //  Reverse and Related Entries
        // --------------------------------------------
        if (count(ee()->TMPL->related_data) > 0 and count($channel->related_entries) > 0) {
            $channel->parse_related_entries();
        }
        if (count(ee()->TMPL->reverse_related_data) > 0 and count($channel->reverse_related_entries) > 0) {
            $channel->parse_reverse_related_entries();
        }
        // ----------------------------------------
        //  Handle problem with pagination segments
        //	in the url
        // ----------------------------------------
        if (preg_match("#(/P\\d+)#", ee()->uri->uri_string, $match)) {
            $channel->return_data = str_replace($match['1'], "", $channel->return_data);
        } elseif (preg_match("#(P\\d+)#", ee()->uri->uri_string, $match)) {
            $channel->return_data = str_replace($match['1'], "", $channel->return_data);
        }
        // ----------------------------------------
        //  Pagination Replace
        // ----------------------------------------
        if ($this->paginate == TRUE) {
            $this->paginate_data = str_replace(LD . 'current_page' . RD, $this->current_page, $this->paginate_data);
            $this->paginate_data = str_replace(LD . 'total_pages' . RD, $this->total_pages, $this->paginate_data);
            $this->paginate_data = str_replace(LD . 'pagination_links' . RD, $this->pagination_links, $this->paginate_data);
            if (preg_match("/" . LD . "if previous_page" . RD . "(.+?)" . LD . preg_quote(T_SLASH, '/') . "if" . RD . "/s", $this->paginate_data, $match)) {
                if ($this->page_previous == '') {
                    $this->paginate_data = preg_replace("/" . LD . "if previous_page" . RD . ".+?" . LD . preg_quote(T_SLASH, '/') . "if" . RD . "/s", '', $this->paginate_data);
                } else {
                    $match['1'] = preg_replace("/" . LD . 'path.*?' . RD . "/", $this->page_previous, $match['1']);
                    $match['1'] = preg_replace("/" . LD . 'auto_path' . RD . "/", $this->page_previous, $match['1']);
                    $this->paginate_data = str_replace($match['0'], $match['1'], $this->paginate_data);
                }
            }
            if (preg_match("/" . LD . "if next_page" . RD . "(.+?)" . LD . preg_quote(T_SLASH, '/') . "if" . RD . "/s", $this->paginate_data, $match)) {
                if ($this->page_next == '') {
                    $this->paginate_data = preg_replace("/" . LD . "if next_page" . RD . ".+?" . LD . preg_quote(T_SLASH, '/') . "if" . RD . "/s", '', $this->paginate_data);
                } else {
                    $match['1'] = preg_replace("/" . LD . 'path.*?' . RD . "/", $this->page_next, $match['1']);
                    $match['1'] = preg_replace("/" . LD . 'auto_path' . RD . "/", $this->page_next, $match['1']);
                    $this->paginate_data = str_replace($match['0'], $match['1'], $this->paginate_data);
                }
            }
            $position = !ee()->TMPL->fetch_param('paginate') ? '' : ee()->TMPL->fetch_param('paginate');
            switch ($position) {
                case "top":
                    $channel->return_data = $this->paginate_data . $channel->return_data;
                    break;
                case "both":
                    $channel->return_data = $this->paginate_data . $channel->return_data . $this->paginate_data;
                    break;
                default:
                    $channel->return_data .= $this->paginate_data;
                    break;
            }
        }
        $tagdata = $channel->return_data;
        return $tagdata;
    }
 /**
  * For stand-alone entry forms
  *
  * @return	string
  */
 public function form($return_form = FALSE, $captcha = '')
 {
     // -------------------------------------
     //  Load 'em up
     // -------------------------------------
     $this->load_calendar_datetime();
     $this->load_calendar_parameters();
     $output = '';
     $event_id = '';
     $event_data = array();
     $edit = FALSE;
     // -------------------------------------
     //  Prep the parameters
     // -------------------------------------
     $params = array(array('name' => 'event_name', 'required' => FALSE, 'type' => 'bool', 'multi' => FALSE), array('name' => 'event_id', 'required' => FALSE, 'type' => 'integer', 'multi' => FALSE), array('name' => 'occurrence_id', 'required' => FALSE, 'type' => 'integer', 'multi' => FALSE), array('name' => 'occurrence_date', 'required' => FALSE, 'type' => 'date'), array('name' => 'ignore_field', 'required' => FALSE, 'type' => 'string', 'multi' => TRUE));
     //ee()->TMPL->log_item('Calendar: Processing parameters');
     $this->add_parameters($params);
     // -------------------------------------
     //  Has an event_name been provided?
     // -------------------------------------
     if ($this->P->value('event_name') !== FALSE) {
         $ids = $this->data->get_event_id_from_name($this->P->value('event_name'));
         if (!empty($ids)) {
             $event_id = $ids[0];
             $event_data = $this->data->fetch_event_data_for_view($event_id);
             if (!empty($event_data)) {
                 $edit = TRUE;
             }
         }
     } elseif ($this->P->value('event_id') !== FALSE) {
         $event_data = $this->data->fetch_event_data_for_view($this->P->value('event_id'));
         $event_id = $this->P->value('event_id');
         if (!empty($event_data)) {
             $edit = TRUE;
         }
     } elseif ($this->P->value('occurrence_id') !== FALSE) {
         $event_id = $this->data->fetch_entry_id_by_occurrence_id($this->P->value('occurrence_id'));
         if (!empty($event_id)) {
             $event_id = $event_id[0];
             $edit = TRUE;
         }
     }
     // -------------------------------------
     //  Ignore fields?
     // -------------------------------------
     $ignore_fields = array();
     if ($this->P->value('ignore_field') !== FALSE) {
         $ignore_fields = explode('|', $this->P->value('ignore_field'));
     }
     // -------------------------------------
     //  Add some hidden values if we're creating a new edited occurrence
     // -------------------------------------
     $event_data['edit_occurrence'] = FALSE;
     if ($this->P->value('occurrence_date') !== FALSE and ($this->P->value('event_name') !== FALSE or $this->P->value('event_id') !== FALSE)) {
         //ee()->TMPL->log_item('Calendar: This is an edited occurrence');
         ee()->TMPL->tagdata .= '<input type="hidden" name="entry_id" value="" />' . "\n";
         ee()->TMPL->tagdata .= '<input type="hidden" name="calendar_parent_entry_id" value="{entry_id}" />' . "\n";
         ee()->TMPL->tagdata .= '<input type="hidden" name="event_id" value="' . $event_data['event_id'] . '" />' . "\n";
         ee()->TMPL->tagdata .= '<input type="hidden" name="start_date" value="' . $this->P->value('occurrence_date', 'ymd') . '" />' . "\n";
         ee()->TMPL->tagdata .= '<input type="hidden" name="start_time" value="' . $event_data['start_time'] . '" />' . "\n";
         ee()->TMPL->tagdata .= '<input type="hidden" name="end_time" value="' . $event_data['end_time'] . '" />' . "\n";
         ee()->TMPL->var_single['entry_id'] = 'entry_id';
         $event_data['edit_occurrence'] = TRUE;
         $event_data['new_occurrence'] = TRUE;
         $event_data['occurrence_id'] = '';
         $event_data['ymd'] = $this->P->value('occurrence_date', 'ymd');
     }
     // -------------------------------------
     //  Add date widget
     // -------------------------------------
     if (strpos(ee()->TMPL->tagdata, LD . 'calendar_date_widget' . RD) !== FALSE) {
         ee()->TMPL->tagdata = str_replace(LD . 'calendar_date_widget' . RD, $this->date_widget($event_data), ee()->TMPL->tagdata);
     }
     //	----------------------------------------
     //	Invoke Channel class
     //	----------------------------------------
     if (APP_VER < 2.0) {
         if (!class_exists('Weblog')) {
             require PATH_MOD . '/weblog/mod.weblog' . EXT;
         }
         $channel = new Weblog();
     } else {
         if (!class_exists('Channel')) {
             require PATH_MOD . '/channel/mod.channel' . EXT;
         }
         $channel = new Channel();
     }
     //default is 100 and that could limit events when there are very many to be shown
     $channel->limit = 500;
     // --------------------------------------------
     //  Invoke Pagination for EE 2.4 and Above
     // --------------------------------------------
     if (APP_VER >= '2.4.0') {
         ee()->load->library('pagination');
         $channel->pagination = new Pagination_object('Channel');
         // Used by pagination to determine whether we're coming from the cache
         $channel->pagination->dynamic_sql = FALSE;
     }
     // -------------------------------------
     //  Prepare parameters
     // -------------------------------------
     ee()->TMPL->tagparams['entry_id'] = $event_id;
     ee()->TMPL->tagparams['weblog'] = CALENDAR_EVENTS_CHANNEL_NAME;
     ee()->TMPL->tagparams['channel'] = CALENDAR_EVENTS_CHANNEL_NAME;
     // -------------------------------------
     //  Editing?
     // -------------------------------------
     if ($edit === TRUE) {
         //ee()->TMPL->log_item('Calendar: Editing, so doing Weblog module tasks');
         // -------------------------------------
         //  Pre-process related data
         // -------------------------------------
         ee()->TMPL->tagdata = ee()->TMPL->assign_relationship_data(ee()->TMPL->tagdata);
         ee()->TMPL->var_single = array_merge(ee()->TMPL->var_single, ee()->TMPL->related_markers);
         // -------------------------------------
         //  Execute needed methods
         // -------------------------------------
         if (APP_VER < 2.0) {
             $channel->fetch_custom_weblog_fields();
         } else {
             $channel->fetch_custom_channel_fields();
         }
         $channel->fetch_custom_member_fields();
         // --------------------------------------------
         //  Pagination Tags Parsed Out
         // --------------------------------------------
         if (APP_VER >= '2.4.0') {
             $channel->pagination->get_template();
         } else {
             $channel->fetch_pagination_data();
         }
         // -------------------------------------
         //  Querification
         // -------------------------------------
         $channel->build_sql_query();
         if ($channel->sql == '') {
             return $this->no_results();
         }
         $channel->query = ee()->db->query($channel->sql);
         if ($channel->query->num_rows() == 0) {
             //ee()->TMPL->log_item('Calendar: Channel module says no results, bailing');
             return $this->no_results();
         }
         $channel->query->result = $channel->query->result_array();
         // --------------------------------------------
         //  Typography
         // --------------------------------------------
         if (APP_VER < 2.0) {
             if (!class_exists('Typography')) {
                 require PATH_CORE . 'core.typography' . EXT;
             }
             $channel->TYPE = new Typography();
             $channel->TYPE->text_format = 'none';
             $channel->TYPE->convert_curly = FALSE;
         } else {
             ee()->load->library('typography');
             ee()->typography->initialize();
             ee()->typography->text_format = 'none';
             ee()->typography->convert_curly = FALSE;
         }
         $no_parse = array('xhtml', 'br', 'none', 'lite');
         // -------------------------------------
         //  Add _field_name and _field_format variables
         // -------------------------------------
         foreach ($channel->query->result as $r => $row) {
             $channel->query->result[$r]['author'] = $row['screen_name'] != '' ? $row['screen_name'] : $row['username'];
             foreach ($channel->cfields[$row['site_id']] as $k => $v) {
                 if (in_array($k, $ignore_fields)) {
                     continue;
                 }
                 $channel->query->result[$r][$k . '_field_name'] = 'field_id_' . $v;
                 $channel->query->result[$r][$k . '_format_name'] = 'field_ft_' . $v;
                 $channel->query->result[$r][$k . '_format_value'] = $row['field_ft_' . $v] === NULL ? '' : $row['field_ft_' . $v];
                 // -------------------------------------
                 //  Don't apply any text formatting
                 // -------------------------------------
                 if (in_array($channel->query->result[$r]['field_ft_' . $v], $no_parse)) {
                     $channel->query->result[$r]['field_ft_' . $v] = '';
                 }
             }
         }
         //	----------------------------------------
         //	Redeclare
         //	----------------------------------------
         //	We will reassign the $channel->query->result with our
         //	reordered array of values. Thank you PHP for being so fast with array loops.
         //	----------------------------------------
         if (APP_VER < 2.0) {
             $channel->query->result = $channel->query->result;
             $super_temp_fake = $channel->query->result[0];
         } else {
             $super_temp_fake = $channel->query->result_array = $channel->query->result;
             $super_temp_fake = $channel->query->row_array();
         }
         $channel->fetch_categories();
         // -------------------------------------
         //  Prep ignored fields to be ignored
         // -------------------------------------
         $gibberish = 'e46b98f8a2a06d1ac6069e8980693dc0';
         foreach ($ignore_fields as $field) {
             ee()->TMPL->tagdata = str_replace(LD . $field, LD . $gibberish . $field, ee()->TMPL->tagdata);
         }
         // -------------------------------------
         //  Parse
         // -------------------------------------
         //ee()->TMPL->log_item('Calendar: Parsing, via channel module');
         if (APP_VER < 2.0) {
             $channel->parse_weblog_entries();
         } else {
             $channel->parse_channel_entries();
         }
         // -------------------------------------
         //  De-prep ignored fields
         // -------------------------------------
         foreach ($ignore_fields as $field) {
             $channel->return_data = str_replace(LD . $gibberish . $field, LD . $field, $channel->return_data);
         }
         // -------------------------------------
         //  Paginate
         // -------------------------------------
         if (APP_VER >= '2.4.0') {
             $channel->return_data = $this->channel->pagination->render($this->channel->return_data);
         } else {
             $channel->add_pagination_data();
         }
         // -------------------------------------
         //  Related entries
         // -------------------------------------
         if (count(ee()->TMPL->related_data) > 0 and count($channel->related_entries) > 0) {
             $channel->parse_related_entries();
         }
         if (count(ee()->TMPL->reverse_related_data) > 0 and count($channel->reverse_related_entries) > 0) {
             $channel->parse_reverse_related_entries();
         }
         // -------------------------------------
         //  Grab the goods
         // -------------------------------------
         ee()->TMPL->tagdata = $channel->return_data;
         // -------------------------------------
         //  Add some hidden variables
         // -------------------------------------
         $date = ee()->localize->decode_date('%Y-%m-%d %g:%i %A', $super_temp_fake['entry_date']);
         $more = "<input type='hidden' name='entry_date' value='{$date}' />\n";
         if ($this->P->value('occurrence_date') === FALSE or $this->P->value('event_name') === FALSE or $this->P->value('event_id') === FALSE) {
             $more .= "<input type='hidden' name='entry_id' value='{$event_id}' />\n";
         }
         ee()->TMPL->tagdata .= $more;
     } else {
         // -------------------------------------
         //  Add _field_name and _field_format variables
         // -------------------------------------
         if (APP_VER < 2.0) {
             $channel->fetch_custom_weblog_fields();
         } else {
             $channel->fetch_custom_channel_fields();
         }
         $fields = array();
         foreach ($channel->cfields[$this->data->get_site_id()] as $k => $v) {
             $fields[LD . $k . '_field_name' . RD] = 'field_id_' . $v;
             $fields[LD . $k . '_format_name' . RD] = 'field_ft_' . $v;
             $fields[LD . $k . '_format_value' . RD] = '';
         }
         ee()->TMPL->tagdata = str_replace(array_keys($fields), $fields, ee()->TMPL->tagdata);
     }
     // -------------------------------------
     //  Remove any leftover {event_ or {calendar_ variables
     // -------------------------------------
     if (strpos(ee()->TMPL->tagdata, LD . 'calendar_') !== FALSE) {
         preg_match_all('#' . LD . 'calendar_(.*?)' . RD . '#', ee()->TMPL->tagdata, $matches);
         if (!empty($matches)) {
             foreach ($matches[0] as $k => $match) {
                 ee()->TMPL->tagdata = str_replace($match, '', ee()->TMPL->tagdata);
             }
         }
     }
     if (strpos(ee()->TMPL->tagdata, LD . 'event_') !== FALSE) {
         preg_match_all('#' . LD . '(event_.*?)' . RD . '#', ee()->TMPL->tagdata, $matches);
         if (!empty($matches)) {
             foreach ($matches[0] as $k => $match) {
                 if (!in_array($matches[1][$k], $ignore_fields)) {
                     ee()->TMPL->tagdata = str_replace($match, '', ee()->TMPL->tagdata);
                 }
             }
         }
     }
     //	----------------------------------------
     //	Invoke Channel standalone class
     //	----------------------------------------
     if (APP_VER < 2.0) {
         if (!class_exists('Weblog_standalone')) {
             require_once PATH_MOD . 'weblog/mod.weblog_standalone.php';
         }
         $WS = new Weblog_standalone();
         $output = $WS->entry_form($return_form, $captcha);
     } else {
         if (!class_exists('Channel_standalone')) {
             require_once PATH_MOD . 'channel/mod.channel_standalone.php';
         }
         $CS = new Channel_standalone();
         $output = $CS->entry_form($return_form, $captcha);
     }
     //ee()->TMPL->log_item('Calendar: Done!');
     return $output;
 }
 function search()
 {
     $address = '';
     $tagdata = $this->EE->TMPL->tagdata;
     $prec = !$this->EE->TMPL->fetch_param('prec') ? '' : ',' . $this->EE->TMPL->fetch_param('prec');
     $prefix = !$this->EE->TMPL->fetch_param('prefix') ? '' : ',' . $this->EE->TMPL->fetch_param('prefix');
     $orderby = !$this->EE->TMPL->fetch_param('orderby') ? false : ($this->EE->TMPL->fetch_param('orderby') == 'distance' ? false : $this->EE->TMPL->fetch_param('orderby'));
     $sort = !$this->EE->TMPL->fetch_param('sort') ? 'asc' : $this->EE->TMPL->fetch_param('sort');
     $this->EE->TMPL->tagparams['limit'] = !$this->EE->TMPL->fetch_param('limit') ? 99999 : $this->EE->TMPL->fetch_param('limit');
     $address_fields = !$this->EE->TMPL->fetch_param('address_fields') ? false : $this->EE->TMPL->fetch_param('address_fields');
     $debug = !$this->EE->TMPL->fetch_param('debug') ? false : true;
     //@delete
     $reverse_geocoding = !$this->EE->TMPL->fetch_param('reverse_geocoding') ? '' : ',' . $this->EE->TMPL->fetch_param('reverse_geocoding');
     if (isset($_POST) and count($_POST) > 0 or isset($_GET) and count($_GET) > 0) {
         $zipLongitude = $this->EE->security->xss_clean($this->EE->input->get_post('long'));
         $zipLatitude = $this->EE->security->xss_clean($this->EE->input->get_post('lat'));
         $unit = $this->EE->security->xss_clean($this->EE->input->get_post('unit'));
         //@add to site description
         if ($address_fields) {
             foreach (explode('|', $address_fields) as $field_name) {
                 $address = $this->EE->input->get_post($field_name) ? $address . $this->EE->security->xss_clean($this->EE->input->get_post($field_name)) . ', ' : '';
             }
         } else {
             $address = $this->EE->security->xss_clean($this->EE->input->get_post('address'));
             if (is_array($address)) {
                 $address = implode(",", $address);
             }
         }
         $address = $prefix . $address;
         $radius = $this->EE->security->xss_clean($this->EE->input->get_post('radius'));
     } else {
         $zipLongitude = $this->EE->TMPL->fetch_param('long') != '' ? $this->EE->TMPL->fetch_param('long') : "";
         $zipLatitude = $this->EE->TMPL->fetch_param('lat') != '' ? $this->EE->TMPL->fetch_param('lat') : '';
         $unit = $this->EE->TMPL->fetch_param('unit') != '' ? $this->EE->TMPL->fetch_param('unit') : 'ml';
         $address = $this->EE->TMPL->fetch_param('address') != '' ? $this->EE->TMPL->fetch_param('address') : '';
         $radius = $this->EE->TMPL->fetch_param('radius') != '' ? $this->EE->TMPL->fetch_param('radius') : $this->default_radius;
     }
     $radius = $radius == '' ? $this->default_radius : $radius;
     $earth_radius = $unit == 'km' ? 6371 : 3959;
     //earth_radius
     if (($zipLongitude == "" or $zipLatitude == "") and $address == "") {
         $zipLongitude = $this->default_long;
         $zipLatitude = $this->default_lat;
         $address = $this->default_address;
     }
     $entry_id = '';
     $points = array();
     $entry_id = rtrim($entry_id, '|');
     $channel = new Channel();
     $LD = '\\{';
     $RD = '\\}';
     $SLASH = '\\/';
     $variable = "entries";
     $return_data = "";
     if (isset($_POST['categories'])) {
         $this->EE->TMPL->tagparams['category'] = (isset($this->EE->TMPL->tagparams['category']) ? $this->EE->TMPL->tagparams['category'] : '') . '|' . implode("|", $this->EE->security->xss_clean($_POST['categories']));
     }
     if (preg_match("/" . LD . $variable . ".*?" . RD . "(.*?)" . LD . '\\/' . $variable . RD . "/s", $tagdata, $entries)) {
         $channel->EE->TMPL->tagdata = $entries[1];
         if ($channel->EE->TMPL->fetch_param('related_categories_mode') == 'yes') {
             return $channel->related_entries();
         }
         $channel->initialize();
         $channel->uri = $channel->query_string != '' ? $channel->query_string : 'index.php';
         if ($channel->enable['custom_fields'] == TRUE) {
             $channel->fetch_custom_channel_fields();
         }
         if ($channel->enable['member_data'] == TRUE) {
             $channel->fetch_custom_member_fields();
         }
         if ($channel->enable['pagination'] == TRUE) {
             if (version_compare(APP_VER, '2.4', '>=')) {
                 $channel->add_pagination_data();
             } else {
                 $channel->fetch_pagination_data();
             }
         }
         $save_cache = FALSE;
         $channel->EE->TMPL->tagparams['dynamic'] = 'no';
         //$zipLongitude.$zipLatitude.$address
         if ($channel->EE->config->item('enable_sql_caching') == 'y') {
             if (FALSE == ($channel->sql = $channel->fetch_cache())) {
                 $save_cache = TRUE;
             } else {
                 if ($channel->EE->TMPL->fetch_param('dynamic') != 'no') {
                     if (preg_match("#(^|\\/)C(\\d+)#", $channel->query_string, $match) or in_array($channel->reserved_cat_segment, explode("/", $channel->query_string))) {
                         $channel->cat_request = TRUE;
                     }
                 }
             }
             if (FALSE !== ($cache = $channel->fetch_cache('pagination_count'))) {
                 if (FALSE !== $channel->fetch_cache('field_pagination')) {
                     if (FALSE !== ($pg_query = $channel->fetch_cache('pagination_query'))) {
                         $channel->paginate = TRUE;
                         $channel->field_pagination = TRUE;
                         $channel->create_pagination(trim($cache), $channel->EE->db->query(trim($pg_query)));
                     }
                 } else {
                     $channel->create_pagination(trim($cache));
                 }
             }
         }
         if ($channel->sql == '') {
             $channel->build_sql_query();
         }
         if ($channel->sql == '') {
             return $channel->EE->TMPL->no_results();
         }
         $sql = "";
         //@start geocoding
         //if don't have the Latitude and Longitude, do query to google.map; ($zipLongitude == "" OR $zipLatitude == "") AND
         if ($address != "" and ($zipLongitude == "" or $zipLatitude == "")) {
             $GetLatLong_result = $this->GetLatLong($address, 2);
             if ($GetLatLong_result != false) {
                 list($zipLongitude, $zipLatitude) = $GetLatLong_result;
             } else {
                 return $this->EE->TMPL->no_results();
             }
         }
         if ($reverse_geocoding and $address == "") {
             $GetLatLong_result = $this->GetLatLong($zipLatitude . ',' . $zipLongitude, $api_key, 1);
             if ($GetLatLong_result != false) {
                 $address = $GetLatLong_result;
             } else {
                 return $this->EE->TMPL->no_results();
             }
         }
         //@END geocoding
         $conds['radius'] = $radius;
         $tagdata = $this->EE->functions->prep_conditionals($tagdata, $conds);
         $tagdata = str_replace(array('{center:long}', '{center:lat}', '{radius}'), array($zipLongitude, $zipLatitude, $radius), $tagdata);
         $where_strpos = strpos($channel->sql, "WHERE");
         if ($where_strpos > 0) {
             $sql_entry_id = substr($channel->sql, $where_strpos + 5, strpos($channel->sql, "ORDER BY") - $where_strpos - 5);
             $limit_strpos = strpos($channel->sql, "LIMIT");
             $order_by = substr($channel->sql, strpos($channel->sql, "ORDER BY"), $limit_strpos);
             $limit = substr($channel->sql, strpos($channel->sql, "LIMIT"));
             $sql = str_replace('FROM', ", gm.*, ROUND( {$earth_radius} * acos( cos( radians({$zipLatitude}) ) * cos( radians( gm.latitude ) ) * cos( radians( gm.longitude ) - radians({$zipLongitude}) ) + sin( radians({$zipLatitude}) ) *  sin( radians( gm.latitude ) ) ) {$prec} ) AS distance   FROM ", $channel->sql);
             $sql = substr($sql, 0, strpos($sql, "WHERE")) . "RIGHT JOIN exp_mx_google_map AS gm ON t.entry_id = gm.entry_id HAVING distance < {$radius} AND " . $sql_entry_id;
             if ($orderby) {
                 $sql = $sql . $order_by;
             } else {
                 $sql = $sql . " ORDER BY distance " . $sort;
             }
             $channel->sql = $sql;
         }
         if ($save_cache == TRUE) {
             $channel->save_cache($channel->sql);
         }
         $channel->query = $channel->EE->db->query($channel->sql);
         if ($channel->query->num_rows() == 0) {
             return $channel->EE->TMPL->no_results();
         }
         foreach ($channel->query->result_array() as $row) {
             $points[$row['point_id']] = $row['distance'];
         }
         $channel->EE->TMPL->tagparams['points'] = $points;
         if ($channel->EE->config->item('relaxed_track_views') === 'y' && $channel->query->num_rows() == 1) {
             $channel->hit_tracking_id = $channel->query->row('entry_id');
         }
         $channel->track_views();
         $channel->EE->load->library('typography');
         $channel->EE->typography->initialize();
         $channel->EE->typography->convert_curly = FALSE;
         if ($channel->enable['categories'] == TRUE) {
             $channel->fetch_categories();
         }
         $channel->parse_channel_entries();
         if ($channel->enable['pagination'] == TRUE) {
             if (version_compare(APP_VER, '2.4', '>=')) {
                 $channel->add_pagination_data();
             } else {
                 $channel->fetch_pagination_data();
             }
         }
         if (count($channel->EE->TMPL->related_data) > 0 && count($channel->related_entries) > 0) {
             $channel->parse_related_entries();
         }
         if (count($channel->EE->TMPL->reverse_related_data) > 0 && count($channel->reverse_related_entries) > 0) {
             $channel->parse_reverse_related_entries();
         }
         $return_data = str_replace($entries[0], $channel->return_data, $tagdata);
     }
     return $return_data;
 }
 /**
  *	List of Entires for an Author, Sub-Processing for entries() method
  *
  *	@access		private
  *	@param		array
  *	@return		string
  */
 private function _entries($params = array())
 {
     /**	----------------------------------------
     		/**	Execute?
     		/**	----------------------------------------*/
     if ($this->entry_id == '') {
         return FALSE;
     }
     /**	----------------------------------------
     		/**	Invoke Channel/Weblog class
     		/**	----------------------------------------*/
     if (APP_VER < 2.0) {
         if (!class_exists('Weblog')) {
             require PATH_MOD . 'weblog/mod.weblog' . EXT;
         }
         $channel = new Weblog();
     } else {
         if (!class_exists('Channel')) {
             require PATH_MOD . 'channel/mod.channel.php';
         }
         $channel = new Channel();
     }
     // --------------------------------------------
     //  Invoke Pagination for EE 2.4 and Above
     // --------------------------------------------
     if (APP_VER >= '2.4.0') {
         ee()->load->library('pagination');
         $channel->pagination = new Pagination_object('Channel');
         // Used by pagination to determine whether we're coming from the cache
         $channel->pagination->dynamic_sql = FALSE;
     }
     /**	----------------------------------------
     		/**	Pass params
     		/**	----------------------------------------*/
     ee()->TMPL->tagparams['entry_id'] = $this->entry_id;
     ee()->TMPL->tagparams['inclusive'] = '';
     if (isset($params['dynamic']) and $params['dynamic'] == "off") {
         if (APP_VER < 2.0) {
             ee()->TMPL->tagparams['dynamic'] = 'off';
         } else {
             ee()->TMPL->tagparams['dynamic'] = 'no';
         }
     }
     /**	----------------------------------------
     		/**	Pre-process related data
     		/**	----------------------------------------*/
     ee()->TMPL->tagdata = ee()->TMPL->assign_relationship_data(ee()->TMPL->tagdata);
     ee()->TMPL->var_single = array_merge(ee()->TMPL->var_single, ee()->TMPL->related_markers);
     /**	----------------------------------------
     		/**	Execute needed methods
     		/**	----------------------------------------*/
     if (APP_VER < 2.0) {
         $channel->fetch_custom_weblog_fields();
     } else {
         $channel->fetch_custom_channel_fields();
     }
     $channel->fetch_custom_member_fields();
     // --------------------------------------------
     //  Pagination Tags Parsed Out
     // --------------------------------------------
     if (APP_VER >= '2.4.0') {
         $channel->pagination->get_template();
     } else {
         $channel->fetch_pagination_data();
     }
     if (APP_VER >= '2.4.0') {
         $channel->pagination->cfields = $channel->cfields;
         $channel->pagination->build();
     } else {
         $channel->create_pagination();
     }
     /**	----------------------------------------
     		/**	Grab entry data
     		/**	----------------------------------------*/
     //$channel->create_pagination();
     $channel->build_sql_query();
     if ($channel->sql == '') {
         return $this->no_results();
     }
     $channel->query = ee()->db->query($channel->sql);
     if (APP_VER < 2.0) {
         $channel->query->result = $channel->query->result_array();
     }
     if (!isset($channel->query) or $channel->query->num_rows() == 0) {
         return $this->no_results();
     }
     if (APP_VER < 2.0) {
         if (!class_exists('Typography')) {
             require PATH_CORE . 'core.typography' . EXT;
         }
         $channel->TYPE = new Typography();
         $channel->TYPE->convert_curly = FALSE;
     } else {
         ee()->load->library('typography');
         ee()->typography->initialize();
         ee()->typography->convert_curly = FALSE;
     }
     $channel->fetch_categories();
     /**	----------------------------------------
     		/**	Parse and return entry data
     		/**	----------------------------------------*/
     if (APP_VER < 2.0) {
         $channel->parse_weblog_entries();
     } else {
         $channel->parse_channel_entries();
     }
     if (APP_VER >= '2.4.0') {
         $channel->return_data = $channel->pagination->render($channel->return_data);
     } else {
         $channel->add_pagination_data();
     }
     /**	----------------------------------------
     		/**	Count tag
     		/**	----------------------------------------*/
     if (count(ee()->TMPL->related_data) > 0 and count($channel->related_entries) > 0) {
         $channel->parse_related_entries();
     }
     if (count(ee()->TMPL->reverse_related_data) > 0 and count($channel->reverse_related_entries) > 0) {
         $channel->parse_reverse_related_entries();
     }
     // ----------------------------------------
     //  Handle problem with pagination segments in the url
     // ----------------------------------------
     if (preg_match("#(/P\\d+)#", ee()->uri->uri_string, $match)) {
         $channel->return_data = str_replace($match['1'], "", $channel->return_data);
     } elseif (preg_match("#(P\\d+)#", ee()->uri->uri_string, $match)) {
         $channel->return_data = str_replace($match['1'], "", $channel->return_data);
     }
     $tagdata = $channel->return_data;
     return $tagdata;
 }