Exemplo n.º 1
0
 public static function debug($message)
 {
     if (!DEBUG) {
         return;
     }
     ErrorHandler::error(500, "Debug", "<pre>" . $message . "</pre>", 3);
 }
Exemplo n.º 2
0
 public static function ensureDir($name, $mode = 0750)
 {
     if (!is_dir($name)) {
         if (!@mkdir($name, $mode, true)) {
             ErrorHandler::error(500, null, "Unable to create directory {$name}");
         }
     }
 }
Exemplo n.º 3
0
 public function getArray()
 {
     $data = json_decode(file_get_contents($this->filename_cache), true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         ErrorHandler::error(500, null, "Error in {$filename} : " . self::jsonLastErrorMsg());
     }
     return $data;
 }
Exemplo n.º 4
0
 public function loadAsKey($key, $filename)
 {
     $data = json_decode(file_get_contents($filename), true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         ErrorHandler::error(500, null, "Error in {$filename} : " . self::jsonLastErrorMsg());
     }
     $this->data[$key] = $data;
     Logger::debug("Config {$filename} loaded");
 }
Exemplo n.º 5
0
 protected function login($username, $password)
 {
     $users = new UsersModel();
     $userid = $users->dologin($username, $password);
     if ($userid === false) {
         ErrorHandler::error(401, "Invalid username or password");
     }
     return $userid;
 }
Exemplo n.º 6
0
 /**
  * Dispatch the request.
  */
 public function dispatch()
 {
     if ($this->active) {
         // Initialize the core model
         $coreModel = new CoreModel($this->request);
         // Validate the request
         $requestValid = $coreModel->validateRequest();
         $output = '';
         if ($requestValid) {
             // Retrieve the correct module controller
             $controllerObj = $this->getRequestController();
             // In case the controller could not be initialized, throw an exception
             if (!$controllerObj) {
                 ErrorHandler::error(E_ERROR, 'The requested endpoint could not be initialized');
             }
             // In case the module is inactive or the requested method does not exist, throw an exception
             if (!$controllerObj->active || !method_exists($controllerObj, $this->action)) {
                 ErrorHandler::error(E_ERROR, "The requested action '%s' is not available", $this->action);
             }
             // Start an output buffer to catch request content
             ob_start();
             // Execute the before action when present
             $beforeMethodName = 'before' . ucfirst($this->action);
             if (method_exists($controllerObj, $beforeMethodName)) {
                 $controllerObj->{$beforeMethodName}();
             }
             // Execute the requested action
             $controllerObj->{$this->action}();
             // Execute the after action when present
             $afterMethodName = 'after' . ucfirst($this->action);
             if (method_exists($controllerObj, $afterMethodName)) {
                 $controllerObj->{$afterMethodName}();
             }
             // Retrieve the output buffer result
             $result = ob_get_clean();
             // In case the request is AJAX, output the request result directly
             if ($this->request->ajax) {
                 // Retrieve the header include content
                 $header = $this->getHeaderIncludeHTML();
                 $output = $header . $result;
             } else {
                 // Retrieve the output
                 ob_start();
                 require_once $this->modulePath . DIR_VIEW . 'index.php';
                 $output = ob_get_clean();
             }
         }
     } else {
         $output = $this->getMaintenanceView();
     }
     // Set the output character set
     header('Content-type: text/html; charset=utf-8');
     //                header('Cache-Control: max-age=3600');
     // Send the output
     exit($output);
 }
Exemplo n.º 7
0
 public function insert($filename, $optional = false)
 {
     $template = self::findTemplate($filename);
     if ($template === false) {
         if ($optional) {
             return;
         }
         ErrorHandler::error(404, null, $filename);
     }
     include $template;
 }
