Exemplo n.º 1
0
 /**
  * Default error action.
  *
  * On Phprojekt_PublishedException, return an error string in JSON format.
  * <pre>
  *  - type    => 'error'.
  *  - message => Error message.
  *  - code    => Error code.
  * </pre>
  *
  * On wrong controller name or action, terminates script execution.
  *
  * In all cases, the error is logged.
  *
  * @return void
  */
 public function errorAction()
 {
     $error = $this->_getParam('error_handler');
     $this->getResponse()->clearBody();
     switch ($error->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             // 404 error -- controller or action not found
             $this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');
             $message = "The url " . Cleaner::sanitize('xss', urldecode($error->request->getRequestUri())) . " do not exists";
             Phprojekt::getInstance()->getLog()->err($message);
             die($message);
             break;
         default:
             $exception = $error->exception;
             // We only forward exception with type PublishedException
             if ($exception instanceof Phprojekt_PublishedException) {
                 $error = array('type' => 'error', 'message' => $exception->getMessage(), 'code' => $exception->getCode());
                 echo '{}&&(' . Zend_Json_Encoder::encode($error) . ')';
             } else {
                 $logger = Phprojekt::getInstance()->getLog();
                 $logger->err($exception->getMessage() . "\n" . $exception->getTraceAsString());
             }
             break;
     }
 }
Exemplo n.º 2
0
 /**
  * Default error action.
  *
  * On Zend_Controller_Action_Exception, if the error code is 4xx return an error message matching the accepted type.
  *
  * On wrong controller name or action, terminates script execution.
  *
  * In all cases, the error is logged.
  *
  * @return void
  */
 public function errorAction()
 {
     $error = $this->_getParam('error_handler');
     $this->getResponse()->clearBody();
     $exception = $error->exception;
     $viewerror = array('type' => 'error', 'message' => 'Internal Server Error');
     switch ($error->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             // 404 error -- controller or action not found
             $this->getResponse()->setHttpResponseCode(404);
             $message = "The url " . Cleaner::sanitize('xss', urldecode($error->request->getRequestUri())) . " do not exists";
             Phprojekt::getInstance()->getLog()->err($message);
             die($message);
             break;
         default:
             // We only forward exception with 4xx code to the client
             if ($exception instanceof Zend_Controller_Action_Exception && $exception->getCode() >= 400 && $exception->getCode() < 500) {
                 $this->getResponse()->setHttpResponseCode($exception->getCode());
                 $viewerror['message'] = $exception->getMessage();
             } else {
                 $this->getResponse()->setHttpResponseCode(500);
                 $logger = Phprojekt::getInstance()->getLog();
                 $logger->err($exception->getMessage() . "\n" . $exception->getTraceAsString());
             }
             break;
     }
     $this->view->error = $viewerror;
 }
Exemplo n.º 3
0
 /**
  * Validate the configurations.
  *
  * @param array $params Array with values to save.
  *
  * @return string|null Error message.
  */
 public function validateConfigurations($params)
 {
     $message = null;
     // Company Name
     $companyName = Cleaner::sanitize('string', $params['companyName']);
     if (empty($companyName)) {
         $message = Phprojekt::getInstance()->translate('The Company name is empty');
     }
     return $message;
 }
Exemplo n.º 4
0
 /**
  * Returns the statistics data.
  *
  * Also return the Total per rows.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - date    <b>startDate</b> ISO start date for filter.
  *  - date    <b>endDate</b>   ISO end date for filter.
  *  - integer <b>nodeId</b>    List all the projects under nodeId.
  * </pre>
  *
  * The return is in CSV format.
  *
  * @return void
  */
 public function csvListAction()
 {
     $startDate = Cleaner::sanitize('date', $this->getRequest()->getParam('startDate', date("Y-m-d")));
     $endDate = Cleaner::sanitize('date', $this->getRequest()->getParam('endDate', date("Y-m-d")));
     $projectId = (int) $this->getRequest()->getParam('nodeId', null);
     $this->setCurrentProjectId();
     $data = $this->getModelObject()->getStatistics($startDate, $endDate, $projectId);
     $data = $data['data'];
     $rows = array();
     $sumPerUser = array();
     $index = 0;
     $rows[$index][] = 'Project';
     foreach ($data['users'] as $name) {
         $rows[$index][] = $name;
     }
     $rows[$index][] = 'Total';
     $index++;
     $converter = new Phprojekt_Converter_Time();
     foreach ($data['projects'] as $projectId => $title) {
         $sumPerProject = 0;
         $rows[$index][] = $title;
         foreach (array_keys($data['users']) as $userId) {
             if (!isset($data['rows'][$projectId][$userId])) {
                 $rows[$index][] = $converter->convertMinutesToHours(0);
             } else {
                 $rows[$index][] = $converter->convertMinutesToHours($data['rows'][$projectId][$userId]);
                 $sumPerProject = $sumPerProject + $data['rows'][$projectId][$userId];
                 if (!isset($sumPerUser[$userId])) {
                     $sumPerUser[$userId] = 0;
                 }
                 $sumPerUser[$userId] = $sumPerUser[$userId] + $data['rows'][$projectId][$userId];
             }
         }
         $rows[$index][] = $converter->convertMinutesToHours($sumPerProject);
         $index++;
     }
     $rows[$index][] = 'Total';
     $total = 0;
     foreach (array_keys($data['users']) as $userId) {
         if (!isset($sumPerUser[$userId])) {
             $rows[$index][] = $converter->convertMinutesToHours(0);
         } else {
             $rows[$index][] = $converter->convertMinutesToHours($sumPerUser[$userId]);
             $total = $total + $sumPerUser[$userId];
         }
     }
     $rows[$index][] = $converter->convertMinutesToHours($total);
     Phprojekt_Converter_Csv::echoConvert($rows);
 }
