Esempio n. 1
0
 /**
  * Return true if the event is past
  * A past event, is events that are has passed more than 24 hours from the last date
  */
 public static function isPast($event)
 {
     $endDate = CTimeHelper::getLocaleDate($event->enddate);
     $now = CTimeHelper::getLocaleDate();
     $nowUnix = $now->toUnix();
     $isPast = $endDate->toUnix() < $nowUnix;
     return $isPast;
 }
Esempio n. 2
0
    /**
     * Get event child count
     *
     * @param int    $parent
     * @return int total
     *
     * */
    public function getEventChildsCount($parent)
    {
        $db = $this->getDBO();
        $pastDate = CTimeHelper::getLocaleDate();
        $query = 'SELECT COUNT(*)
			      FROM ' . $db->quoteName('#__community_events') . '
				  WHERE ' . $db->quoteName('parent') . '=' . $db->Quote($parent) . '
				  AND ' . $db->quoteName('enddate') . ' > ' . $db->Quote($pastDate->toSql(true)) . '
				  AND ' . $db->quoteName('published') . '=' . $db->Quote(1);
        $db->setQuery($query);
        if ($db->getErrorNum()) {
            JError::raiseError(500, $db->stderr());
        }
        return $db->loadResult();
    }
Esempio n. 3
0
 /**
  * Method to save the group
  * @return false if create fail, return the group id if create is successful
  **/
 public function save(&$event)
 {
     // Check for request forgeries
     JRequest::checkToken() or jexit(JText::_('COM_COMMUNITY_INVALID_TOKEN'));
     $mainframe = JFactory::getApplication();
     $document = JFactory::getDocument();
     $viewType = $document->getType();
     $viewName = JRequest::getCmd('view', $this->getName());
     $view = $this->getView($viewName, '', $viewType);
     if (JString::strtoupper(JRequest::getMethod()) != 'POST') {
         $view->addWarning(JText::_('COM_COMMUNITY_PERMISSION_DENIED_WARNING'));
         return false;
     }
     // Get my current data.
     $my = CFactory::getUser();
     $validated = true;
     $model = $this->getModel('events');
     $eventId = JRequest::getInt('eventid', '0');
     $isNew = $eventId == '0' ? true : false;
     $postData = JRequest::get('post');
     //format startdate and eendate with time before we bind into event object
     $this->_formatStartEndDate($postData);
     //		if( !empty($postData['coordinate']) )
     //		{
     //			$coord	= explode( ',', $postData['coordinate'] );
     //			$postData['latitude']	=   trim($coord[0]);
     //			$postData['longitude']	=   trim($coord[1]);
     //		}
     $event->load($eventId);
     $event->bind($postData);
     if (!array_key_exists('permission', $postData)) {
         $event->permission = 0;
     }
     if (!array_key_exists('allowinvite', $postData)) {
         $event->allowinvite = 0;
     } elseif (isset($postData['endtime-ampm']) && $postData['endtime-ampm'] == 'AM' && $postData['endtime-hour'] == 12) {
         $postData['endtime-hour'] = 00;
     }
     $inputFilter = CFactory::getInputFilter(true);
     // Despite the bind, we would still need to capture RAW description
     $event->description = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $event->description = $inputFilter->clean($event->description);
     // @rule: Test for emptyness
     if (empty($event->title)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TITLE_ERROR'), 'error');
     }
     if (empty($event->location)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_LOCATION_ERR0R'), 'error');
     }
     // @rule: Test if the event is exists
     if ($model->isEventExist($event->title, $event->location, $event->startdate, $event->enddate, $eventId)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TAKEN_ERROR'), 'error');
     }
     // @rule: Description cannot be empty
     /*if( empty( $event->description ) )
     		{
     			$validated = false;
     			$mainframe->enqueueMessage( JText::_('COM_COMMUNITY_EVENTS_TAKEN_ERROR'), 'error');
     		}*/
     // @rule: Start date cannot be empty
     if (empty($event->startdate)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_STARTDATE_ERROR'), 'error');
     }
     // @rule: End date cannot be empty
     if (empty($event->enddate)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_ENDDATE_ERROR'), 'error');
     }
     // @rule: Number of ticket must at least be 0
     if (Jstring::strlen($event->ticket) <= 0) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TICKET_EMPTY_ERROR'), 'error');
     }
     require_once JPATH_COMPONENT . DS . 'helpers' . DS . 'time.php';
     if (CTimeHelper::timeIntervalDifference($event->startdate, $event->enddate) > 0) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_STARTDATE_GREATER_ERROR'), 'error');
     }
     // @rule: Event must not end in the past
     $now = CTimeHelper::getLocaleDate();
     if (CTimeHelper::timeIntervalDifference($now->toMySQL(true), $event->enddate) > 0) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_ENDDATE_GREATER_ERROR'), 'error');
     }
     if ($validated) {
         // If show event timezone is disabled, we need to set the event offset to 0.
         $config = CFactory::getConfig();
         if (!$config->get('eventshowtimezone')) {
             $event->offset = 0;
         }
         // Set the default thumbnail and avatar for the event just in case
         // the user decides to skip this
         if ($isNew) {
             $event->creator = $my->id;
             $config = CFactory::getConfig();
             //@rule: If event moderation is enabled, event should be unpublished by default
             $event->published = $config->get('event_moderation') ? 0 : 1;
             $event->created = JFactory::getDate()->toMySQL();
         }
         $event->store();
         if ($isNew) {
             CFactory::load('helpers', 'event');
             $handler = CEventHelper::getHandler($event);
             $event->contentid = $handler->getContentId();
             $event->type = $handler->getType();
             // Since this is storing event, we also need to store the creator / admin
             // into the events members table
             $member = JTable::getInstance('EventMembers', 'CTable');
             $member->eventid = $event->id;
             $member->memberid = $event->creator;
             // Creator should always be 1 as approved as they are the creator.
             $member->status = COMMUNITY_EVENT_STATUS_ATTEND;
             // @todo: Setup required permissions in the future
             $member->permission = '1';
             $member->store();
             // Increment the member count
             $event->updateGuestStats();
             $event->store();
             CFactory::load('helpers', 'event');
             $handler = CEventHelper::getHandler($event);
             // Activity stream purpose if the event is a public event
             if ($handler->isPublic()) {
                 $actor = $my->id;
                 $target = 0;
                 $content = '';
                 $cid = $event->id;
                 $app = 'events';
                 $act = $handler->getActivity('events.create', $actor, $target, $content, $cid, $app);
                 $url = $handler->getFormattedLink('index.php?option=com_community&view=events&task=viewevent&eventid=' . $event->id, false, true, false);
                 // Set activity group id if the event is in group
                 $act->groupid = $event->type == 'group' ? $event->contentid : null;
                 $act->eventid = $event->id;
                 $act->location = $event->location;
                 $act->comment_id = $event->id;
                 $act->comment_type = 'events';
                 $act->like_id = $event->id;
                 $act->like_type = 'events';
                 $params = new CParameter('');
                 $action_str = 'events.create';
                 $cat_url = $handler->getFormattedLink('index.php?option=com_community&view=events&task=display&categoryid=' . $event->catid, false, true, false);
                 $params->set('action', $action_str);
                 $params->set('event_url', $url);
                 $params->set('event_category_url', $cat_url);
                 // Add activity logging
                 CFactory::load('libraries', 'activities');
                 CActivityStream::add($act, $params->toString());
             }
             //add user points
             CFactory::load('libraries', 'userpoints');
             CUserPoints::assignPoint($action_str);
             //add notification: New group event is added
             CFactory::load('helpers', 'event');
             if ($event->type == CEventHelper::GROUP_TYPE && $event->contentid != 0) {
                 CFactory::load('libraries', 'notification');
                 $group =& JTable::getInstance('Group', 'CTable');
                 $group->load($event->contentid);
                 $modelGroup =& $this->getModel('groups');
                 $groupMembers = array();
                 $groupMembers = $modelGroup->getMembersId($event->contentid, true);
                 $subject = JText::sprintf('COM_COMMUNITY_GROUP_NEW_EVENT_NOTIFICATION', $my->getDisplayName(), $group->name);
                 $params = new CParameter('');
                 $params->set('title', $event->title);
                 $params->set('group', $group->name);
                 $params->set('subject', $subject);
                 $params->set('url', 'index.php?option=com_community&view=events&task=viewevent&eventid=' . $event->id);
                 CNotificationLibrary::add('etype_groups_create_event', $my->id, $groupMembers, $subject, '', 'groups.event', $params);
             }
         }
         $validated = $event->id;
         $this->cacheClean(array(COMMUNITY_CACHE_TAG_FRONTPAGE, COMMUNITY_CACHE_TAG_EVENTS, COMMUNITY_CACHE_TAG_EVENTS_CAT, COMMUNITY_CACHE_TAG_ACTIVITIES));
     }
     return $validated;
 }