Exemplo n.º 8
0
 public function validateRequestParams()
 {
     $userName = $this->getParam(REQUEST_PARAMETER_USER_NAME);
     $userPassword = $this->getParam(REQUEST_PARAMETER_USER_PASSWORD);
     if (!$userName || !$userPassword) {
         ErrorHandler::error(E_ERROR, 'Missing user parameters');
     }
     $this->userName = strtolower($userName);
     $password = mcrypt_encrypt(MCRYPT_RIJNDAEL_192, VISUALIZATION_KEY, $userPassword, MCRYPT_MODE_ECB);
     $this->userPassword = urlencode($password);
 }
Exemplo n.º 9
0
 public function validateRequestParams()
 {
     $loggedIn = Session::getData(REQUEST_PARAMETER_LOGGEDIN);
     $this->user = Session::getData(REQUEST_PARAMETER_USER_NAME);
     if (!$loggedIn || !isset($this->user['UserName']) || !isset($this->user['Email'])) {
         ErrorHandler::error(E_ERROR, 'This action is not allowed');
     }
     $this->visualization = $this->getVisualization();
     if (!isset($this->visualization[REQUEST_PARAMETER_VIZ_ID]) || !$this->visualization[REQUEST_PARAMETER_VIZ_ID]) {
         ErrorHandler::error(E_ERROR, 'An invalid visualization was requested');
     }
     if (!$this->visualization[REQUEST_PARAMETER_MYMAP]) {
         ErrorHandler::error(E_ERROR, 'Only My Maps are allowed');
     }
 }
Exemplo n.º 10
0
 public function validateRequestParams()
 {
     $loggedIn = Session::getData(REQUEST_PARAMETER_LOGGEDIN);
     $this->user = Session::getData(REQUEST_PARAMETER_USER_NAME);
     if (!$loggedIn || !isset($this->user['UserName']) || !isset($this->user['Email'])) {
         ErrorHandler::error(E_ERROR, 'This action is not allowed');
     }
     $this->visualization = $this->getVisualization();
     if (!isset($this->visualization[REQUEST_PARAMETER_VIZ_ID]) || !$this->visualization[REQUEST_PARAMETER_VIZ_ID] || !$this->visualization[REQUEST_PARAMETER_MYMAP] && (!$this->visualization['map_enabled'] || !$this->visualization['edit_enabled'])) {
         ErrorHandler::error(E_ERROR, 'An invalid visualization was requested');
     }
     $this->featureId = $this->getParam('featureId');
     $this->layerId = $this->getParam('layerId');
     if (!$this->featureId || !$this->layerId) {
         ErrorHandler::error(E_ERROR, 'No feature data was given');
     }
 }
Exemplo n.º 11
0
 public function parse($filenames)
 {
     if (!is_array($filenames)) {
         $filenames = array($filenames);
     }
     $template = false;
     foreach ($filenames as $filename) {
         $template = self::findTemplate($filename);
         if ($template !== false) {
             break;
         }
     }
     if ($template === false) {
         ErrorHandler::error(404, null, implode(", ", $filenames));
     }
     return Markdown::transform(file_get_contents($template));
 }
Exemplo n.º 12
0
 public static function ensureRequest($array, $mandatory, $optional = array(), $strict = false)
 {
     foreach ($mandatory as $param) {
         if (!isset($array[$param])) {
             ErrorHandler::error(417, null, "Missing parameter {$param}");
         }
         if ($array[$param] == "") {
             ErrorHandler::error(417, null, "Empty parameter {$param}");
         }
     }
     if ($strict) {
         foreach ($array as $param => $val) {
             if (!(in_array($param, $mandatory) || in_array($param, $optional))) {
                 ErrorHandler::error(417, null, "Parameter overly {$param}");
             }
         }
     }
 }
