function display($tpl = null)
 {
     // Assign data to the view
     $this->walks = $this->get('Walks');
     $this->controller = JControllerLegacy::getInstance('SWG_WalkLibrary');
     // Check for errors.
     if (count($errors = $this->get('Errors'))) {
         JError::raiseError(500, implode('<br />', $errors));
         return false;
     }
     // Set the template & title
     switch (JRequest::getInt("initialView")) {
         case 0:
             $this->pageTitle = "List walks";
             $this->showList = true;
             $this->showSearch = false;
             $this->noWalkMsg = "No walks found";
             break;
         case 1:
             // Get this leader's record
             // TODO: Integrate with Joomla users
             $leader = Leader::fromJoomlaUser(JFactory::getUser()->id);
             if ($leader == null) {
                 $this->pageTitle = "Walks you've suggested";
                 $this->showList = true;
                 $this->showSearch = false;
                 $this->noWalkMsg = "Your leader account hasn't been set up properly. Please contact the vice chair or webmaster.";
             } else {
                 $this->pageTitle = "Walks suggested by " . $leader->displayName;
                 $this->showList = true;
                 $this->showSearch = false;
                 $this->noWalkMsg = "You haven't suggested any walks yet";
             }
             break;
         case 2:
             $this->pageTitle = "Suggested walks";
             $this->showList = true;
             $this->showSearch = false;
             $this->noWalkMsg = "No walks have been suggested";
             break;
         case 3:
         default:
             $this->pageTitle = "Walks library";
             $this->noWalkMsg = "No walks found";
             if ($this->getModel()->hasWalkList()) {
                 $this->showList = true;
                 $this->showSearch = false;
             } else {
                 $this->showList = false;
                 $this->showSearch = true;
             }
             break;
     }
     // Set page heading.
     // TODO: Fix hack?
     JFactory::getApplication()->getMenu()->getActive()->params->set("page_heading", $this->pageTitle);
     // Display the view
     parent::display($tpl);
 }
 public function submit()
 {
     // Check for request forgeries.
     JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
     // Initialise variables.
     $app = JFactory::getApplication();
     $model = $this->getModel('addeditwalk');
     $view = $this->getView('addeditwalk', 'html');
     $view->setModel($model, true);
     // Get the data from the form POST
     $data = JRequest::getVar('jform', array(), 'post', 'array');
     // Send the data to the model
     $model->updateWalk($data);
     // If this is a new walk, set the suggester to the current user
     if (!isset($model->getWalk()->id)) {
         $model->getWalk()->suggestedBy = Leader::fromJoomlaUser(JFactory::getUser()->id);
     }
     // Did we save the walk, or just upload a GPX file?
     if (JRequest::getVar('upload', false, 'post')) {
         $view->display();
     } else {
         if (JRequest::getVar('clearroute', false, 'post')) {
             // Remember that we've cleared the route, so we can delete it from the database when we save
             JFactory::getApplication()->setUserState("deleteroute", $model->getWalk()->route->id);
             JFactory::getApplication()->setUserState("uploadedroute", null);
             $model->clearRoute();
             $view->display();
         } else {
             $model->getWalk()->save();
             // Delete the route if necessary
             $deleteRoute = JFactory::getApplication()->getUserState("deleteroute", false);
             if ($deleteRoute) {
                 $db =& JFactory::getDBO();
                 $query = $db->getQuery(true);
                 $query->delete("routes");
                 $query->where("routeid = " . (int) $deleteRoute);
                 $db->setQuery($query);
                 $db->query();
             }
             // Redirect to the walk details page
             $url = $_SERVER['REQUEST_URI'];
             // Get the current URL parameters
             if (strpos($url, "?") !== false) {
                 $inParams = explode("&", substr($url, strpos($url, "?") + 1));
                 $urlBase = substr($url, 0, strpos($url, "?"));
             } else {
                 $inParams = array();
                 $urlBase = $url;
             }
             // Build the new URL parameters
             $params = array("view=walkdetails", "walkid=" . $model->getWalk()->id);
             if (isset($inParams['option'])) {
                 $params['option'] = $inParams['option'];
             }
             JFactory::getApplication()->redirect($urlBase . "?" . implode("&", $params));
             return true;
         }
     }
 }
 public function getWalks()
 {
     // If we have a custom walk list, return that
     if (isset($this->walkList)) {
         return $this->walkList;
     }
     // Otherwise, get the default data
     switch (JRequest::getInt("initialView")) {
         case 0:
         default:
             return array();
         case 1:
             // Get this leader's record
             $leader = Leader::fromJoomlaUser(JFactory::getUser()->id);
             if (!empty($leader)) {
                 return Walk::getWalksBySuggester($leader);
             } else {
                 return array();
             }
     }
 }
 function canEdit($walkOrID)
 {
     if (JFactory::getUser()->authorise("walk.editall", "com_swg_walklibrary")) {
         return true;
     } else {
         if (!JFactory::getUser()->authorise("walk.editown", "com_swg_walklibrary")) {
             return false;
         } else {
             if (is_numeric($walkOrID)) {
                 $walk = Walk::getSingle($walkOrID);
             } else {
                 if ($walkOrID instanceof Walk) {
                     $walk = $walkOrID;
                 }
             }
             if (empty($walk)) {
                 throw new InvalidArgumentException("Invalid walk or ID");
             }
             return $walk->suggestedBy == Leader::fromJoomlaUser(JFactory::getUser()->id);
         }
     }
 }
 function onUserAfterSave($data, $isNew, $result, $error)
 {
     $userId = JArrayHelper::getValue($data, 'id', null, 'int');
     $oldLeader = Leader::fromJoomlaUser($userId);
     $leaderChanged = false;
     if ($oldLeader == null && !empty($data['swg_extras']['leadersetup'])) {
         // Create a new leader account
         $leader = new Leader();
         $leader->username = $data['username'];
         $leader->password = "******";
         // TODO: This is temporary
         $leader->surname = substr($data['name'], strrpos($data['name'], " ") + 1);
         $leader->forename = substr($data['name'], 0, strrpos($data['name'], " "));
         $leader->email = $data['email'];
         $leader->active = true;
         $leader->joomlaUserID = $userId;
         $leader->save();
         $leaderChanged = true;
     } else {
         if (!empty($data['swg_extras']['leaderid']) && $data['swg_extras']['leaderid'] != $oldLeader->id) {
             if ($oldLeader != null) {
                 // Disconnect from old leader
                 $oldLeader->joomlaUserID = null;
                 $oldLeader->save();
             }
             // Connect to new leader
             $leader = Leader::getLeader($data['swg_extras']['leaderid']);
             $leader->joomlaUserID = $userId;
             $leader->save();
             $leaderChanged = true;
         }
     }
     $db = JFactory::getDbo();
     if ($leaderChanged) {
         // Remove any existing links to this user
         $db->setQuery("UPDATE walkleaders SET joomlauser = null WHERE joomlauser = '******'");
         $db->query();
         // TODO: Check for success
         // Create the new link
         $db->setQuery("UPDATE walkleaders SET joomlauser = '******' WHERE ID = '{$data['swg_extras']['leaderid']}'");
         $db->query();
     } else {
         $leader = Leader::fromJoomlaUser($userId);
     }
     if (isset($leader)) {
         // Save details to the Leader
         if (!empty($data['swg_extras']['programmename'])) {
             $leader->setDisplayName($data['swg_extras']['programmename']);
         }
         if (!empty($data['swg_extras']['telephone'])) {
             $leader->telephone = $data['swg_extras']['telephone'];
         }
         $leader->noContactOfficeHours = !empty($data['swg_extras']['nocontactofficehours']) ? true : false;
         $leader->publishInOtherSites = !empty($data['swg_extras']['publishinothersites']) ? true : false;
         $leader->dogFriendly = !empty($data['swg_extras']['dogfriendly']) ? true : false;
         $leader->notes = $data['swg_extras']['notes'];
         $leader->save();
         // Don't save this data to the profile info
         $ex &= $data['swg_extras'];
         //unset($ex['programmename'], $ex['telephone'], $ex['nocontactofficehours'], $ex['publishinothersites'], $ex['dogfriendly'], $ex['notes']);
     }
     if ($userId && $result && isset($data['swg_extras']) && count($data['swg_extras'])) {
         try {
             // Sanitize the date
             if (!empty($data['swg_extras']['joindate'])) {
                 $date = new JDate($data['swg_extras']['joindate']);
                 $data['swg_extras']['joindate'] = $date->format('Y-m-d');
             }
             $db = JFactory::getDbo();
             $db->setQuery('DELETE FROM #__user_profiles WHERE user_id = ' . $userId . " AND profile_key LIKE 'swg_extras.%'");
             if (!$db->query()) {
                 throw new Exception($db->getErrorMsg());
             }
             $tuples = array();
             $order = 1;
             foreach ($data['swg_extras'] as $k => $v) {
                 $tuples[] = '(' . $userId . ', ' . $db->quote('swg_extras.' . $k) . ', ' . $db->quote($v) . ', ' . $order++ . ')';
             }
             // Joomla won't give us access to the FB token via the form field, so set that from the session
             /*$fb = new Facebook(SWG::$fbconf);
             		if ($fb->getUser())
             		{
             			$tuples[] = '('.$userId.', '.$db->quote('swg_extras.fbtoken').', '.$db->quote($fb->getAccessToken()).', '.$order++.')';
             		}*/
             $db->setQuery('INSERT INTO #__user_profiles VALUES ' . implode(', ', $tuples));
             if (!$db->query()) {
                 throw new Exception($db->getErrorMsg());
             }
         } catch (JException $e) {
             $this->_subject->setError($e->getMessage());
             return false;
         }
     }
 }
 /**
  * Outputs arrays of user stats
  * @param JUser $user 			User to get stats for. Default is current user.
  * @param int 	$distanceUnits	Convert distance units to this unit. Includes unit suffix, abbreviated - intended for display
  */
 static function getStats($user = null, $distanceUnits = null)
 {
     // Get attended walks
     if (!isset($user)) {
         $user = JFactory::getUser();
     }
     $wiFact = SWG::WalkInstanceFactory();
     $wiFact->reset();
     $wiFact->endDate = Event::DateEnd;
     $wiFact->addAttendee($user->id);
     $soFact = SWG::SocialFactory();
     $soFact->reset();
     $soFact->endDate = Event::DateEnd;
     $soFact->addAttendee($user->id);
     $weFact = SWG::WeekendFactory();
     $weFact->reset();
     $weFact->endDate = Event::DateEnd;
     $weFact->addAttendee($user->id);
     // TODO: Put into loops
     $startDates = array('alltime' => 0, 'year' => 365, '3month' => 90, 'month' => 30);
     foreach ($startDates as $period => $days) {
         if (empty($days)) {
             $start = 0;
         } else {
             $start = time() - $days * 86400;
         }
         $wiFact->startDate = $start;
         $weFact->startDate = $start;
         $soFact->startDate = $start;
         $walkData = $wiFact->cumulativeStats();
         $socials[$period] = $soFact->cumulativeStats();
         $weekend[$period] = $weFact->cumulativeStats();
         // Stats for all-day walks (walks starting at or before 14:00)
         $wiFact->startTimeMax = 14 * 3600;
         $dayWalkData = $wiFact->cumulativeStats();
         $wiFact->startTimeMax = null;
         // TODO: Check this doesn't fail for non-leaders: should say "0"
         $wiFact->leader = Leader::fromJoomlaUser($user->id);
         if (!empty($wiFact->leader)) {
             $ledData = $wiFact->cumulativeStats();
         } else {
             $ledData = array("count" => 0, "sum_miles" => 0);
         }
         // Convert walk units if needed
         if (isset($distanceUnits)) {
             $walkData['sum_miles'] = UnitConvert::displayDistance($walkData['sum_miles'], UnitConvert::Mile, $distanceUnits, false);
             $walkData['mean_miles'] = UnitConvert::displayDistance($walkData['mean_miles'], UnitConvert::Mile, $distanceUnits, false);
             $walkData['sum_distance'] = UnitConvert::displayDistance($walkData['sum_distance'], UnitConvert::Metre, $distanceUnits, false);
             $walkData['mean_distance'] = UnitConvert::displayDistance($walkData['mean_distance'], UnitConvert::Metre, $distanceUnits, false);
             $dayWalkData['sum_miles'] = UnitConvert::displayDistance($dayWalkData['sum_miles'], UnitConvert::Mile, $distanceUnits, false);
             $dayWalkData['mean_miles'] = UnitConvert::displayDistance($dayWalkData['mean_miles'], UnitConvert::Mile, $distanceUnits, false);
             $dayWalkData['sum_distance'] = UnitConvert::displayDistance($dayWalkData['sum_distance'], UnitConvert::Metre, $distanceUnits, false);
             $dayWalkData['mean_distance'] = UnitConvert::displayDistance($dayWalkData['mean_distance'], UnitConvert::Metre, $distanceUnits, false);
             if (!empty($wiFact->leader)) {
                 $ledData['sum_miles'] = UnitConvert::displayDistance($ledData['sum_miles'], UnitConvert::Mile, $distanceUnits, false);
                 $ledData['mean_miles'] = UnitConvert::displayDistance($ledData['mean_miles'], UnitConvert::Mile, $distanceUnits, false);
                 $ledData['sum_distance'] = UnitConvert::displayDistance($ledData['sum_distance'], UnitConvert::Metre, $distanceUnits, false);
                 $ledData['mean_distance'] = UnitConvert::displayDistance($ledData['mean_distance'], UnitConvert::Metre, $distanceUnits, false);
             }
         }
         $walks[$period] = $walkData;
         $dayWalks[$period] = $dayWalkData;
         $led[$period] = $ledData;
         $wiFact->leader = null;
         // Note: this is AFTER the conversions, we check if the leader is set in there
     }
     return array('walks' => $walks, 'daywalks' => $dayWalks, 'led' => $led, 'socials' => $socials, 'weekends' => $weekend);
 }
 public function __construct()
 {
     $this->setProgramme(WalkProgramme::getNextProgrammeId());
     $this->setLeader(Leader::fromJoomlaUser(JFactory::getUser()->id));
     parent::__construct();
 }