Exemplo n.º 5
0
 public function jsonGetSpecificUsersAction()
 {
     $ids = Cleaner::sanitize('arrayofint', $this->getRequest()->getParam('users', array()));
     if (empty($ids)) {
         $ids[] = (int) PHprojekt_Auth::getUserId();
     }
     $db = Phprojekt::getInstance()->getDb();
     $where = sprintf('status = %s AND id IN (%s)', $db->quote('A'), implode(", ", $ids));
     $user = new Phprojekt_User_User();
     $records = $user->fetchAll($where);
     $data = array();
     foreach ($records as $record) {
         $data['data'][] = array('id' => (int) $record->id, 'display' => $record->displayName);
     }
     Phprojekt_Converter_Json::echoConvert($data, Phprojekt_ModelInformation_Default::ORDERING_LIST);
 }
Exemplo n.º 6
0
 /**
  * Checks in the session if user is loggued in or not.
  * If it is not logged, tries to log him/her using browser cookies.
  *
  * @throws Phprojekt_Auth_UserNotLoggedInException On user not logged in.
  *
  * @return boolean True if user is logued in.
  */
 public static function isLoggedIn()
 {
     $authNamespace = new Zend_Session_Namespace('Phprojekt_Auth-login');
     // Is there session data?
     if (!isset($authNamespace->userId) || empty($authNamespace->userId)) {
         // No - Read cookies
         $readingPrefix = str_replace('.', '_', self::COOKIES_PREFIX);
         $cookieHashName = $readingPrefix . self::LOGGED_TOKEN . '_hash';
         $cookieUserId = $readingPrefix . self::LOGGED_TOKEN . '_user';
         // Are there cookies?
         if (isset($_COOKIE[$cookieHashName]) && isset($_COOKIE[$cookieUserId]) && (int) $_COOKIE[$cookieUserId] > 0) {
             // Yes
             $tokenCookieHash = Cleaner::sanitize('alnum', $_COOKIE[$cookieHashName]);
             $tokenCookieUserId = (int) $_COOKIE[$cookieUserId];
             $goToLoginPage = false;
             $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting');
             $setting->setModule('User');
             $tokenDbHash = $setting->getSetting(self::LOGGED_TOKEN . '_hash', $tokenCookieUserId);
             $tokenDbExpires = (int) $setting->getSetting(self::LOGGED_TOKEN . '_expires', (int) $tokenCookieUserId);
             // Is there valid DB token data, which has not expired?
             if ($tokenDbExpires > time()) {
                 // Yes - The expiration time exists and is valid. The hashes match?
                 if ($tokenCookieHash == $tokenDbHash) {
                     // Yes - Log in the user
                     $user = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User');
                     $user->find($tokenCookieUserId);
                     // If the user was found we will save the user information in the session
                     $authNamespace->userId = $user->id;
                     $authNamespace->admin = $user->admin;
                     // Save the data into the DB and Cookies
                     self::_saveLoginData($tokenCookieUserId);
                 } else {
                     $goToLoginPage = true;
                 }
             } else {
                 $goToLoginPage = true;
             }
             if ($goToLoginPage) {
                 self::_deleteDbAndCookies($tokenCookieUserId);
                 throw new Phprojekt_Auth_UserNotLoggedInException('User not logged in', 1);
             }
         } else {
             throw new Phprojekt_Auth_UserNotLoggedInException('User not logged in', 1);
         }
     }
     return true;
 }
Exemplo n.º 7
0
 /**
  * Return a value for set, using some validations from the table data.
  *
  * @param string $type  Type of field.
  * @param mixed  $value Value to transform.
  *
  * @return mixed Sanitized value.
  */
 public static function set($type, $value)
 {
     switch ($type) {
         case 'int':
             $value = Cleaner::sanitize('integer', $value, 0);
             break;
         case 'float':
             $value = Cleaner::sanitize('float', $value, 0);
             if ($value !== false) {
                 $value = Zend_Locale_Format::getFloat($value, array('precision' => 2));
             } else {
                 $value = 0;
             }
             break;
         case 'date':
             $value = Cleaner::sanitize('date', $value);
             break;
         case 'time':
             $value = Cleaner::sanitize('time', $value);
             $value = date("H:i:s", Phprojekt_Converter_Time::userToUtc($value));
             break;
         case 'datetime':
         case 'timestamp':
             $value = Cleaner::sanitize('timestamp', $value);
             $value = date("Y-m-d H:i:s", Phprojekt_Converter_Time::userToUtc($value));
             break;
         case 'text':
         default:
             if (is_array($value)) {
                 // if given value for a text field is an array, it's from a MultiSelect field
                 $value = implode(',', $value);
             }
             // Run html sanitize only if the text contain some html code
             if (preg_match("/([\\<])([^\\>]{1,})*([\\>])/i", $value)) {
                 $value = Cleaner::sanitize('html', $value);
             } else {
                 $value = Cleaner::sanitize('string', $value);
             }
             break;
     }
     return $value;
 }