Exemplo n.º 13
0
 /**
  * Send a cURL request.
  *
  * @param       string          $url            URL to call
  * @param       array           $options        cURL options (optional)
  * @param       array           $timeout        Request timeout in seconds (optional)
  * @return      mixed                           Result
  */
 public static function runCurl($url, $options = array(), $timeout = 30)
 {
     // Prepare the timeout option
     $options[CURLOPT_TIMEOUT] = intval($timeout);
     // Initialize the cURL connection
     self::initCurl($url, $options);
     // Execute the call
     $curlResult = curl_exec(self::$curl);
     // In case of an unsuccessful request, set the result to false
     if (!in_array(curl_getinfo(self::$curl, CURLINFO_HTTP_CODE), array(200, 204, 301, 302, 304))) {
         // In case debug mode is enabled, throw an error
         if (debugMode()) {
             ErrorHandler::error(500, curl_getinfo(self::$curl, CURLINFO_HTTP_CODE) . ': ' . curl_error(self::$curl));
         }
         $curlResult = false;
     }
     // Return the call result
     return $curlResult;
 }
Exemplo n.º 14
0
 public function validateRequestParams()
 {
     $loggedIn = Session::getData(REQUEST_PARAMETER_LOGGEDIN);
     $this->user = Session::getData(REQUEST_PARAMETER_USER_NAME);
     if (!$loggedIn || !isset($this->user['UserName']) || !isset($this->user['Email'])) {
         ErrorHandler::error(E_ERROR, 'This action is not allowed');
     }
     // @todo: update so this class can deal with other update fields like email
     $passwordOld = $this->getParam('passwordOld');
     $passwordNew = $this->getParam('passwordNew');
     $passwordConfirm = $this->getParam('passwordConfirm');
     if (!$passwordOld || !$passwordNew || !$passwordConfirm) {
         ErrorHandler::error(E_ERROR, 'Invalid password input');
     }
     $passwordHashOld = mcrypt_encrypt(MCRYPT_RIJNDAEL_192, VISUALIZATION_KEY, $passwordOld, MCRYPT_MODE_ECB);
     $this->passwordOld = urlencode($passwordHashOld);
     $passwordHashNew = mcrypt_encrypt(MCRYPT_RIJNDAEL_192, VISUALIZATION_KEY, $passwordNew, MCRYPT_MODE_ECB);
     $this->passwordNew = urlencode($passwordHashNew);
     $passwordHashConfirm = mcrypt_encrypt(MCRYPT_RIJNDAEL_192, VISUALIZATION_KEY, $passwordConfirm, MCRYPT_MODE_ECB);
     $this->passwordConfirm = urlencode($passwordHashConfirm);
 }
Exemplo n.º 15
0
 public function create()
 {
     $webserviceUrl = WEBSERVICE_URL . 'visualization/wo/visualization';
     $webserviceParams = array('user' => WEBSERVICE_USER, 'password' => WEBSERVICE_PASSWORD, 'userName' => $this->user['UserName'], 'userKey' => $this->user['ApiKey'], 'format' => 'application/json');
     $visualizationName = $this->getParam('createName');
     if ($visualizationName) {
         $webserviceParams['visualizationName'] = strip_tags($visualizationName);
     }
     $webserviceResult = Connectivity::runCurl($webserviceUrl, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $webserviceParams));
     $result = false;
     if ($webserviceResult) {
         $webserviceContents = json_decode($webserviceResult, true);
         if (isset($webserviceContents['response']['visualization'])) {
             $result = $webserviceContents['response']['visualization'];
         }
     }
     if ($result === false) {
         ErrorHandler::error(E_NOTICE, "The visualization '%s' could not be created, result: %s", $visualizationName ? $webserviceParams['visualizationName'] : '', $webserviceResult);
     }
     return array(REQUEST_RESULT => $result);
 }
