function doLogin($error_string = null) { /* $currentUrl = Core_Helper::getModule() == 'Login' ? Core_Url::getReferer() : 'index.php' . Core_Url::getCurrentQueryString(); */ //self::checkForceSslLogin(); /* Keep reference to the url, so we can redirect there later */ $currentUrl = 'index.php' . Core_Url::getCurrentQueryString(); $urlToRedirect = Core_Common::getRequestVar('form_url', $currentUrl, 'string'); $urlToRedirect = htmlspecialchars_decode($urlToRedirect); $form = new Module_Login_LoginForm(); if ($form->validate()) { $login = $form->getSubmitValue('form_login'); $password = $form->getSubmitValue('form_password'); $rememberme = $form->getSubmitValue('form_rememberme'); try { $this->authenticateAndRedirect($login, $password, $rememberme); } catch (Exception $e) { $error_string = $e->getMessage(); } } $view = Core_View::factory('login'); $view->urlToRedirect = $urlToRedirect; $view->addForm($form); $view->subTemplate = 'genericForm.tpl'; $view->AccessErrorString = $error_string; echo $view->render(); }
/** * 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(); }
/** * */ function preDispatch() { $currentLogin = Core_Common::getCurrentUserLogin(); $currentModule = Core_Helper::getModule(); $loginModule = Core_Helper::getLoginModuleName(); if ($currentModule !== $loginModule && (empty($currentLogin) || $currentLogin === 'anonymous')) { Core_Helper::redirectToModule($loginModule); } }
/** * Smarty {hiddenurl} function plugin. * Writes an input Hidden field for every parameter in the URL. * Useful when using GET forms because we need to print the current parameters * in hidden input so they are to the next URL after the form is submitted. * * * Examples: * <pre> * {hiddenurl module="API"} with a URL 'index.php?action=test&module=CoreHome' will output * <input type=hidden name=action value=test> * <input type=hidden name=module value=API> * </pre> * * Set a value to null if you want this value not to be passed in the submitted form. * * @param array * @param Smarty * @return string */ function smarty_function_hiddenurl($params, &$smarty) { $queryStringModified = Core_Url::getCurrentQueryStringWithParametersModified($params); $urlValues = Core_Common::getArrayFromQueryString($queryStringModified); $out = ''; foreach ($urlValues as $name => $value) { $out .= '<input type="hidden" name="' . $name . '" value="' . $value . '" />'; } return $out; }
function viewDaily() { $api = new Module_Plans_API(); $week_date = Core_Common::getRequestVar('week_date', null, 'string'); $daily_plans = $api->getDailyPlans($week_date); $view = Core_View::factory('daily'); $view->plans = $daily_plans; $view->week_date = $week_date; $view->coach = $_SESSION['coach']; echo $view->render(); }
/** * Apply generic filters to the DataTable object resulting from the API Call. * Disable this feature by setting the parameter disable_generic_filters to 1 in the API call request. * * @param Core_DataTable */ protected function applyGenericFilters($datatable) { if ($datatable instanceof Core_DataTable_Array) { $tables = $datatable->getArray(); foreach ($tables as $table) { $this->applyGenericFilters($table); } return; } $genericFilters = self::getGenericFiltersInformation(); foreach ($genericFilters as $filterName => $parameters) { $filterParameters = array(); $exceptionRaised = false; foreach ($parameters as $name => $info) { // parameter type to cast to $type = $info[0]; // default value if specified, when the parameter doesn't have a value $defaultValue = null; if (isset($info[1])) { $defaultValue = $info[1]; } try { $value = Core_Common::getRequestVar($name, $defaultValue, $type, $this->request); settype($value, $type); $filterParameters[] = $value; } catch (Exception $e) { $exceptionRaised = true; break; } } if (!$exceptionRaised) { // a generic filter class name must follow this pattern $class = "Core_DataTable_Filter_" . $filterName; if ($filterName == 'Limit') { $datatable->setRowsCountBeforeLimitFilter(); } // build the set of parameters for the filter $filterParameters = array_merge(array($datatable), $filterParameters); // use Reflection to create a new instance of the filter, given parameters $filterParameters $reflectionObj = new ReflectionClass($class); $filter = $reflectionObj->newInstanceArgs($filterParameters); } } }
/** * Handles the request to the API. * It first checks that the method called (parameter 'method') is available in the module (it means that the method exists and is public) * It then reads the parameters from the request string and throws an exception if there are missing parameters. * It then calls the API Proxy which will call the requested method. * * @return mixed The data resulting from the API call */ public function process() { // read the format requested for the output data //$outputFormat = strtolower(Core_Common::getRequestVar('format', 'xml', 'string', $this->request)); $outputFormat = strtolower(Core_Common::getRequestVar('format', 'json', 'string', $this->request)); // create the response $response = new API_ResponseBuilder($this->request, $outputFormat); try { // read parameters $moduleMethod = Core_Common::getRequestVar('method', null, null, $this->request); list($module, $method) = $this->extractModuleAndMethod($moduleMethod); /* Load the request module */ $api_file = "Module" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . "API.php"; /* Include the module */ if (!file_exists($api_file)) { echo "API not found " . $requested_module; return; } require_once $api_file; $api_class = "Module_" . $module . "_API"; if (!class_exists($api_class)) { // Error throw new Exception("Error: Unknown class " . $requested_module); } // Dynamically create the class $this->api = new $api_class(); // Dynamically call the action if (!method_exists($this->api, $method)) { // Error throw new Exception("Error: Unknown method " . $method); return; } // call the method $returnedValue = API_Proxy::getInstance()->call($api_class, $method, $this->request); $toReturn = $response->getResponse($returnedValue); } catch (Exception $e) { $toReturn = $response->getResponseException($e); } return $toReturn; }
function dispatch($module = null, $action = null, $parameters = null) { if (is_null($module)) { $defaultModule = Core_Helper::getDefaultModuleName(); $module = Core_Common::getRequestVar('module', $defaultModule, 'string'); } if (is_null($action)) { $action = Core_Common::getRequestVar('action', false); } if (is_null($parameters)) { $parameters = array(); } if (!ctype_alnum($module)) { throw new Exception("Invalid module name '{$module}'"); } $controllerClassName = "Module_" . $module . "_Controller"; /* Check if the plugin has been activated */ if (!Core_ModuleManager::getInstance()->isModuleActivated($module)) { throw new Core_FrontController_PluginDeactivatedException($module); } // Dynamically create the class $controller = new $controllerClassName(); if ($action === false) { $action = $controller->getDefaultAction(); } // Dynamically call the action if (!is_callable(array($controller, $action))) { throw new Exception("Action not found in {$controllerClassName}::{$action}()."); } try { $controller->preDispatch(); return call_user_func_array(array($controller, $action), $parameters); } catch (Core_Access_NoAccessException $e) { Core_PostEvent('FrontController.NoAccessException'); } catch (Exception $e) { echo 'Error: ' . $e; return null; } }
/** * Returns a HTML page containing help for all the successfully loaded APIs. * For each module it will return a mini help with the method names, parameters to give, * links to get the result in Xml/Csv/etc * * @return string */ public function getAllInterfaceString($outputExampleUrls = true, $prefixUrls = '') { $str = ''; $token_auth = "&token_auth=" . Core::getCurrentUserTokenAuth(); $parametersToSet = array('idSite' => Core_Common::getRequestVar('idSite', 1, 'int'), 'period' => Core_Common::getRequestVar('period', 'day', 'string'), 'date' => Core_Common::getRequestVar('date', 'today', 'string')); foreach (Core_API_Proxy::getInstance()->getMetadata() as $class => $info) { $moduleName = Core_API_Proxy::getInstance()->getModuleNameFromClassName($class); $str .= "\n<h2 id='{$moduleName}'>Module " . $moduleName . "</h2>"; foreach ($info as $methodName => $infoMethod) { $params = $this->getStrListParameters($class, $methodName); $str .= "\n" . "- <b>{$moduleName}.{$methodName} " . $params . "</b>"; $str .= '<small>'; if ($outputExampleUrls) { // we prefix all URLs with $prefixUrls // used when we include this output in the Core official documentation for example $str .= "<span class=\"example\">"; $exampleUrl = $this->getExampleUrl($class, $methodName, $parametersToSet); if ($exampleUrl !== false) { $lastNUrls = ''; if (preg_match('/(&period)|(&date)/', $exampleUrl)) { $exampleUrlRss1 = $prefixUrls . $this->getExampleUrl($class, $methodName, array('date' => 'last10') + $parametersToSet); $exampleUrlRss2 = $prefixUrls . $this->getExampleUrl($class, $methodName, array('date' => 'last5', 'period' => 'week') + $parametersToSet); $lastNUrls = ",\tRSS of the last <a target=_blank href='{$exampleUrlRss1}&format=rss{$token_auth}'>10 days</a>, <a target=_blank href='{$exampleUrlRss2}&format=Rss'>5 weeks</a>,\n\t\t\t\t\t\t\t\t\tXML of the <a target=_blank href='{$exampleUrlRss1}&format=xml{$token_auth}'>last 10 days</a>"; } $exampleUrl = $prefixUrls . $exampleUrl; $str .= " [ Example in \n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=xml{$token_auth}'>XML</a>, \n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=PHP&prettyDisplay=true{$token_auth}'>PHP</a>, \n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=JSON{$token_auth}'>Json</a>, \n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=Csv{$token_auth}'>Csv</a>, \n\t\t\t\t\t\t\t\t\t<a target=_blank href='{$exampleUrl}&format=Html{$token_auth}'>Basic html</a> \n\t\t\t\t\t\t\t\t\t{$lastNUrls}\n\t\t\t\t\t\t\t\t\t]"; } else { $str .= " [ No example available ]"; } $str .= "</span>"; } $str .= '</small>'; $str .= "\n<br>"; } } return $str; }
function getClimbs() { $db = Zend_Registry::get('db'); $select = $db->select()->from('v_climbs_details', array('userid', 'session_date', 'climb_num', 'name', 'description', 'name AS duration', 'name AS distance'))->where('userid = ?', Core_Common::getCurrentUserLogin())->order('climb_num ASC'); $stmt = $db->query($select); return $stmt->fetchAll(); }
/** * View factory method * * @param $templateName Template name (e.g., 'index') * @param $viewType View type (e.g., View::CLI) */ public static function factory($templateName, $viewType = null, $path = null) { //PostEvent('View.getViewType', $viewType); // get caller if ($path === null) { $bt = @debug_backtrace(); if ($bt === null || !isset($bt[0])) { throw new Exception("View factory cannot be invoked"); } $path = dirname($bt[0]['file']); } else { $path = USER_PATH . DIRECTORY_SEPARATOR . $path; } // determine best view type if ($viewType === null) { if (Core_Common::isPhpCliMode()) { $viewType = self::CLI; } else { $viewType = self::STANDARD; } } // get template filename if ($viewType == self::CLI) { $templateFile = $path . '/templates/cli_' . $templateName . '.tpl'; if (file_exists($templateFile)) { return new View($templateFile, array(), false); } $viewType = self::STANDARD; } if ($viewType == self::MOBILE) { $templateFile = $path . '/templates/mobile_' . $templateName . '.tpl'; if (!file_exists($templateFile)) { $viewType = self::STANDARD; } } if ($viewType != self::MOBILE) { $templateFile = $path . '/templates/' . $templateName . '.tpl'; if (!file_exists($templateFile)) { throw new Exception('Template not found: ' . $templateFile); } } return new Core_View($templateFile); }
/** * Escape values from the cookie before sending them back to the client * (when using the get() method). * * @return mixed The value once cleaned. */ protected static function escapeValue($value) { return Core_Common::sanitizeInputValues($value); }
function viewLaps() { $api = new Module_SessionGraphs_API(); $session_date = Core_Common::getRequestVar('session_date', null, 'string'); $lap_num = Core_Common::getRequestVar('lap_num', null, 'string'); $view = Core_View::factory('sessionlaps'); $view->session_date = $session_date; $view->lap_num = $lap_num; $session = $api->getSession($session_date); $laps = $api->getLaps($session_date); $lap = $laps[$lap_num - 1]; $zones = $api->getZones($session_date, $lap['start_time'], $lap['end_time']); $view->zones = $zones; $view->laps = $laps; $view->lap = $lap; $session_labels = array(); $session_labels[] = array("label" => 'Date', "value" => $session['session_date'], "id" => 'session_date', "units" => ''); $session_labels[] = array("label" => 'Duration', "value" => $session['duration'], "id" => 'duration', "units" => ''); $session_labels[] = array("label" => 'Distance', "value" => $session['distance'], "id" => 'distance', "units" => 'km'); $session_labels[] = array("label" => 'Avg Speed', "value" => $session['avg_speed'], "id" => 'avg_speed', "units" => 'km/h'); $session_labels[] = array("label" => 'Max Speed', "value" => $session['max_speed'], "id" => 'max_speed', "units" => 'km/h'); $session_labels[] = array("label" => 'Avg Heart Rate', "value" => $session['avg_heartrate'], "id" => 'avg_heartrate', "units" => 'bpm'); $session_labels[] = array("label" => 'Max Heart Rate', "value" => $session['max_heartrate'], "id" => 'max_heartrate', "units" => 'bpm'); $session_labels[] = array("label" => 'Avg Heart Percent', "value" => $session['avg_heartrate_percent'], "id" => 'avg_heartrate_percent', "units" => '%'); $session_labels[] = array("label" => 'Max Heart Percent', "value" => $session['max_heartrate_percent'], "id" => 'max_heartrate_percent', "units" => '%'); $session_labels[] = array("label" => 'Energy', "value" => round($session['calories'] * 4.184), "id" => 'calories', "units" => 'kJ'); $session_labels[] = array("label" => 'Total Ascent', "value" => $session['total_ascent'], "id" => 'total_ascent', "units" => 'm'); $session_labels[] = array("label" => 'Total Descent', "value" => $session['total_descent'], "id" => 'total_descent', "units" => 'm'); $view->session = $session_labels; echo $view->render(); }
/** * Is user the anonymous user? * * @return bool True if anonymouse; false otherwise */ public static function isUserIsAnonymous() { return Core_Common::getCurrentUserLogin() == 'anonymous'; }
/** * Returns the current action read from the URL * * @return string */ public static function getAction() { return Core_Common::getRequestVar('action', '', 'string'); }
function updatePlanSession($plan_date, $session_date) { $db = Zend_Registry::get('db'); $db->update('t_exercise_plans_daily', array('session_timestamp' => $session_date), array('userid = \'' . Core_Common::getCurrentUserLogin() . '\'', 'timestamp = \'' . $plan_date . '\'')); }
function getClimb($session_date, $climb_num) { $db = Zend_Registry::get('db'); $select = $db->select()->from('v_climbs_data', array('userid', 'session_date', 'climb_num', 'cat AS category', 'top', 'bottom', 'total_distance', 'total_climbed', 'gradient_avg', 'gradient_max', 'min_altitude', 'max_altitude'))->where('userid = ?', Core_Common::getCurrentUserLogin())->where('session_date = ?', $session_date)->where('climb_num = ?', $climb_num); $stmt = $db->query($select); $climbs = $stmt->fetchAll(); return $climbs[0]; }
/** * Loads the module filename and instanciates the module with the given name, eg. UserCountry * Do NOT give the class name ie. Core_UserCountry, but give the module name ie. UserCountry * * @param Core_Module $moduleName */ public function loadModule($moduleName) { if (isset($this->loadedModules[$moduleName])) { return $this->loadedModules[$moduleName]; } $moduleFileName = $moduleName . '/Module.php'; $moduleClassName = 'Module_' . $moduleName . '_Module'; if (!Core_Common::isValidFilename($moduleName)) { throw new Exception("The module filename '{$moduleFileName}' is not a valid filename"); } $path = INCLUDE_PATH . '/Module/' . $moduleFileName; if (!file_exists($path)) { throw new Exception("Unable to load module '{$moduleName}' because '{$path}' couldn't be found.\n\t\t\tYou can manually uninstall the module by removing the line <code>Modules[] = {$moduleName}</code> from the Core config file."); } // Don't remove this. // Our autoloader can't find Module/ModuleName/Module.php require_once $path; // prefixed by CORE_INCLUDE_PATH if (!class_exists($moduleClassName, false)) { throw new Exception("The class {$moduleClassName} couldn't be found in the file '{$path}'"); } $newModule = new $moduleClassName(); if (!$newModule instanceof Core_Module) { throw new Exception("The module {$moduleClassName} in the file {$path} must inherit from Core_Module."); } return $newModule; }
/** * 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(); }
/** * Returns an array containing the values of the parameters to pass to the method to call * * @param array array of (parameter name, default value) * @return array values to pass to the function call * @throws exception If there is a parameter missing from the required function parameters */ private function getRequestParametersArray($requiredParameters, $parametersRequest) { $finalParameters = array(); foreach ($requiredParameters as $name => $defaultValue) { try { if ($defaultValue instanceof API_Proxy_NoDefaultValue) { $requestValue = Core_Common::getRequestVar($name, null, null, $parametersRequest); } else { try { $requestValue = Core_Common::getRequestVar($name, $defaultValue, null, $parametersRequest); } catch (Exception $e) { $requestValue = $defaultValue; } } } catch (Exception $e) { throw new Exception("The required variable '{$name}' is not correct or has not been found in the API Request. Add the parameter '&{$name}=' (with a value) in the URL."); } $finalParameters[] = $requestValue; } return $finalParameters; }
/** * Is the URL on the same host and in the same script path? * * @param string $url * @return bool True if local; false otherwise. */ public static function isLocalUrl($url) { // handle case-sensitivity differences $pathContains = Core_Common::isWindows() ? 'stripos' : 'strpos'; // test the scheme/protocol portion of the reconstructed "current" URL if (!strncasecmp($url, 'http://', 7) || !strncasecmp($url, 'https://', 8)) { // determine the offset to begin the comparison $offset = strpos($url, '://'); $current = strstr(self::getCurrentUrlWithoutFileName(), '://'); if ($pathContains($url, $current, $offset) === $offset) { return true; } } return false; }
/** * Get the list of bike parts * * @param string $bike_id The bicycle unique id * * @return Array of bike parts */ function getBikeData($bike_id) { $userid = Core_Common::getCurrentUserLogin(); $db = Zend_Registry::get('db'); $select = $db->select()->from('t_users_bikes_parts', array('userid', 'bike_id', 'id', 'category', 'part', 'description', 'inspection_period_km', 'inspection_period_date', 'inspected_km', 'inspected_date', 'replaced_km', 'replaced_date', 'withdrawn_km', 'withdrawn_date'))->where('userid = ?', $userid)->where('bike_id = ?', $bike_id)->order('category')->order('part')->order('id'); $stmt = $db->query($select); $parts = $stmt->fetchAll(); return $parts; }
function Core_Form_fieldHaveSameValue($element, $value, $arg) { $value2 = Core_Common::getRequestVar($arg, '', 'string'); $value2 = Core_Common::unsanitizeInputValue($value2); return $value === $value2; }
/** * Returns the plugin's base name without the "Core_" prefix, * e.g., "UserCountry" when the plugin class is "Core_UserCountry" * * @return string */ public final function getClassName() { return Core_Common::unprefixClass(get_class($this)); }
protected function handleDataTable($datatable) { // if the flag disable_generic_filters is defined we skip the generic filters if ('false' == Core_Common::getRequestVar('disable_generic_filters', 'false', 'string', $this->request)) { $genericFilter = new Core_API_DataTableGenericFilter($datatable, $this->request); $genericFilter->filter(); } // we automatically safe decode all datatable labels (against xss) $datatable->queueFilter('SafeDecodeLabel'); // if the flag disable_queued_filters is defined we skip the filters that were queued if (Core_Common::getRequestVar('disable_queued_filters', 'false', 'string', $this->request) == 'false') { $datatable->applyQueuedFilters(); } return $this->getRenderedDataTable($datatable); }