Exemplo n.º 8
0
 /**
  * Returns the list of actions done in one item.
  *
  * REQUIRES request parameters:
  * <pre>
  *  - integer <b>moduleId</b> id of the module (if moduleName is sent, this is not necessary).
  *  - integer <b>itemId</b>   id of the item.
  * </pre>
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - integer <b>userId</b>     To filter by user id.
  *  - string  <b>moduleName</b> Name of the module (if moduleId is sent, this is not necessary).
  *  - date    <b>startDate</b>  To filter by start date.
  *  - date    <b>endDate</b>    To filter by end date.
  * </pre>
  *
  * The return is in JSON format.
  *
  * @throws Zend_Controller_Action_Exception On missing or wrong moduleId or itemId.
  *
  * @return void
  */
 public function jsonListAction()
 {
     $moduleId = (int) $this->getRequest()->getParam('moduleId', null);
     $itemId = (int) $this->getRequest()->getParam('itemId', null);
     $userId = (int) $this->getRequest()->getParam('userId', null);
     $moduleName = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', 'Default'));
     $startDate = Cleaner::sanitize('date', $this->getRequest()->getParam('startDate', null));
     $endDate = Cleaner::sanitize('date', $this->getRequest()->getParam('endDate', null));
     $this->setCurrentProjectId();
     if (empty($moduleId)) {
         $moduleId = Phprojekt_Module::getId($moduleName);
     }
     if (empty($itemId) || empty($moduleId)) {
         throw new Zend_Controller_Action_Exception("Invalid module or item", 400);
     } else {
         $history = new Phprojekt_History();
         $data = $history->getHistoryData(null, $itemId, $moduleId, $startDate, $endDate, $userId);
         $data = array('data' => $data);
         Phprojekt_Converter_Json::echoConvert($data);
     }
 }
Exemplo n.º 9
0
 /**
  * Saves a module.
  *
  * If the request parameter "id" is null or 0, the function will add a new module,
  * if the "id" is an existing module, the function will update it.
  *
  * The save action will try also to copy files into the application folder
  * if the module is a new one.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - integer <b>id</b>                      id of the module to save.
  *  - string  <b>name</b>                    Name of the module.
  *  - string  <b>label</b>                   Display of the module.
  *  - mixed   <b>all other module fields</b> All the fields values to save.
  * </pre>
  *
  * If there is an error, the save will return a Phprojekt_PublishedException,
  * if not, it returns a string in JSON format with:
  * <pre>
  *  - type    => 'success'.
  *  - message => Success message.
  *  - code    => 0.
  *  - id      => Id of the module.
  * </pre>
  *
  * @throws Phprojekt_PublishedException On error in the action save.
  *
  * @return void
  */
 public function jsonSaveAction()
 {
     $id = (int) $this->getRequest()->getParam('id');
     $this->setCurrentProjectId();
     if (empty($id)) {
         $model = $this->getModelObject();
         $message = Phprojekt::getInstance()->translate('The module was added correctly');
     } else {
         $model = $this->getModelObject()->find($id);
         $message = Phprojekt::getInstance()->translate('The module was edited correctly');
     }
     // Set the hidden name to name or label
     // use ucfirst and delete spaces
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('name', null));
     if (empty($module)) {
         $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('label', null));
     }
     $module = ucfirst(str_replace(" ", "", $module));
     $this->getRequest()->setParam('name', $module);
     $model->saveModule($this->getRequest()->getParams());
     $return = array('type' => 'success', 'message' => $message, 'code' => 0, 'id' => $model->id);
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 10
0
 /**
  * Assign a value to a var using some validations from the table data.
  *
  * @param string $varname Name of the var to assign.
  * @param mixed  $value   Value for assign to the var.
  *
  * @return void
  */
 public function __set($varname, $value)
 {
     $varForInfo = Phprojekt_ActiveRecord_Abstract::convertVarToSql($varname);
     $info = $this->info();
     if (true == isset($info['metadata'][$varForInfo])) {
         $type = $info['metadata'][$varForInfo]['DATA_TYPE'];
         $value = Phprojekt_Converter_Value::set($type, $value);
     } else {
         $value = Cleaner::sanitize('string', $value);
     }
     parent::__set($varname, $value);
 }