Exemplo n.º 16
0
 public function import()
 {
     // Set the script execution settings
     $importSize = String::formatBytes(VISUALIZATION_IMPORT_SIZE, 'mB');
     setExecutionSettings($importSize + 256);
     $result = false;
     $error = null;
     $fileName = File::handleUpload(DIR_TEMP, 'importFile', null, array(), VISUALIZATION_IMPORT_SIZE);
     if ($fileName) {
         $fileInfo = pathinfo($fileName);
         $fileNameNew = str_replace(' ', '_', substr(strtolower($fileInfo['filename']), 0, 22)) . '_' . Date::format('now', 'Ymd_His') . '.' . $fileInfo['extension'];
         $destinationDir = '\\\\db-images\\data.spotzi.com\\import\\' . $this->user['UserName'];
         if (!is_dir($destinationDir)) {
             mkdir($destinationDir);
         }
         $destination = $destinationDir . '\\' . $fileNameNew;
         if (is_dir($destinationDir) && copy(DIR_TEMP . $fileName, $destination)) {
             $importName = $this->getParam('importName');
             if (!$importName) {
                 $importName = ucwords(substr(str_replace('_', ' ', $fileName), 0, strrpos($fileName, '.')));
             }
             $dataUrl = 'http://data.spotzi.com/import/' . $this->user['UserName'] . '/' . $fileNameNew;
             $this->vizDb->insert(self::DB_CONNECTION_VIZ_WRITE, 'VisualizationImport', array('Service' => 'geonovum', 'UserName' => $this->user['UserName'], 'Email' => $this->user['Email'], 'Name' => $importName, 'DataUrl' => $dataUrl, 'DebugImport' => debugMode()));
             $webserviceUrl = String::prepare('%svisualization/wo/import?user=%s&password=%s&userName=%s&userKey=%s&callback=%s&format=application/json', WEBSERVICE_URL, WEBSERVICE_USER, WEBSERVICE_PASSWORD, $this->user['UserName'], $this->user['ApiKey'], Url::buildPlatformURL(false, 'import', 'import', 'finish'));
             Connectivity::runCurlAsync($webserviceUrl);
             $result = true;
         } else {
             $error = __('An error occured while preparing the file');
         }
         File::delete(DIR_TEMP . $fileName);
     } else {
         $error = __('An error occured while uploading the file');
     }
     if ($result === false) {
         ErrorHandler::error(E_NOTICE, "The import failed, file name: %s\nerror: %s", $fileName, $error);
     }
     return array(REQUEST_RESULT => $result, REQUEST_ERROR => $error);
 }
Exemplo n.º 17
0
 /**
  * Load the module Model and View files by action.
  *
  * @param       string          $action         Module action to load (optional)
  */
 protected function render($action = null)
 {
     // In case no action is given, load the one given in the request
     if (empty($action)) {
         $action = $this->action;
     }
     // Load the model
     $model = $this->getModel($action);
     // In case the model could not be loaded, throw an error
     if (!$model) {
         ErrorHandler::error(E_ERROR, 'Invalid module model');
     }
     // Retrieve the module view path for the given action
     $viewPath = $this->getViewPath($action);
     // In case the view file does not exist, throw an error
     if (!file_exists($viewPath)) {
         ErrorHandler::error(E_ERROR, 'Invalid module view');
     }
     // Prepare the scope variables for easy accessibility in the view file
     // $this and $model are also be available
     // Include the view file
     require_once $viewPath;
 }
Exemplo n.º 18
0
 /**
  * Validate a request.
  *
  * @return      boolean                         True on success
  */
 public function validateRequest()
 {
     // In case of a missing request, throw an exception
     if (empty($this->request)) {
         ErrorHandler::error(E_ERROR, 'No request object was found for validation');
     }
     // Validate the endpoint
     $service = $this->validateEndpoint();
     // In case of an invalid endpoint, throw an exception
     if (!$service) {
         ErrorHandler::error(E_ERROR, 'Invalid endpoint specified');
     }
     $this->setLocale(REQUEST_LOCALE_DEFAULT);
     if (Session::getData(REQUEST_PARAMETER_LOGGEDIN)) {
         $user = Session::getData(REQUEST_PARAMETER_USER_NAME);
         if (!isset($user['UserName'])) {
             $this->clearSession();
         }
         $this->setParam('freshLogin', (bool) Session::getData('freshLogin'));
         Session::clearData('freshLogin');
     }
     // Return the validation result
     return true;
 }
