/** * Authenticate user and initializes the session. * Listens to Login.initSession hook. * * @param Core_Event_Notification $notification */ function initSession($notification) { $info = $notification->getNotificationObject(); $login = $info['login']; $password = $info['password']; $rememberMe = $info['rememberMe']; $tokenAuth = Module_UserManagement_API::getInstance()->getTokenAuth($login, $password); $auth = Zend_Registry::get('auth'); $auth->setLogin($login); $auth->setTokenAuth($tokenAuth); $authResult = $auth->authenticate(); $authCookieName = Zend_Registry::get('config')->General->login_cookie_name; $authCookieExpiry = $rememberMe ? time() + Zend_Registry::get('config')->General->login_cookie_expire : 0; $authCookiePath = Zend_Registry::get('config')->General->login_cookie_path; $cookie = new Core_Cookie($authCookieName, $authCookieExpiry, $authCookiePath); if (!$authResult->isValid()) { $cookie->delete(); throw new Exception('Login_LoginPasswordNotCorrect'); } $cookie->set('login', $login); $cookie->set('token_auth', $auth->getHashTokenAuth($login, $authResult->getTokenAuth())); $cookie->setSecure(Core_Common::isHttps()); $cookie->setHttpOnly(true); $cookie->save(); Zend_Session::regenerateId(); }
/** * Returns the singleton ModuleUserManagementAPI. * * @return ModuleUserManagementAPI */ public static function getInstance() { if (self::$_instance == null) { $c = __CLASS__; self::$_instance = new $c(); } return self::$_instance; }
function init() { $bikes = Module_UserManagement_API::getInstance()->getBikes(); $wind_directions = Module_Sessions_API::getInstance()->getWindDirections(); $bike = $this->addElement('select', 'bike', array()); $bike->setLabel('Bike'); $bike->loadOptions($bikes); $wind_direction = $this->addElement('select', 'wind_direction'); $wind_direction->setLabel('Wind Direction'); $wind_direction->loadOptions($wind_directions); $wind_speed = $this->addElement('text', 'wind_speed'); $wind_speed->setLabel('Wind Speed'); $file = $this->addElement('file', 'upload', array('required' => 'required')); $file->setLabel('Session File'); $file->addRule('required', 'The upload file is required'); $this->addElement('submit', 'submit'); }
/** * Authenticates user * * @return Core_Auth_Result */ public function authenticate() { $rootLogin = Zend_Registry::get('config')->superuser->login; $rootPassword = Zend_Registry::get('config')->superuser->password; $rootToken = Module_UserManagement_API::getInstance()->getTokenAuth($rootLogin, $rootPassword); if (is_null($this->login)) { $db = Zend_Registry::get('db'); if ($this->token_auth === $rootToken) { return new Core_Auth_Result(Core_Auth_Result::SUCCESS_SUPERUSER_AUTH_CODE, $rootLogin, $this->token_auth); } $select = $db->select()->from('t_users', array('userid'))->where('token = ?', $token_auth); $stmt = $db->query($select); $login_details = $stmt->fetch(); $login - $login_details['userid']; if (!empty($login)) { return new Core_Auth_Result(Core_Auth_Result::SUCCESS, $login, $this->token_auth); } } else { if (!empty($this->login)) { $db = Zend_Registry::get('db'); if ($this->login === $rootLogin && $this->getHashTokenAuth($rootLogin, $rootToken) === $this->token_auth || $rootToken === $this->token_auth) { $this->setTokenAuth($rootToken); return new Core_Auth_Result(Core_Auth_Result::SUCCESS_SUPERUSER_AUTH_CODE, $rootLogin, $this->token_auth); } $login = $this->login; $select = $db->select()->from('t_users', array('token'))->where('userid = ?', $login); $stmt = $db->query($select); $user_details = $stmt->fetch(); $userToken = $user_details['token']; if (!empty($userToken) && ($this->getHashTokenAuth($login, $userToken) === $this->token_auth || $userToken === $this->token_auth)) { $this->setTokenAuth($userToken); return new Core_Auth_Result(Core_Auth_Result::SUCCESS, $login, $userToken); } } } return new Core_Auth_Result(Core_Auth_Result::FAILURE, $this->login, $this->token_auth); }
/** * Get current user email address * * @return string */ public static function getCurrentUserEmail() { if (!Core_Common::isUserIsSuperUser()) { $user = Module_UserManagement_API::getInstance()->getUser(Core_Common::getCurrentUserLogin()); return $user['email']; } $superuser = Zend_Registry::get('config')->superuser; return $superuser->email; }
/** * View the parts on a bike. * * @return The Webpage Text */ function viewBike() { $api = new Module_UserManagement_API(); $bike_id = Core_Common::getRequestVar('id', null, 'int'); $view = Core_View::factory('viewBike'); $view->bikes = $api->getBikes(); $view->parts = $api->getBikeData($bike_id); echo $view->render(); }
function viewUpload() { $form = new SessionUploadForm(); $view = Core_View::factory('sessionsfileupload'); $view->UploadStatusMsg = ""; $view->UploadStatus = "Error"; if ($form->validate()) { $timer = new Benchmark_Timer(); $timer->start(); $upload = $form->getSubmitValue('upload'); $timer->setMarker('Decode Sessions - Start'); exec('/usr/local/bin/fitdecode -s ' . $upload['tmp_name'], $xml_session); $xml_session = implode("\n", $xml_session); $sessions = parseSessions($xml_session); $timer->setMarker('Decode Sessions - End'); /* There should only be one session */ if (is_array($sessions)) { $session = $sessions[0]; unset($sessions); } $db = Zend_Registry::get('db'); $db->beginTransaction(); try { $api = new Module_Sessions_API(); /* Insert the session data into the database */ $api->createSessionFull($session->start_time, 'E1', 'Untitled', $session->total_timer_time, $session->total_distance, $session->total_calories, $session->avg_heart_rate, $session->max_heart_rate, $session->avg_speed, $session->max_speed, $session->total_ascent, $session->total_descent, ''); /* Find the seconds since epoch so we can do simple maths */ $ftime = strptime($session->start_time, '%FT%T%z'); $session_epoch = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1, $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900); $session_timestamp = $session->start_time; unset($session); unset($sessions); $timer->setMarker('Decode Records - Start'); exec('/usr/local/bin/fitdecode -r ' . $upload['tmp_name'], $xml_records); $xml_records = implode("\n", $xml_records); $records_input = parseRecords($xml_records, $session_epoch); $timer->setMarker('Decode Records - End'); if (is_array($records_input)) { $record_prev = $records_input[0]; } /* Get the array of records, removing duplicates */ $records = array(); foreach ($records_input as $record) { if (!isset($record_last) || $record_last->interval != $record->interval) { $records[] = $record; } $record_last = $record; } unset($records_input); unset($record_last); $UserAPI = Module_UserManagement_API::getInstance(); $user = $UserAPI->getUser(); /* Add the matching data points */ foreach ($records as $record) { /* Skip duplicates, they will cause issues in graphs */ if (!isset($record->power)) { $record->power = $api->getPower($record->gradient, $record->temperature, $record->altitude, $record->speed, $record->speed - $record_prev->speed, $record->interval - $record_prev->interval, $user['rider_weight'], $user['bike_weight']); } $record_prev = $record; } unset($user); unset($UserAPI); $timer->setMarker('Record insertion - start'); $api->insertAllSessionData($session_timestamp, $records); /* Insert all the data */ $timer->setMarker('Record insertion - end'); /* Calculate the climbs */ $climbs = $api->getClimbCategories(); $timer->setMarker('Climb - Start'); $min_climb = $climbs[0]; /* 500m with an average gradient of more than 3% (cat 5)*/ /* Find the points that have a distance of 500m */ $window_distance = 0; $window_altitude = 0; $cat = -1; $climb_num = 1; $num_records = count($records); $num_climbs = count($climbs); for ($front = 0, $back = 0; $front < $num_records; $front++) { $window_distance += $records[$front]->delta_distance * 1000; $window_altitude += $records[$front]->delta_altitude; if ($window_distance > $min_climb['min_distance']) { $window_gradient = $window_altitude / $window_distance * 100; /* Check if we have found the start of a climb */ if ($cat == -1 && $window_gradient >= $climbs[$cat + 1]['min_gradient']) { $cat++; /* Go through and find the minimum height */ $min = $back; for ($i = $back; $i < $front; $i++) { if ($records[$i]->altitude <= $records[$min]->altitude) { $min = $i; } } $climb['bottom'] = $records[$min]->interval; $climb['min_altitude'] = $records[$min]->altitude; } /* Check if we have finished the climb */ if ($cat != -1 && $window_gradient < $climbs[$cat]['min_gradient']) { /* Need to go back and find the maximum altitude */ $max = $back; for ($i = $back; $i < $front; $i++) { if ($records[$i]->altitude > $records[$max]->altitude) { $max = $i; } } $climb['top'] = $records[$max]->interval; $climb['max_altitude'] = $records[$max]->altitude; /* Get the max gradient */ $climb['gradient_max'] = $records[$min]->gradient; for ($i = $min; $i <= $max; $i++) { if ($climb['gradient_max'] < $records[$i]->gradient) { $climb['gradient_max'] = $records[$i]->gradient; } } /* Tally the totals */ $climb['total_climbed'] = 0; for ($i = $min + 1; $i <= $max; $i++) { $climb['total_climbed'] += $records[$i]->delta_altitude; } $climb['total_distance'] = round($records[$max]->distance - $records[$min]->distance, 2); $climb['gradient_avg'] = round($climb['total_climbed'] / ($climb['total_distance'] * 1000) * 100, 2); /* Find the category of the climb */ $cat = -1; while ($cat + 1 < $num_climbs && $climb['gradient_avg'] >= $climbs[$cat + 1]['min_gradient'] && $climb['total_distance'] * 1000 >= $climbs[$cat + 1]['min_distance'] && $climb['total_climbed'] >= $climbs[$cat + 1]['min_height']) { $cat++; } $climb['cat'] = $cat; if ($cat != -1) { /* Store it into the database */ $api->insertClimb($session_timestamp, $climb_num++, $climb['bottom'], $climb['top'], $climb['gradient_avg'], $climb['gradient_max'], $climb['total_distance'], $climb['total_climbed'], $climb['min_altitude'], $climb['max_altitude']); /* Start search for the next climb */ $front = $max; $back = $max; $window_distance = 0; $window_altitude = 0; } else { /* It was a false climb, either not steep enough, * too short, and the window just masked this * Keep searching for the next climb */ } $cat = -1; } /* Move the back of the window up */ while ($window_distance > $min_climb['min_distance'] && $back < $num_records) { $window_distance -= $records[$back]->delta_distance * 1000; $window_altitude -= $records[$back]->delta_altitude; $back++; } } } $timer->setMarker('Climb - End'); /* * Bikes * userid * name * description * type, TT or Road * weight * picture? * Assign a bike to an exercise session at creation time? */ unset($records); $timer->setMarker('Laps - Start'); exec('/usr/local/bin/fitdecode -l ' . $upload['tmp_name'], $xml_laps); $xml_laps = implode("\n", $xml_laps); $laps = parseLaps($xml_laps); $timer->setMarker('Laps - End'); $lap_num = 1; foreach ($laps as $lap) { $ftime = strptime($lap->start_time, '%FT%T%z'); $start_epoch = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1, $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900); $lap_start = $start_epoch - $session_epoch; $api->insertLap($session_timestamp, $lap_num, $lap_start, $lap->start_position_lat, $lap->start_position_long, $lap->total_timer_time, $lap->total_elapsed_time, $lap->total_calories, $lap->avg_heart_rate, $lap->max_heart_rate, $lap->avg_speed, $lap->max_speed, $lap->total_ascent, $lap->total_descent, $lap->total_distance); $lap_num++; } //$timer->display(); $db->commit(); $plans = Module_Plans_API::getInstance(); $view->planned = $plans->getClosestPlan($session_timestamp); $view->session_timestamp = $session_timestamp; $view->UploadStatusMsg = "Is this session the planned exercise session on at ere"; $view->UploadStatus = "Success"; } catch (Exception $e) { $db->rollback(); $view->UploadStatusMsg = "Failed to upload"; $view->UploadStatus = "Error"; echo $e->getMessage(); } $timer->display(); } $view->addForm($form); $view->subTemplate = 'genericForm.tpl'; echo $view->render(); }
/** * Create a new user */ function signup() { $form = new Module_Login_SignUpForm(); $view = Core_View::factory('signup'); $view->errorMessage = ""; if ($form->validate()) { $api = new Module_Login_API(); $user_api = new Module_UserManagement_API(); $login = $form->getSubmitValue('form_login'); $password = $form->getSubmitValue('form_password'); $password2 = $form->getSubmitValue('form_passwordconfirm'); $email = $form->getSubmitValue('form_email'); /* Check the passwords match */ try { /* Check if the username exists */ if ($api->getUser($login)) { throw new Exception('The username is already taken'); } /* Check the passwords */ if ($password !== $password2) { throw new Exception('The passwords do not match'); } $user_api->createUser($login, $password, $email); Core_Url::redirectToUrl('index.php'); } catch (Exception $e) { $view->errorMessage = $e->getMessage(); } } $view->addForm($form); $view->subTemplate = 'genericForm.tpl'; echo $view->render(); }