Exemplo n.º 11
0
 /**
  * Validate the params and if is all ok, migrate the data.
  *
  * REQUIRES request parameters:
  * <pre>
  *  - string <b>migrationConfigFile</b> File for get the config of P5.
  *  - integer <b>diffToUtc</b> Difference between the server and UTC.
  *  - string <b>module</b> Module to migrate.
  * </pre>
  *
  * The return have:
  * <pre>
  * - type     => The type of the message (error or success).
  * - message  => The message.
  * - template => The template to show.
  * </pre>
  *
  * The return is in JSON format.
  *
  * @return void
  */
 public function jsonMigrateSetupAction()
 {
     $this->view->message = array();
     $this->view->success = array();
     $params = array('migrationConfigFile' => Cleaner::sanitize('string', $this->getRequest()->getParam('migrationConfigFile')), 'diffToUtc' => Cleaner::sanitize('integer', $this->getRequest()->getParam('diffToUtc')), 'module' => Cleaner::sanitize('string', $this->getRequest()->getParam('module')));
     if (null !== $this->_setup) {
         if ($this->_setup->validateMigration($params)) {
             if (in_array($params['module'], $this->view->exportModules)) {
                 ob_start();
                 $this->_setup->migrate($params);
                 $errors = ob_get_contents();
                 if (!empty($errors)) {
                     $message = $errors;
                     $type = 'error';
                 } else {
                     $message = "Migration OK";
                     $type = 'success';
                 }
                 ob_end_clean();
             } else {
                 $message = 'Wrong module';
                 $type = 'error';
             }
         } else {
             $error = $this->_setup->getError();
             $message = array_shift($error);
             $type = 'error';
         }
     } else {
         $this->getResponse()->setHttpResponseCode(403);
         $this->sendResponse();
     }
     $template = $this->view->render('migrationOk.phtml');
     $this->returnContent($type, $message, $template, $params['module']);
 }
Exemplo n.º 12
0
 /**
  * Returns all the words translated in each modules for the request language.
  *
  * REQUIRES request parameters:
  * <pre>
  *  - string <b>language</b> The current language for get the translations.
  * </pre>
  *
  * The return is in JSON format.
  *
  * @return void
  */
 public function jsonGetTranslatedStringsAction()
 {
     $language = Cleaner::sanitize('alpha', $this->getRequest()->getParam('language', 'en'));
     $translate = Phprojekt::getInstance()->getTranslate();
     Phprojekt_Converter_Json::echoConvert($translate->getTranslatedStrings($language));
 }