Exemplo n.º 19
0
 /**
  * Handle a database error.
  *
  * @param       string          $message        Error Message
  */
 public function error($message)
 {
     $message = '<pre>' . print_r($message, true) . '</pre>';
     ErrorHandler::error(E_ERROR, 3, debugMode() ? $message : 'Invalid data source response');
 }
                //$errors['insert_failed'] = "Could not add the new user";
                ErrorHandler::error("Could not add the new user");
            }
        }
    } catch (SecurityException $e) {
        //this is probably fatal?
        ErrorHandler::error($e->getMessage());
    } catch (DuplicateUserException $e) {
        ErrorHandler::error($e->getMessage());
    }
} else {
    if (isset($_GET['type'])) {
        //get requests need to be validated too. Work on validating these kinds of requests.
        $userType = sanitize($_GET['type']);
        if (!in_array($userType, array_keys($userCategories))) {
            ErrorHandler::error('Invalid User Category');
        }
    }
}
?>
<section class="content">
	<?php 
ErrorHandler::displayErrors();
?>
	<div>
		<div class="notice">Note: Password is automatically set as the
			combination of user's first name and last four digits of their phone
			number, all lowercase.</div>
		<?php 
//error could be set elsewhere in the code, so we need retrieve it after the checks, if any
//in this case, we are checking for the usernam, if it is already in the database
Exemplo n.º 21
0
 function error($params)
 {
     $this->controller->plugin = basename(dirname(__FILE__));
     $this->controller->layout = 'noswad_error';
     parent::error($params);
 }
Exemplo n.º 22
0
 public static function handle($method = null, $path = null)
 {
     if ($path == null) {
         $path = @$_SERVER["PATH_INFO"];
     }
     if ($method == null) {
         $method = $_SERVER["REQUEST_METHOD"];
     }
     while (strlen($path) > 0 && $path[0] == "/") {
         $path = substr($path, 1);
     }
     if ($path == "") {
         $path = "index";
     }
     $pos = strpos($path, "/");
     if ($pos === false) {
         $request = $path;
         $next_path = "";
     } else {
         $request = substr($path, 0, $pos);
         $next_path = substr($path, $pos);
     }
     $request = str_replace(".", "_", $request);
     $request = str_replace("-", " ", $request);
     $request = ucwords($request);
     $request = str_replace(" ", "", $request) . "Rest";
     $request_file = Plugins::find(self::REQUEST_DIR . DIRECTORY_SEPARATOR . $request . ".class.php");
     if ($request_file === null) {
         ErrorHandler::error(404, null, $request . ".class.php");
     }
     require_once $request_file;
     $class_name = __NAMESPACE__ . "\\" . $request;
     $instance = new $class_name();
     $instance->handleRequest($method, $next_path);
     ErrorHandler::error(204);
 }
Exemplo n.º 23
0
 protected function doApiLogin($r)
 {
     Input::ensureRequest($_REQUEST, array("token"));
     if (($apiid = $this->apiLogin($_REQUEST["token"])) !== false) {
         Session::Set(self::apiid, $apiid);
         Session::addRight(self::logged_api);
         Output::success();
     }
     ErrorHandler::error(401);
 }
                            ErrorHandler::error('Could not update user profile');
                        }
                    } else {
                        ErrorHandler::error("Cannot retrieve current user information");
                    }
                } else {
                    //report as validation error that old password is incorrect
                    $validator->setError('old_pass', 'Invalid old password');
                }
            } else {
                //report as validation error that verify pass doesn't match
                $validator->setError('verify_pass', 'New password and verify password do not match');
            }
        }
    } catch (SecurityException $e) {
        ErrorHandler::error($e->getMessage());
    }
}
?>
<section class="content">
<?php 
ErrorHandler::displayErrors();
?>
	<div>
		<h2>
			<?php 
echo getCurrentUser();
?>
		</h2>
		<p>Please use this page to change your default password, if you
			haven't already done so.</p>
Exemplo n.º 25
0
 public static function ensureLoggedinUser()
 {
     if (!is_logged()) {
         ErrorHandler::error(401);
     }
 }