Esempio n. 4
0
 public function getActiveEvent()
 {
     $db = $this->getDBO();
     $CTimeHelper = new CTimeHelper();
     $pastDate = $CTimeHelper->getLocaleDate();
     $query = 'SELECT * FROM ' . $db->quoteName('#__community_events') . ' WHERE ' . $db->quoteName('published') . '=' . $db->Quote(1) . ' AND ' . $db->quoteName('enddate') . ' > ' . $db->Quote($pastDate->format('Y-m-d H:i:s', true, false));
     $db->setQuery($query);
     $result = $db->loadObjectList();
     return $result;
 }
Esempio n. 5
0
 /**
  * Method to save the group
  * @return false if create fail, return the group id if create is successful
  * */
 public function save($event, $isDuplicate = false)
 {
     // Check for request forgeries
     JSession::checkToken('post') or jexit(JText::_('COM_COMMUNITY_INVALID_TOKEN'));
     $mainframe = JFactory::getApplication();
     $jinput = $mainframe->input;
     $document = JFactory::getDocument();
     $viewType = $document->getType();
     $viewName = $jinput->get('view', $this->getName(), 'String');
     $view = $this->getView($viewName, '', $viewType);
     if (JString::strtoupper($jinput->getMethod()) != 'POST') {
         $view->addWarning(JText::_('COM_COMMUNITY_PERMISSION_DENIED_WARNING'));
         return false;
     }
     // Get my current data.
     $my = CFactory::getUser();
     $validated = true;
     $model = $this->getModel('events');
     $eventId = $jinput->get->get('eventid', 0, 'Int');
     $isNew = $eventId == 0 ? true : false;
     $postData = JRequest::get('post');
     $repeataction = $jinput->get('repeataction', null, 'NONE');
     $inviteAllMembers = $jinput->get('invitegroupmembers', 0, 'INT');
     if (!isset($postData['allday'])) {
         $postData['allday'] = 0;
     }
     //format startdate and eendate with time before we bind into event object
     $postData = $this->_formatStartEndDate($postData);
     $event->load($eventId);
     // record event original start and end date
     $postData['oldstartdate'] = $event->startdate;
     $postData['oldenddate'] = $event->enddate;
     $postData['unlisted'] = JRequest::getVar('unlisted', 0, 'post', 'int', JREQUEST_ALLOWRAW);
     if (CFactory::getConfig()->get('eventshowtimezone')) {
         $timezoneName = $postData['offset'];
         $postData['offset'] = CTimeHelper::getOffsetByTimezone($postData['offset']);
         //update offset before binding
     }
     $event->bind($postData);
     if (!array_key_exists('permission', $postData)) {
         $event->permission = 0;
     }
     if (!array_key_exists('allowinvite', $postData)) {
         $event->allowinvite = 0;
     } elseif (isset($postData['endtime-ampm']) && $postData['endtime-ampm'] == 'AM' && $postData['endtime-hour'] == 12) {
         $postData['endtime-hour'] = 00;
     }
     $inputFilter = CFactory::getInputFilter(true);
     // Despite the bind, we would still need to capture RAW description
     $event->description = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $event->description = $inputFilter->clean($event->description);
     // binding the params
     $params = new CParameter('');
     $photoPermissionAdmin = $jinput->get('photopermission-admin', 0, 'STRING');
     $photoPermissionMember = $jinput->get('photopermission-member', 0, 'STRING');
     $videoPermissionAdmin = $jinput->get('videopermission-admin', 0, 'STRING');
     $videoPermissionMember = $jinput->get('videopermission-member', 0, 'STRING');
     $eventRecentPhotos = $jinput->get('eventrecentphotos', 6, 'STRING');
     $eventRecentVideos = $jinput->get('eventrecentvideos', 6, 'STRING');
     $params->set('eventrecentphotos', $eventRecentPhotos);
     $params->set('eventrecentvideos', $eventRecentVideos);
     $params->set('timezone', $timezoneName);
     if ($photoPermissionAdmin) {
         $params->set('photopermission', EVENT_PHOTO_PERMISSION_ADMINS);
         if ($photoPermissionMember) {
             $params->set('photopermission', EVENT_PHOTO_PERMISSION_ALL);
         }
     } else {
         $params->set('photopermission', EVENT_PHOTO_PERMISSION_DISABLE);
     }
     if ($videoPermissionAdmin) {
         $params->set('videopermission', EVENT_VIDEO_PERMISSION_ADMINS);
         if ($videoPermissionMember) {
             $params->set('videopermission', EVENT_VIDEO_PERMISSION_ALL);
         }
     } else {
         $params->set('videopermission', EVENT_VIDEO_PERMISSION_DISABLE);
     }
     $event->params = $params->toString();
     // @rule: Test for emptyness
     if (empty($event->title)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TITLE_ERROR'), 'error');
     }
     if (empty($event->location)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_LOCATION_ERR0R'), 'error');
     }
     // @rule: Test if the event is exists
     if ($model->isEventExist($event->title, $event->location, $event->startdate, $event->enddate, $eventId, $event->parent)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TAKEN_ERROR'), 'error');
     }
     // @rule: Start date cannot be empty
     if (empty($event->startdate)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_STARTDATE_ERROR'), 'error');
     }
     // @rule: End date cannot be empty
     if (empty($event->enddate)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_ENDDATE_ERROR'), 'error');
     }
     // @rule: Number of ticket must at least be 0
     if (Jstring::strlen($event->ticket) <= 0) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TICKET_EMPTY_ERROR'), 'error');
     }
     if (!is_numeric($event->ticket)) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_TICKET_INVALID_ERROR'), 'error');
     }
     $now = CTimeHelper::getLocaleDate();
     require_once JPATH_COMPONENT . '/helpers/time.php';
     if (CTimeHelper::timeIntervalDifference($event->startdate, $event->enddate) > 0) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_STARTDATE_GREATER_ERROR'), 'error');
     }
     // if all day event.
     $isToday = false;
     if ($postData['allday'] == '1') {
         $isToday = date("Y-m-d", strtotime($event->enddate)) == date("Y-m-d", strtotime($now->toSql(true))) ? true : $isToday;
     }
     // @rule: Event must not end in the past
     if (CTimeHelper::timeIntervalDifference($now->toSql(true), $event->enddate) > 0 && !$isToday && $isNew) {
         $validated = false;
         $mainframe->enqueueMessage(JText::_('COM_COMMUNITY_EVENTS_ENDDATE_GREATER_ERROR'), 'error');
     }
     $eventChild = array();
     // check event recurrence limit.
     if (!empty($event->repeat) && ($isNew || $postData['repeataction'] == 'future')) {
         $repeatLimit = 'COMMUNITY_EVENT_RECURRING_LIMIT_' . strtoupper($event->repeat);
         if (defined($repeatLimit)) {
             $eventChild = $this->_generateRepeatList($event);
             if (count($eventChild) > constant($repeatLimit)) {
                 $validated = false;
                 $mainframe->enqueueMessage(sprintf(JText::_('COM_COMMUNITY_EVENTS_REPEAT_LIMIT_ERROR'), constant($repeatLimit)), 'error');
             }
         }
     }
     if ($validated) {
         // If show event timezone is disabled, we need to set the event offset to 0.
         $config = CFactory::getConfig();
         if (!$config->get('eventshowtimezone')) {
             $event->offset = 0;
         }
         if ($isDuplicate) {
             $event->id = 0;
             $isNew = 1;
         }
         // Set the default thumbnail and avatar for the event just in case
         // the user decides to skip this
         if ($isNew) {
             $event->creator = $my->id;
             $config = CFactory::getConfig();
             //@rule: If event moderation is enabled, event should be unpublished by default
             $event->published = $this->isPublished();
             $event->created = JFactory::getDate()->toSql();
             $handler = CEventHelper::getHandler($event);
             $event->contentid = $handler->getContentId();
             $event->type = $handler->getType();
         }
         $event->store();
         // Save event members
         if ($isNew && !$event->isRecurring()) {
             $this->_saveMember($event);
             // Increment the member count
             $event->updateGuestStats();
             $event->store();
         }
         if ($isNew) {
             $event->parent = !empty($event->repeat) ? $event->id : 0;
         }
         // Save recurring event's child.
         $this->_saveRepeatChild($event, $eventChild, $isNew, $postData);
         // Stream and notification
         if ($isNew) {
             // add activity stream
             $this->_addActivityStream($event);
             //add user points
             $action_str = 'events.create';
             CUserPoints::assignPoint($action_str);
             //add notification: New group event is added
             $this->_addGroupNotification($event);
         }
         $validated = $event->id;
         $this->cacheClean(array(COMMUNITY_CACHE_TAG_FRONTPAGE, COMMUNITY_CACHE_TAG_EVENTS, COMMUNITY_CACHE_TAG_EVENTS_CAT, COMMUNITY_CACHE_TAG_ACTIVITIES));
     }
     //if saved and we should invite all members of the group
     if ($inviteAllMembers && $event->id && $event->contentid) {
         $groupid = $event->contentid;
         $groupsModel = CFactory::getModel('groups');
         $members = $groupsModel->getMembers($groupid, 0, true, false, SHOW_GROUP_ADMIN);
         $membersArr = array();
         foreach ($members as $member) {
             if ($member->id == $my->id) {
                 continue;
             }
             $membersArr[] = $member->id;
         }
         $inviteMail = $this->inviteUsers($event->id, $membersArr, '', '');
         if ($inviteMail instanceof CInvitationMail) {
             // Once stored, we need to store selected user so they wont be invited again
             $callback = "events,inviteUsers";
             $invitation = JTable::getInstance('Invitation', 'CTable');
             $invitation->load($callback, $event->id);
             if ($membersArr) {
                 if (!$invitation->id) {
                     // If the record doesn't exists, we need add them into the
                     $invitation->cid = $event->id;
                     $invitation->callback = $callback;
                 }
                 $invitation->users = implode(',', $membersArr);
                 $invitation->store();
             }
             //start sending email and notification
             CNotificationLibrary::add($inviteMail->getCommand(), $my->id, $membersArr, $inviteMail->getTitle(), $inviteMail->getContent(), '', $inviteMail->getParams());
         }
     }
     return $validated;
 }