Exemplo n.º 13
0
 /**
  * Converts the P5 datetime format YYYYMMDDHHMMSS to P6 date format YYYY-MM-DD.
  *
  * @param string $date Date & time in YYYYMMDDHHMMSS format.
  *
  * @return string Date in YYYY-MM-DD format.
  */
 private function _longDateToShortDate($date)
 {
     if (strlen($date) == 14) {
         $year = substr($date, 0, 4);
         $month = substr($date, 4, 2);
         $day = substr($date, 6, 2);
         $dateOut = $year . "-" . $month . "-" . $day;
         $dateOut = Cleaner::sanitize('date', $dateOut);
     } else {
         $dateOut = null;
     }
     return $dateOut;
 }
 /**
  * Saves the design of all the fields in the module.
  *
  * If the request parameter "id" is null or 0, the function will add a new module,
  * if the "id" is an existing module, the function will update it.
  *
  * The save action will try to add or update the module table itself and the database_manager.
  *
  * REQUIRES request parameters:
  * <pre>
  *  - integer <b>id</b>           id of the module to save.
  *  - string  <b>designerData</b> Data of the fields.
  *  - string  <b>name</b>         Name of the module.
  *  - string  <b>label</b>        Display of the module.
  * </pre>
  *
  * The return is a string in JSON format with:
  * <pre>
  *  - type    => 'success' or 'error'.
  *  - message => Success or error message.
  *  - id      => id of the module.
  * </pre>
  *
  * @throws Zend_Controller_Action_Exception On error in the action save.
  *
  * @return void
  */
 public function jsonSaveAction()
 {
     $id = (int) $this->getRequest()->getParam('id');
     $data = $this->getRequest()->getParam('designerData');
     $saveType = (int) $this->getRequest()->getParam('saveType');
     $model = null;
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('name', null));
     $this->setCurrentProjectId();
     if (empty($module)) {
         $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('label'));
     }
     $module = ucfirst(str_replace(" ", "", $module));
     $this->getRequest()->setParam('name', $module);
     if ($id > 0) {
         $model = Phprojekt_Loader::getModel($module, $module);
     }
     $message = $this->_handleDatabaseChange($model, $module, $data, $saveType, $id);
     if (!is_null($message)) {
         Phprojekt_Converter_Json::echoConvert($message);
         return;
     }
     $this->setCurrentProjectId();
     $message = '';
     if (empty($id)) {
         $model = new Phprojekt_Module_Module();
         $message = Phprojekt::getInstance()->translate('The module was added correctly');
     } else {
         $model = new Phprojekt_Module_Module();
         $model = $model->find($id);
         $message = Phprojekt::getInstance()->translate('The module was edited correctly');
     }
     $model->saveModule($this->getRequest()->getParams());
     Phprojekt_Module::clearCache();
     $return = array('type' => 'success', 'message' => $message, 'id' => $model->id);
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 15
0
 /**
  * Convert the rule and value into a real where clause.
  *
  * @param string $field      Field for filter.
  * @param string $identifier Converted field for filter.
  * @param string $rule       Rule for apply the filter.
  * @param string $keyword    Value used for filter.
  *
  * @return string Where clause.
  */
 private function _convertRule($field, $identifier, $rule, $keyword)
 {
     // Sanitize values
     if ($this->_info['metadata'][$identifier]['DATA_TYPE'] == 'time') {
         // Moving the value to UTC
         $identifier = $this->_record->getTableName() . '.' . $identifier;
         $identifier = Phprojekt::getInstance()->getDb()->quoteIdentifier($identifier);
         $value = Cleaner::sanitize('time', $keyword);
         $k = date("H:i:s", Phprojekt_Converter_Time::userToUtc($value));
         //$identifier = 'TIME(' . $identifier . ')';
     } else {
         if ($this->_info['metadata'][$identifier]['DATA_TYPE'] == 'datetime') {
             $identifier = $this->_record->getTableName() . '.' . $identifier;
             $identifier = Phprojekt::getInstance()->getDb()->quoteIdentifier($identifier);
             if (strstr($keyword, '-')) {
                 // Use it as date
                 $k = Cleaner::sanitize('date', $keyword);
                 $identifier = 'DATE(' . $identifier . ')';
             } else {
                 if (strstr($keyword, ':')) {
                     // Use it as time
                     $value = Cleaner::sanitize('time', $keyword);
                     $k = date("H:i:s", Phprojekt_Converter_Time::userToUtc($value));
                     $identifier = 'TIME(' . $identifier . ')';
                 } else {
                     // Use it as datetime
                     $value = Cleaner::sanitize('timestamp', $keyword);
                     $k = date("Y-m-d H:i:s", Phprojekt_Converter_Time::userToUtc($value));
                 }
             }
         } else {
             $keyword = mb_strtolower($keyword, 'UTF-8');
             $k = $keyword;
             $identifier = $this->_record->getTableName() . '.' . $identifier;
             $identifier = Phprojekt::getInstance()->getDb()->quoteIdentifier($identifier);
         }
     }
     switch ($rule) {
         case 'equal':
             $w = $identifier . ' = ? ';
             break;
         case 'notEqual':
             $w = $identifier . ' != ? ';
             break;
         case 'major':
             $w = $identifier . ' > ? ';
             break;
         case 'majorEqual':
             $w = $identifier . ' >= ? ';
             break;
         case 'minor':
             $w = $identifier . ' < ? ';
             break;
         case 'minorEqual':
             $w = $identifier . ' <= ? ';
             break;
         case 'begins':
             $w = $identifier . ' LIKE ? ';
             $k = $keyword . '%';
             break;
         case 'ends':
             $w = $identifier . ' LIKE ? ';
             $k = '%' . $keyword;
             break;
         case 'notLike':
             $w = $identifier . ' NOT LIKE ? ';
             $k = '%' . $keyword . '%';
             break;
         case 'like':
         default:
             $w = $identifier . ' LIKE ? ';
             $k = '%' . $keyword . '%';
     }
     return Phprojekt::getInstance()->getDb()->quoteInto($w, $k);
 }
Exemplo n.º 16
0
 protected function getFilterWhere($where = null)
 {
     $filters = $this->getRequest()->getParam('filters', "[]");
     $filters = Zend_Json_Decoder::decode($filters);
     if (!empty($filters)) {
         $filterClass = new Phprojekt_Filter($this->newModelObject(), $where);
         foreach ($filters as $filter) {
             list($filterOperator, $filterField, $filterRule, $filterValue) = $filter;
             $filterOperator = Cleaner::sanitize('alpha', $filterOperator, null);
             $filterField = Cleaner::sanitize('alpha', $filterField, null);
             $filterRule = Cleaner::sanitize('alpha', $filterRule, null);
             if (isset($filterOperator) && isset($filterField) && isset($filterRule) && isset($filterValue)) {
                 $filterClass->addFilter($filterField, $filterRule, $filterValue, $filterOperator);
             }
         }
         $where = $filterClass->getWhere();
     }
     return $where;
 }
Exemplo n.º 17
0
 /**
  * Returns the list of events where the logged user is involved,
  * for a specific period (like week or month).
  *
  * The function use Phprojekt_ModelInformation_Default::ORDERING_LIST for get and sort the fields.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - date    <b>dateStart</b> Start date for filter.
  *  - date    <b>dateEnd</b>   End date for filter.
  *  - integer <b>count</b>     Use for SQL LIMIT count.
  *  - integer <b>offset</b>    Use for SQL LIMIT offset.
  * </pre>
  *
  * The return is in CSV format.
  *
  * @return void
  */
 public function csvPeriodListAction()
 {
     $count = (int) $this->getRequest()->getParam('count', null);
     $offset = (int) $this->getRequest()->getParam('start', null);
     $db = Phprojekt::getInstance()->getDb();
     $dateStart = $db->quote(Cleaner::sanitize('date', $this->getRequest()->getParam('dateStart', date("Y-m-d"))));
     $dateEnd = $db->quote(Cleaner::sanitize('date', $this->getRequest()->getParam('dateEnd', date("Y-m-d"))));
     $this->setCurrentProjectId();
     $where = sprintf('participant_id = %d AND DATE(start_datetime) <= %s AND DATE(end_datetime) >= %s', (int) PHprojekt_Auth::getUserId(), $dateEnd, $dateStart);
     $records = $this->getModelObject()->fetchAll($where, "start_datetime", $count, $offset);
     Phprojekt_Converter_Csv::echoConvert($records, Phprojekt_ModelInformation_Default::ORDERING_FORM);
 }
