/**
  * Changes the leader being managed.
  * This does not reset the form.
  * @param int $leaderid
  */
 public function setLeader($leaderOrID)
 {
     if ($leaderOrID instanceof Leader) {
         $this->leader = $leaderOrID;
     } else {
         if (is_numeric($leaderOrID)) {
             $this->leader = Leader::getLeader($leaderOrID);
         }
     }
 }
 public function search()
 {
     // This is a Safe Form - there is no effect to searching and it's safe to share URLS.
     // Therefore, there is no need to check tokens or use POST
     $data = JRequest::getVar('jform', array(), 'get', 'array');
     $search = new WalkSearcher();
     // Go through each field on the form and, if it's set, convert its value to that expected by the searcher and apply it
     if (isset($data['keywords'])) {
         // TODO: Allow searching by leaders' information if logged in?
         $search->setPublicText($data['keywords']);
     }
     // Need to get each grade separately, then build the array.
     // If no grades are set, allow all.
     $possibleGrades = array("A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3");
     $selectedGrades = array();
     foreach ($possibleGrades as $grade) {
         if (!empty($data['grade' . $grade])) {
             $selectedGrades[] = $grade;
         }
     }
     if (!empty($selectedGrades)) {
         $search->setGrade($selectedGrades);
     }
     // Areas
     if (!empty($data['location'])) {
         $search->setLocation(array((int) $data['location']));
     }
     // Transport
     if (isset($data['transportPublic'])) {
         $search->setTransportPublic((bool) $data['transportPublic']);
     }
     if (isset($data['transportCar'])) {
         $search->setTransportByCar((bool) $data['transportCar']);
     }
     // TODO: Leader - currently this searches who suggested it, not anyone else who's led it
     if (!empty($data['leader'])) {
         $search->setSuggestedBy(Leader::getLeader($data['leader']));
     }
     $this->getModel()->setWalkList($search->search());
     $this->display();
     return true;
 }
 public function fromDatabase(array $dbArr)
 {
     $this->id = $dbArr['ID'];
     parent::fromDatabase($dbArr);
     $this->suggestedBy = Leader::getLeader($dbArr['suggestedby']);
     // Also set the lat/lng
     if (!empty($this->startGridRef)) {
         $startOSRef = getOSRefFromSixFigureReference($this->startGridRef);
         $startLatLng = $startOSRef->toLatLng();
         $startLatLng->OSGB36ToWGS84();
         $this->startLatLng = $startLatLng;
     }
     if (!empty($this->endGridRef)) {
         $endOSRef = getOSRefFromSixFigureReference($this->endGridRef);
         $endLatLng = $endOSRef->toLatLng();
         $endLatLng->OSGB36ToWGS84();
         $this->endLatLng = $endLatLng;
     }
     // TODO: Load route?
 }
 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;
         }
     }
 }
 /**
  * Update the current walk with passed in form data
  * This also handles GPX data
  */
 public function updateWalk(array $formData)
 {
     $this->loadWalk($formData['id']);
     // Update all basic fields
     // Fields that can't be saved are just ignored
     // Invalid fields throw an exception - display this to the user and continue
     foreach ($formData as $name => $value) {
         try {
             if ($name == "suggestedBy") {
                 $this->walk->suggestedBy = Leader::getLeader($value);
             } else {
                 $this->walk->{$name} = $value;
             }
         } catch (UnexpectedValueException $e) {
             echo "<p>";
             var_dump($name);
             var_dump($value);
             var_dump($e->getMessage());
             echo "</p>";
         }
     }
     // Handle the route file upload
     $file = JRequest::getVar('jform', array(), 'files', 'array');
     if (!empty($file) && $file['error']['route'] == UPLOAD_ERR_OK) {
         // We've been given a GPX file. Try to parse it.
         $gpx = DOMDocument::load($file['tmp_name']['route']);
         if ($gpx) {
             // Check for a GPX element at the root
             if ($gpx->getElementsByTagName("gpx")->length == 1) {
                 // Get the route ID if we have an existing route
                 if (isset($this->walk->route)) {
                     $routeID = $this->walk->route->id;
                 } else {
                     $routeID = null;
                 }
                 // TODO: Turn on or off overwriting of existing properties
                 if (isset($this->walk->route)) {
                     $route = $this->walk->route;
                 } else {
                     $route = new Route($this->walk);
                 }
                 $route->readGPX($gpx);
                 $route->uploadedBy = JFactory::getUser()->id;
                 $route->uploadedDateTime = time();
                 $this->walk->setRoute($route, true);
                 // Store this route for later requests
                 JFactory::getApplication()->setUserState("uploadedroute", serialize($route));
                 JFactory::getApplication()->setUserState("deleteroute", false);
             } else {
                 echo "Must have only one GPX tag";
             }
         } else {
             echo "Not a GPX file";
         }
         // Return to the form
     } else {
         // Restore previously uploaded file from state
         $route = unserialize(JFactory::getApplication()->getUserState("uploadedroute"));
         if ($route) {
             $route->setWalk($this->walk);
             $this->walk->setRoute($route);
         }
     }
     // If we have a route, allow the user to set options on it
     if (isset($this->walk->route)) {
         $this->walk->route->visibility = $formData['routeVisibility'];
     }
 }
 public function __get($name)
 {
     // Load connected objects from the database as needed
     switch ($name) {
         case "meetPoint":
             $this->meetPoint = new WalkMeetingPoint($this->meetPointId, $this->start, $this->meetPlaceTime);
             break;
         case "leader":
             $this->leader = Leader::getLeader($this->leaderId);
             if (!empty($this->leaderName)) {
                 $this->leader->setDisplayName($this->leaderName);
             }
             break;
         case "backmarker":
             $this->backmarker = Leader::getLeader($this->backmarkerId);
             if (!empty($this->backmarkerName)) {
                 $this->backmarker->setDisplayName($this->backmarkerName);
             }
             break;
         case "walk":
             return Walk::getSingle($this->walkid);
         case "track":
             // Load the track if we don't have it already
             // TODO: Only try once, and catch exceptions
             if (!isset($this->track)) {
                 $this->loadTrack();
             }
             return $this->track;
         case "distance":
             // If we don't have a (real) distance set, convert the (estimated) miles into metres and give that
             break;
             // If the walk is circular, return the equivalent start point
         // If the walk is circular, return the equivalent start point
         case "endPlaceName":
         case "endLatLng":
         case "endGridRef":
             if ($this->isLinear) {
                 return $this->{$name};
             } else {
                 $var = "start" . substr($name, 3);
                 return $this->{$var};
             }
     }
     return $this->{$name};
     // TODO: What params should be exposed?
 }