Esempio n. 6
0
 /**
  * Returns an object of events which the user has registered.
  *
  * @access	public
  * @param	string 	User's id.
  * @param	string 	sorting criteria.
  * @returns array  An objects of event fields.
  */
 public function getEvents($categoryId = null, $userId = null, $sorting = null, $search = null, $hideOldEvent = true, $showOnlyOldEvent = false, $pending = null, $advance = null, $type = CEventHelper::ALL_TYPES, $contentid = 0, $limit = null)
 {
     $db =& $this->getDBO();
     $join = '';
     $extraSQL = '';
     if (!empty($userId)) {
         $join = 'LEFT JOIN ' . $db->nameQuote('#__community_events_members') . ' AS b ON a.' . $db->nameQuote('id') . '=b.' . $db->nameQuote('eventid');
         $extraSQL .= ' AND b.' . $db->nameQuote('memberid') . '=' . $db->Quote($userId) . 'AND b.' . $db->nameQuote('status') . '<' . $db->Quote(2);
     }
     if (!empty($search)) {
         $extraSQL .= ' AND a.' . $db->nameQuote('title') . ' LIKE ' . $db->Quote('%' . $search . '%');
     }
     if (!empty($categoryId) && $categoryId != 0) {
         $extraSQL .= ' AND a.' . $db->nameQuote('catid') . '=' . $db->Quote($categoryId);
     }
     if (!is_null($pending) && !empty($userId)) {
         $extraSQL .= ' AND b.' . $db->nameQuote('status') . '=' . $db->Quote($pending);
     }
     /* Begin : ADVANCE SEARCH */
     if (!empty($advance)) {
         if (!empty($advance['startdate'])) {
             $startDate = CTimeHelper::getDate(strtotime($advance['startdate']));
             $extraSQL .= ' AND a.' . $db->nameQuote('startdate') . ' >= ' . $db->Quote($startDate->toMySQL());
         } else {
             if (!isset($advance['date'])) {
                 $now = CTimeHelper::getDate();
                 $extraSQL .= ' AND a.' . $db->nameQuote('enddate') . ' >= ' . $db->Quote($now->toMySQL());
             }
         }
         if (!empty($advance['date'])) {
             // to get event within this date
             $between_date = date('Ymd', strtotime($advance['date']));
             $extraSQL .= ' AND DATE_FORMAT(a.' . $db->nameQuote('startdate') . ',"%Y%m%d") <= ' . $db->Quote($between_date) . ' AND DATE_FORMAT(a.' . $db->nameQuote('enddate') . ',"%Y%m%d") >= ' . $db->Quote($between_date);
             $hideOldEvent = false;
             //show old event as well
         }
         if (!empty($advance['enddate'])) {
             $endDate = CTimeHelper::getDate(strtotime($advance['enddate']));
             $extraSQL .= ' AND a.' . $db->nameQuote('startdate') . ' <= ' . $db->Quote($endDate->toMySQL());
         }
         /* Begin : SEARCH WITHIN */
         if (!empty($advance['radius']) && !empty($advance['fromlocation'])) {
             $longitude = null;
             $latitude = null;
             CFactory::load('libraries', 'mapping');
             $data = CMapping::getAddressData($advance['fromlocation']);
             if ($data) {
                 if ($data->status == 'OK') {
                     $latitude = (double) $data->results[0]->geometry->location->lat;
                     $longitude = (double) $data->results[0]->geometry->location->lng;
                 }
             }
             $now = new JDate();
             $lng_min = $longitude - $advance['radius'] / abs(cos(deg2rad($latitude)) * 69);
             $lng_max = $longitude + $advance['radius'] / abs(cos(deg2rad($latitude)) * 69);
             $lat_min = $latitude - $advance['radius'] / 69;
             $lat_max = $latitude + $advance['radius'] / 69;
             $extraSQL .= ' AND a.' . $db->nameQuote('longitude') . ' > ' . $db->quote($lng_min) . ' AND a.' . $db->nameQuote('longitude') . ' < ' . $db->quote($lng_max) . ' AND a.' . $db->nameQuote('latitude') . ' > ' . $db->quote($lat_min) . ' AND a.' . $db->nameQuote('latitude') . ' < ' . $db->quote($lat_max);
         }
         /* End : SEARCH WITHIN */
     }
     /* End : ADVANCE SEARCH */
     $limitstart = $this->getState('limitstart');
     $limit = $limit === null ? $this->getState('limit') : $limit;
     if ($type != CEventHelper::ALL_TYPES) {
         $extraSQL .= ' AND a.' . $db->nameQuote('type') . '=' . $db->Quote($type);
         $extraSQL .= ' AND a.' . $db->nameQuote('contentid') . '=' . $contentid;
     }
     if ($type == CEventHelper::GROUP_TYPE || $type == CEventHelper::ALL_TYPES) {
         // @rule: Respect group privacy
         $join .= ' LEFT JOIN ' . $db->nameQuote('#__community_groups') . ' AS g';
         $join .= ' ON g.' . $db->nameQuote('id') . ' = a.' . $db->nameQuote('contentid');
         if ($type != CEventHelper::GROUP_TYPE) {
             $extraSQL .= ' AND (g.' . $db->nameQuote('approvals') . ' = ' . $db->Quote('0') . ' OR g.' . $db->nameQuote('approvals') . ' IS NULL';
             if (!empty($userId)) {
                 $extraSQL .= ' OR b.' . $db->nameQuote('memberid') . '=' . $db->Quote($userId);
             }
             $extraSQL .= ')';
         }
     }
     $orderBy = '';
     $total = 0;
     switch ($sorting) {
         case 'latest':
             if (empty($orderBy)) {
                 $orderBy = ' ORDER BY a.' . $db->nameQuote('created') . ' DESC';
             }
             break;
         case 'alphabetical':
             if (empty($orderBy)) {
                 $orderBy = ' ORDER BY a.' . $db->nameQuote('title') . ' ASC';
             }
             break;
         case 'startdate':
             if (empty($orderBy)) {
                 $orderBy = ' ORDER BY a.startdate ASC';
             }
             break;
         default:
             $orderBy = ' ORDER BY a.' . $db->nameQuote('startdate') . ' ASC';
             break;
     }
     $now = new JDate();
     CFactory::load('helpers', 'time');
     $pastDate = CTimeHelper::getLocaleDate();
     if ($hideOldEvent) {
         $extraSQL .= ' AND a.' . $db->nameQuote('enddate') . ' > ' . $db->Quote($pastDate->toMySQL(true));
     }
     if ($showOnlyOldEvent) {
         $extraSQL .= ' AND a.' . $db->nameQuote('enddate') . ' < ' . $db->Quote($pastDate->toMySQL(true));
     }
     $limit = empty($limit) ? 0 : $limit;
     $query = 'SELECT DISTINCT a.* FROM ' . $db->nameQuote('#__community_events') . ' AS a ' . $join . 'WHERE a.' . $db->nameQuote('published') . '=' . $db->Quote('1') . $extraSQL . $orderBy . ' LIMIT ' . $limitstart . ', ' . $limit;
     $db->setQuery($query);
     $result = $db->loadObjectList();
     if ($db->getErrorNum()) {
         JError::raiseError(500, $db->stderr());
     }
     $query = 'SELECT COUNT(DISTINCT(a.`id`)) FROM ' . $db->nameQuote('#__community_events') . ' AS a ' . $join . 'WHERE a.' . $db->nameQuote('published') . '=' . $db->Quote('1') . $extraSQL;
     $db->setQuery($query);
     $this->total = $db->loadResult();
     if ($db->getErrorNum()) {
         JError::raiseError(500, $db->stderr());
     }
     $query = 'SELECT COUNT(DISTINCT(a.' . $db->nameQuote('id') . ')) FROM ' . $db->nameQuote('#__community_events') . ' AS a ' . $join . 'WHERE a.' . $db->nameQuote('published') . '=' . $db->Quote('1') . ' ' . $extraSQL;
     $db->setQuery($query);
     $total = $db->loadResult();
     if ($db->getErrorNum()) {
         JError::raiseError(500, $db->stderr());
     }
     if (empty($this->_pagination)) {
         jimport('joomla.html.pagination');
         $this->_pagination = new JPagination($total, $limitstart, $limit);
     }
     return $result;
 }