Exemplo n.º 18
0
 /**
  * Delete the tags for one item.
  *
  * REQUIRES request parameters:
  * <pre>
  *  - integer <b>id</b> id of the item.
  * </pre>
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string <b>moduleName</b> Name of the module.
  * </pre>
  *
  * If there is an error, the delete will return a Zend_Controller_Action_Exception,
  * if not, it returns a string in JSON format with:
  * <pre>
  *  - type    => 'success'.
  *  - message => Success message.
  *  - id      => 0.
  * </pre>
  *
  * @throws Zend_Controller_Action_Exception On missing or wrong id.
  *
  * @return void
  */
 public function jsonDeleteTagsAction()
 {
     $tagObj = new Phprojekt_Tags();
     $id = (int) $this->getRequest()->getParam('id');
     if (empty($id)) {
         throw new Zend_Controller_Action_Exception(self::ID_REQUIRED_TEXT, 400);
     }
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', 'Project'));
     $moduleId = (int) Phprojekt_Module::getId($module);
     $tagObj->deleteTagsByItem($moduleId, $id);
     $message = Phprojekt::getInstance()->translate('The Tags were deleted correctly');
     $return = array('type' => 'success', 'message' => $message, 'id' => 0);
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 19
0
 /**
  * Set some values deppend on the params.
  *
  * @return array POST values with some changes.
  */
 public function setParams()
 {
     $args = func_get_args();
     $params = $args[0];
     $model = $args[1];
     if (empty($params['topicDate'])) {
         unset($params['topicDate']);
     } else {
         $params['topicDate'] = Cleaner::sanitize('date', $params['topicDate']);
     }
     if (empty($params['userId'])) {
         unset($params['userId']);
     } else {
         $params['userId'] = (int) $params['userId'];
     }
     $params['projectId'] = $model->projectId;
     $params['ownerId'] = $model->ownerId;
     if (isset($params['parentOrder']) && is_numeric($params['parentOrder']) && $params['parentOrder'] > 0) {
         // This item is supposed to be sorted after the given order
         $params['sortOrder'] = $params['parentOrder'] + 1;
         unset($params['parentOrder']);
     }
     return $params;
 }
Exemplo n.º 20
0
 /**
  * Set the file parameters needed by all the file actions.
  *
  * @return array A list with the file parameters.
  */
 private function _getFileParameters()
 {
     $model = $this->getModelObject();
     $field = Cleaner::sanitize('alnum', $this->getRequest()->getParam('field', null));
     $itemId = (int) $this->getRequest()->getParam('id', null);
     $this->setCurrentProjectId();
     return array($model, $field, $itemId);
 }
Exemplo n.º 21
0
 /**
  * Saves the design of all the fields in the module.
  *
  * If the request parameter "id" is null or 0, the function will add a new module,
  * if the "id" is an existing module, the function will update it.
  *
  * The save action will try to add or update the module table itself and the database_manager.
  *
  * REQUIRES request parameters:
  * <pre>
  *  - integer <b>id</b>           id of the module to save.
  *  - string  <b>designerData</b> Data of the fields.
  *  - string  <b>name</b>         Name of the module.
  *  - string  <b>label</b>        Display of the module.
  * </pre>
  *
  * The return is a string in JSON format with:
  * <pre>
  *  - type    => 'success' or 'error'.
  *  - message => Success or error message.
  *  - code    => 0.
  *  - id      => id of the module.
  * </pre>
  *
  * @throws Phprojekt_PublishedException On error in the action save.
  *
  * @return void
  */
 public function jsonSaveAction()
 {
     $id = (int) $this->getRequest()->getParam('id');
     $data = $this->getRequest()->getParam('designerData');
     $saveType = (int) $this->getRequest()->getParam('saveType');
     $model = null;
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('name', null));
     $this->setCurrentProjectId();
     if (empty($module)) {
         $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('label'));
     }
     $module = ucfirst(str_replace(" ", "", $module));
     if ($id > 0) {
         $model = Phprojekt_Loader::getModel($module, $module);
     }
     if ($model instanceof Phprojekt_Item_Abstract || $id == 0) {
         $databaseManager = new Phprojekt_DatabaseManager($model);
         $data = Zend_Json_Decoder::decode($data);
         // Validate
         if ($databaseManager->recordValidate($data, $saveType)) {
             // Update Table Structure
             $tableData = $this->_getTableData($data);
             if (!$databaseManager->syncTable($data, $module, $tableData)) {
                 $type = 'error';
                 $message = Phprojekt::getInstance()->translate('There was an error writing the table');
             } else {
                 // Update DatabaseManager Table
                 $databaseManager->saveData($module, $data, $tableData);
                 if (empty($id)) {
                     $message = Phprojekt::getInstance()->translate('The table module was created correctly');
                 } else {
                     $message = Phprojekt::getInstance()->translate('The table module was edited correctly');
                 }
                 $type = 'success';
             }
         } else {
             $error = $databaseManager->getError();
             $message = $error['label'] . ': ' . $error['message'];
             $type = 'error';
         }
     } else {
         $type = 'success';
         $message = null;
     }
     $return = array('type' => $type, 'message' => $message, 'code' => 0, 'id' => $id);
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 22
0
 /**
  * Set some values deppend on the params
  *
  * Sanitize some values and calculate the minutes value.
  *
  * @return array
  */
 public function setParams()
 {
     $args = func_get_args();
     $params = $args[0];
     $model = $args[1];
     $params['startDatetime'] = Cleaner::sanitize('datetime', $params['startDatetime']);
     if (isset($params['endTime'])) {
         $params['endTime'] = Cleaner::sanitize('time', $params['endTime']);
         if ($params['endTime'] == '') {
             unset($params['endTime']);
         }
     }
     $params['projectId'] = (int) $params['projectId'];
     $params['notes'] = Cleaner::sanitize('string', $params['notes']);
     if (isset($params['endTime']) && isset($params['startDatetime'])) {
         $params['minutes'] = Timecard_Models_Timecard::getDiffTime($params['endTime'], substr($params['startDatetime'], 11));
     } else {
         if (!isset($params['endTime'])) {
             $params['minutes'] = 0;
         } else {
             $params['minutes'] = Timecard_Models_Timecard::getDiffTime($params['endTime'], substr($model->startDatetime, 11));
         }
     }
     return $params;
 }