Exemplo n.º 26
0
 public function addFeature()
 {
     $this->featureArray = ['visualizationId' => $this->visualization[REQUEST_PARAMETER_VIZ_ID], 'featureAction' => $this->action];
     switch ($this->action) {
         case EDITOR_ACTION_NEW_FEATURE:
             $this->featureArray['the_geom'] = $this->the_geom;
             $this->featureArray['geom_type'] = $this->geom_type;
             $this->featureArray['featureStyle'] = $this->featureStyle;
             break;
         case EDITOR_ACTION_EDIT_DATA:
             $this->featureArray['featureId'] = $this->featureId;
             $this->featureArray['layerId'] = $this->layerId;
             $this->featureArray['geom_type'] = $this->geom_type;
             $this->featureArray['featureStyle'] = $this->featureStyle;
             break;
         case EDITOR_ACTION_EDIT_GEOM:
             $this->featureArray['featureId'] = $this->featureId;
             $this->featureArray['layerId'] = $this->layerId;
             $this->featureArray['the_geom'] = $this->the_geom;
             $this->featureArray['geom_type'] = $this->geom_type;
             break;
         case EDITOR_ACTION_DELETE:
             $this->featureArray['featureId'] = $this->featureId;
             $this->featureArray['layerId'] = $this->layerId;
             break;
     }
     if (in_array($this->action, [EDITOR_ACTION_NEW_FEATURE, EDITOR_ACTION_EDIT_DATA])) {
         $fileName = File::handleUpload(DIR_TEMP, 'imageurl', null, array(), 26214400);
         //25 MB
         $imageurl = '';
         if ($fileName) {
             if (exif_imagetype(DIR_TEMP . $fileName)) {
                 $fileNameNew = Date::format('now', 'YmdHis') . '_' . str_replace(' ', '_', $fileName);
                 $destinationDir = '\\\\db-images\\images.spotzi.com\\mapbuilder\\users\\' . $this->user['UserName'];
                 if (!is_dir($destinationDir)) {
                     mkdir($destinationDir);
                 }
                 $destination = $destinationDir . '\\' . $fileNameNew;
                 if (is_dir($destinationDir) && copy(DIR_TEMP . $fileName, $destination)) {
                     $importName = substr(str_replace('_', ' ', $fileName), 0, strrpos($fileName, '.'));
                     $imageurl = 'http://images.spotzi.com/mapbuilder/users/' . $this->user['UserName'] . '/' . $fileNameNew;
                 }
                 File::delete(DIR_TEMP . $fileName);
             } else {
                 File::delete(DIR_TEMP . $fileName);
                 ErrorHandler::error(E_ERROR, String::prepare('%s is not an image', $fileName));
             }
         } else {
             $imageurl = $this->getParam('image');
         }
         $this->featureArray['name'] = $this->getParam('name') ? $this->getParam('name') : '';
         $this->featureArray['description'] = $this->getParam('description') ? $this->getParam('description') : '';
         $this->featureArray['imageurl'] = $imageurl ? $imageurl : '';
     }
     $this->feature = json_encode($this->featureArray);
     $webserviceUrl = WEBSERVICE_URL . 'visualization/wo/map_feature';
     $webserviceParams = array('user' => WEBSERVICE_USER, 'password' => WEBSERVICE_PASSWORD, 'userName' => $this->user['UserName'], 'userKey' => $this->user['ApiKey'], 'feature' => $this->feature, 'format' => 'application/json');
     $result = false;
     $webserviceResult = Connectivity::runCurl($webserviceUrl, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $webserviceParams));
     if ($webserviceResult) {
         $webserviceContents = json_decode($webserviceResult, true);
         if (isset($webserviceContents['response']['map_feature'])) {
             $result = $webserviceContents['response']['map_feature'];
         }
     }
     return array(REQUEST_RESULT => $result);
 }
Exemplo n.º 27
0
 function error($params)
 {
     $this->controller->layout = "default";
     parent::error($params);
 }