Exemplo n.º 23
0
 /**
  * Sanitize all the parsams.
  *
  * @return array Array with the form values.
  */
 private function _setParams()
 {
     return array('serverType' => Cleaner::sanitize('string', $this->getRequest()->getParam('serverType')), 'dbHost' => Cleaner::sanitize('string', $this->getRequest()->getParam('dbHost')), 'dbUser' => Cleaner::sanitize('string', $this->getRequest()->getParam('dbUser')), 'dbPass' => Cleaner::sanitize('string', $this->getRequest()->getParam('dbPass')), 'dbName' => Cleaner::sanitize('string', $this->getRequest()->getParam('dbName')), 'adminPass' => Cleaner::sanitize('string', $this->getRequest()->getParam('adminPass')), 'adminPassConfirm' => Cleaner::sanitize('string', $this->getRequest()->getParam('adminPassConfirm')), 'testPass' => Cleaner::sanitize('string', $this->getRequest()->getParam('testPass')), 'testPassConfirm' => Cleaner::sanitize('string', $this->getRequest()->getParam('testPassConfirm')), 'migrationConfigFile' => Cleaner::sanitize('string', $this->getRequest()->getParam('migrationConfigFile')), 'diffToUtc' => Cleaner::sanitize('integer', $this->getRequest()->getParam('diffToUtc')), 'useExtraData' => (int) $this->getRequest()->getParam('useExtraData'));
 }
Exemplo n.º 24
0
 /**
  * Deletes a file and then renders the upload.phtml template.
  *
  * This function draws the upload field in the form.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string  <b>moduleName</b> Current module name.
  *  - string  <b>field</b>      Name of the field in the module.
  *  - integer <b>id</b>         Id of the current item.
  *  - integer <b>order</b>      Position of the file (Can be many uploaded files in the same field).
  * </pre>
  *
  * @return void
  */
 public function fileDeleteAction()
 {
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', 'Project'));
     $field = Cleaner::sanitize('alnum', $this->getRequest()->getParam('field', null));
     $itemId = (int) $this->getRequest()->getParam('id', null);
     $order = (int) $this->getRequest()->getParam('order', 0);
     $this->getResponse()->clearHeaders();
     $this->getResponse()->clearBody();
     $linkBegin = Phprojekt::getInstance()->getConfig()->webpath . 'index.php/Default/File/';
     $model = Phprojekt_Loader::getModel($module, $module);
     $this->_fileCheckParamField($model, $field);
     $this->_fileCheckWritePermission($model, $itemId);
     $filesIn = explode('||', $_SESSION['uploadedFiles_' . $field]);
     $this->_fileCheckParamOrder($order, count($filesIn));
     // Delete the file name and md5 from the string
     $filesOut = '';
     $i = 1;
     foreach ($filesIn as $file) {
         if ($i != $order) {
             if ($filesOut != '') {
                 $filesOut .= '||';
             }
             $filesOut .= $file;
         } else {
             // Delete the file from the server
             $md5Name = substr($file, 0, strpos($file, '|'));
             $fileAbsolutePath = Phprojekt::getInstance()->getConfig()->uploadPath . $md5Name;
             if (preg_match("/^[A-Fa-f0-9]{32,32}\$/", $md5Name) && file_exists($fileAbsolutePath)) {
                 unlink($fileAbsolutePath);
             }
         }
         $i++;
     }
     $_SESSION['uploadedFiles_' . $field] = $filesOut;
     $this->_fileRenderView($linkBegin, $module, $itemId, $field, $filesOut, true);
 }
Exemplo n.º 25
0
 /**
  * Collect all the js files in the module folder, and return it as one.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string <b>name</b> Name of the module to consult.
  * </pre>
  *
  * @return void
  */
 public function moduleAction()
 {
     $scripttext = '';
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('name', null));
     $module = ucfirst(str_replace(" ", "", $module));
     // Load the module
     if (is_dir(PHPR_USER_CORE_PATH . $module . '/Views/dojo/scripts/')) {
         $scripts = scandir(PHPR_USER_CORE_PATH . $module . '/Views/dojo/scripts/');
     } else {
         $scripts = array();
     }
     $scripttext .= $this->_getModuleScripts(PHPR_USER_CORE_PATH, $scripts, $module);
     $scripttext .= '
         phpr.pageManager.deregister(\'' . $module . '\');
         phpr.pageManager.register(
             new phpr.' . $module . '.Main()
         );
     ';
     $this->_send($this->_collectTemplates() . $scripttext);
 }
Exemplo n.º 26
0
 /**
  * Executes the login by json using the username and password.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string <b>username</b> Username for login.
  *  - string <b>password</b> Password for login.
  * </pre>
  *
  * The return is a string in JSON format with:
  * <pre>
  *  - type    => 'success' or 'error'.
  *  - message => Success or error message.
  * </pre>
  *
  * @return void
  */
 public function jsonLoginAction()
 {
     $username = Cleaner::sanitize('xss', $this->getRequest()->getParam('username', null));
     $password = Cleaner::sanitize('xss', $this->getRequest()->getParam('password', null));
     try {
         $success = Phprojekt_Auth::login($username, $password);
         if ($success === true) {
             $return = array('type' => 'success', 'message' => '');
         }
     } catch (Phprojekt_Auth_Exception $error) {
         $return = array('type' => 'error', 'message' => $error->getMessage());
     }
     $this->_helper->viewRenderer->setNoRender();
     $this->view->clearVars();
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 27
0
 /**
  * Collect all the js files in the module folder, and return it as one.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string <b>name</b> Name of the module to consult.
  * </pre>
  *
  * @return void
  */
 public function moduleAction()
 {
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('name', null));
     $module = ucfirst(str_replace(" ", "", $module));
     // Load the module
     if (is_dir(PHPR_CORE_PATH . '/' . $module . '/Views/dojo/scripts/')) {
         $scripts = scandir(PHPR_CORE_PATH . '/' . $module . '/Views/dojo/scripts/');
     } else {
         $scripts = array();
     }
     echo 'dojo.registerModulePath' . '("phpr.' . $module . '", "../../../application/' . $module . '/Views/dojo/scripts");';
     echo $this->_getModuleScripts($scripts, $module);
     // Preload the templates and save them into __phpr_templateCache
     foreach ($this->_templates as $templateData) {
         $content = str_replace("'", "\\" . "'", $templateData['contents']);
         $content = str_replace("<", "<' + '", $content);
         echo '
             __phpr_templateCache["phpr.' . $templateData['module'] . '.template.' . $templateData['name'] . '"] = \'' . $content . '\';';
     }
     echo '
         this.' . $module . ' = new phpr.' . $module . '.Main();
     ';
 }
Exemplo n.º 28
0
 /**
  * Saves the settings for one module.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string <b>moduleName</b>              Name of the module.
  *  - mixed  <b>all other module fields</b> All the fields values to save.
  * </pre>
  *
  * The return is a string in JSON format with:
  * <pre>
  *  - type    => 'success' or 'error'.
  *  - message => Success or error message.
  *  - code    => 0.
  *  - id      => 0.
  * </pre>
  *
  * @throws Phprojekt_PublishedException On error in the action save or wrong id.
  *
  * @return void
  */
 public function jsonSaveAction()
 {
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', null));
     $this->setCurrentProjectId();
     $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting');
     $setting->setModule($module);
     $message = $setting->validateSettings($this->getRequest()->getParams());
     if (!empty($message)) {
         $type = "error";
     } else {
         $message = Phprojekt::getInstance()->translate(self::EDIT_TRUE_TEXT);
         $setting->setSettings($this->getRequest()->getParams());
         $type = "success";
     }
     $return = array('type' => $type, 'message' => $message, 'code' => 0, 'id' => 0);
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 29
0
 /**
  * Sanitizes an item in the wrapped scope to a certain type.
  *
  * @param string  $type     Type of parameter/item to sanitize.
  * @param string  $name     Name of parameter / Name of item in scope.
  * @param mixed   $default  Return value, if parameter/item is null/empty/...
  * @param boolean $empty    Must parameter/item be not null or empty.
  * @param object  $messages Messages generated while sanitizing.
  *
  * @return mixed Sanitized value.
  */
 public function sanitize($type, $name, $default = null, $empty = false, $messages = null)
 {
     $value = isset($this->_scope[$name]) ? $this->_scope[$name] : null;
     return Cleaner::sanitize($type, $value, $default, $empty, $messages);
 }