Exemplo n.º 1
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.º 2
0
 public function __construct()
 {
     if (isset(self::$current)) {
         throw new ConstructionException('Cannot construct more than one instance of singleton class Cleaner.');
     }
     self::$current = $this;
 }
Exemplo n.º 3
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.º 4
0
/**
 * Cleaner execution hook.
 */
function hook_cleaner_run()
{
    // Watchdog.
    if (variable_get('cleaner_empty_watchdog', FALSE)) {
        Cleaner::cleanerWatchdogClear();
    }
    // Cache.
    if (variable_get('cleaner_clear_cache', FALSE)) {
        Cleaner::cleanerCacheClear();
    }
    // Sessions.
    if (variable_get('cleaner_clean_sessions', 0)) {
        Cleaner::cleanerSessionsClear();
    }
    // CSS.
    if (variable_get('cleaner_clean_cssdir', FALSE)) {
        Cleaner::cleanerCssClear();
    }
    // JS.
    if (variable_get('cleaner_clean_jsdir', FALSE)) {
        Cleaner::cleanerJsClear();
    }
    // MySQL optimizing.
    if ($opt = variable_get('cleaner_optimize_db', FALSE)) {
        Cleaner::cleanerMysqlOptimizing($opt);
    }
}
 public function __construct(array $additional_uri_arguments)
 {
     //	Input
     //
     //		Request array
     //
     $request_parameters = $_REQUEST;
     $this->additional_uri_arguments = $additional_uri_arguments;
     //		JSON input
     //
     $posted_parameters = file_get_contents("php://input");
     if (isset($posted_parameters)) {
         $decoded_parameters = json_decode($posted_parameters, true);
         if (isset($decoded_parameters) && is_array($decoded_parameters)) {
             $request_parameters = array_merge($request_parameters, $decoded_parameters);
         }
     }
     //	Clean input
     //
     foreach ($request_parameters as $key => $value) {
         Cleaner::cleanInput($value);
     }
     foreach ($this->additional_uri_arguments as $value) {
         Cleaner::cleanInput($value);
     }
     //	Set property
     //
     $this->variables_array = $request_parameters;
     //  Notification controller
     //
     $this->notificationController = new NotificationController();
 }
Exemplo n.º 6
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.º 7
0
 protected function action()
 {
     try {
         Cleaner::pack();
     } catch (\Exception $e) {
         \Extasy\Audit\Record::add(__CLASS__, $e->getMessage(), $e);
     }
     $job = new CleanerJob();
     $job->actionDate->setTime('+1 hour');
     $job->insert();
 }
 public static function cleanInput($input)
 {
     $clean_input = array();
     if (is_array($input)) {
         foreach ($input as $key => $value) {
             $clean_input[$key] = Cleaner::cleanInput($value);
         }
     } else {
         $clean_input = trim(strip_tags($input));
     }
     return $clean_input;
 }
 static function changePassword($userToChange, $dirtyUpdatedPassword)
 {
     //Recieves new password. hashes with Salt. Updates database with new password.
     $mysqli = DB::getInstance();
     $cleanUpdatedPassword = Cleaner::cleanVar($dirtyUpdatedPassword);
     //creates long, random salt:
     $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
     $newSalt = mcrypt_create_iv($size);
     //hashes our cleaned password with added salt:
     $safeUpdatedPassword = hash("sha512", "{$newSalt}" . "{$cleanUpdatedPassword}");
     $queryChangePassword = "******" . $safeUpdatedPassword . "', salt='" . $newSalt . "'\n\t\tWHERE users.id=" . $userToChange . ";\n\t\t";
     $mysqli->query($queryChangePassword);
 }
Exemplo n.º 10
0
 static function showSingleGoal($dirtyGoalID, $dirtyUserID)
 {
     // takes POST about goalID and session userID and shows goal that contains both from database.
     $cleanGoalID = Cleaner::cleanVar($dirtyGoalID);
     $cleanUserID = Cleaner::cleanVar($dirtyUserID);
     $mysqli = DB::getInstance();
     $query = "\n\t\t\tSELECT content.*, goals_use_content.id as 'connection_id', goals.id as 'goal_id', goals.goal, goals.subject as 'goal_subject', goals.year as 'goal_year', goals.user_id as 'goal_user_id'\n\t\t\tfrom goals\n\t\t\tleft join goals_use_content\n\t\t\ton goals.id = goals_use_content.goal_id\n\t\t\tleft join content\n\t\t\ton goals_use_content.content_id = content.id\n\t\t\twhere goals.user_id = '" . $cleanUserID . "'\n\t\t\tand goals.id = '" . $cleanGoalID . "'\n\t\t";
     $result = $mysqli->query($query);
     $array = array();
     while ($row = $result->fetch_assoc()) {
         $array[] = $row;
     }
     return ['items' => $array, 'goal' => $array[0]['goal'], 'goal_subject' => $array[0]['goal_subject'], 'goal_year' => $array[0]['goal_year'], 'goal_id' => $array[0]['goal_id']];
 }
Exemplo n.º 11
0
 static function showConnectedContent($dirtyGoalID, $dirtyUserID)
 {
     // takes POST about goalID and userID and shows the content that has both values
     $cleanGoalID = Cleaner::cleanVar($dirtyGoalID);
     $cleanUserID = Cleaner::cleanVar($dirtyUserID);
     $mysqli = DB::getInstance();
     $queryConnections = "\n\t\tSELECT *\n\t\tFROM content, goals_use_content\n\t\tWHERE content.id = goals_use_content.content_id\n\t\tAND goals_use_content.goal_id = '" . $cleanGoalID . "'\n\t\tHAVING goals_use_content.user_id = '" . $cleanUserID . "'\n\t\tORDER BY content.timestamp DESC\n\t\t";
     $resultConnections = $mysqli->query($queryConnections);
     $array = array();
     while ($rowConnections = $resultConnections->fetch_assoc()) {
         $array[] = $rowConnections;
     }
     return $array;
 }
Exemplo n.º 12
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);
 }
 public static function propertyIsValid($property_name, &$property_value, &$error)
 {
     if (!parent::propertyIsValid($property_name, $property_value, $error)) {
         return false;
     }
     if ($property_name === CONFINED_DATE_START || $property_name === CONFINED_DATE_END) {
         //	Check the data is an array of strings
         //
         $property_value = Cleaner::cleanISO8601String($property_value);
         if (!UniversallyUniqueObject::propertyIsValid(UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_CREATED, $property_value, $error)) {
             return false;
         }
     }
     return true;
 }
Exemplo n.º 14
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;
 }
 public static function propertyIsValid($property_name, &$property_value, &$error)
 {
     if ($property_name === UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_CREATED || $property_name === UNIVERSALLY_UNIQUE_OBJECT_KEY_DATE_UPDATED) {
         //	Date Created / Date Updated
         //
         //		Clean the entered string
         //
         $property_value = Cleaner::cleanISO8601String($property_value);
         try {
             new DateTime($property_value);
         } catch (Exception $exception) {
             //	Property is invalid
             //
             $error = Error::withDomain(VALIDATION_ERROR_DOMAIN, VALIDATION_ERROR_CODE_INVALID_PROPERTY, 'The date should be a string in ISO-8601 format. Date given: ' . $property_value);
             return false;
         }
     }
     return true;
 }
Exemplo n.º 16
0
 public function get_controller()
 {
     if (SITE_AVAILABLE) {
         $controllers_array = Gbl::get('controllers_array');
         if (!empty($this->up[0]) && Cleaner::sanitized(CTYPE_ARRAY, $this->up[0], array_keys($controllers_array))) {
             $controller_name = $controllers_array[$this->up[0]];
         } else {
             # we are running from the default page of the site, so pass the default back
             $controller_name = Gbl::get('default_controller');
         }
     } else {
         $controller_name = 'MaintenanceController';
     }
     # do we have to include the code for the controller?
     if (!is_object($controller_name)) {
         require_once CONTROLLERS_PATH . '/' . $controller_name . '.lib.php';
     }
     return new $controller_name();
 }
Exemplo n.º 17
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.º 18
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.º 19
0
 /**
  * EventResource type can be one of the following
  *
  * - Calls
  * - Conferences
  * - Messages
  * - Recordings
  * 
  */
 public function __construct(&$object, $data)
 {
     $data = Ensure::Input($data);
     $args = Cleaner::Omit($data->get());
     $type = $args['eventType'];
     $splits = explode("-", $type);
     $class = __CLASS__;
     $object->eventType = $type;
     /**
      * when we're called directly as 
      * a sub class we should get our input first.
      *
      * i.e
      * call_event = new CallEvent;
      *
      * this is only when the user knows which
      * event should be triggered in his program.
      */
     /** conferences use hyphens **/
     /** i.e speak-conference **/
     if (sizeof($splits) > 1) {
         $g = "";
         foreach ($splits as $s) {
             $g .= ucwords($g);
         }
         $class = "Catapult\\" . "Conference" . $g . "Event";
         return $object->model = new Conference($args['id']);
     }
     /** sms is singular and does not use any other term, use Message here **/
     if ($type == "sms") {
         return $object->model = new Message($args['id']);
     }
     if (in_array($type, array("incoming", "hangup", "answer", "speak", "recording", "dtmf", "gather"))) {
         $cl = "Catapult\\" . ucwords($type) . "CallEvent";
         return $object->model = new Call($args['id']);
     }
     throw new \CatapultApiException("EventType was not found in list of events");
 }
Exemplo n.º 20
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.º 21
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.º 22
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.º 23
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.º 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
 public function GetBool($key)
 {
     try {
         $val = Cleaner::Bool($this->keyer->Get($key));
         $this->keyer->Set($key, $val);
         return $val;
     } catch (\phalanx\base\UndefinedKeyException $e) {
         return NULL;
     }
 }
Exemplo n.º 26
0
 public static function search_users($q)
 {
     $cleaner = new Cleaner();
     $cleaned_array = $cleaner->parseString($q);
     $stemmed_array = array_map('PorterStemmer::Stem', $cleaned_array);
     $users = User::with('metadata')->distinct();
     $users = $users->where(function ($query) use($stemmed_array) {
         $query->where('username', 'LIKE', '%' . array_get($stemmed_array, 0) . '%');
         for ($i = 1; $i < count($stemmed_array); $i++) {
             $query->or_where('username', 'LIKE', '%' . array_get($stemmed_array, $i) . '%');
         }
     });
     $users = $users->or_where(function ($query) use($stemmed_array) {
         $query->where('email', 'LIKE', '%' . array_get($stemmed_array, 0) . '%');
         for ($i = 1; $i < count($stemmed_array); $i++) {
             $query->or_where('email', 'LIKE', '%' . array_get($stemmed_array, $i) . '%');
         }
     });
     $users = $users->order_by('created_at', 'DESC');
     $users = $users->paginate(Config::get('smarttoys.records_per_page'));
     return array(implode(' ', $cleaned_array), $users);
 }
Exemplo n.º 27
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.º 28
0
 /**
  * Saves the new values of the projects dates.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - array <b>projects</b> Array with projectId,startDate and endDate by comma separated
  * </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      => 0.
  * </pre>
  *
  * @throws Phprojekt_PublishedException On error in the action save or wrong parameters.
  *
  * @return void
  */
 public function jsonSaveAction()
 {
     $projects = (array) $this->getRequest()->getParam('projects', array());
     $activeRecord = Phprojekt_Loader::getModel('Project', 'Project');
     $rights = Phprojekt_Loader::getLibraryClass('Phprojekt_Item_Rights');
     $userId = Phprojekt_Auth::getUserId();
     $this->setCurrentProjectId();
     // Error check: no project received
     if (empty($projects)) {
         $label = Phprojekt::getInstance()->translate('Projects');
         $message = Phprojekt::getInstance()->translate('No project info was received');
         throw new Phprojekt_PublishedException($label . ': ' . $message);
     }
     foreach ($projects as $project) {
         list($id, $startDate, $endDate) = explode(",", $project);
         // Check: are the three values available?
         if (empty($id) || empty($startDate) || empty($endDate)) {
             $label = Phprojekt::getInstance()->translate('Projects');
             $message = Phprojekt::getInstance()->translate('Incomplete data received');
             throw new Phprojekt_PublishedException($label . ': ' . $message);
         }
         $id = (int) $id;
         $activeRecord->find($id);
         // Check: project id exists?
         if (empty($activeRecord->id)) {
             $label = Phprojekt::getInstance()->translate('Project');
             $message = Phprojekt::getInstance()->translate('Id not found #') . $id;
             throw new Phprojekt_PublishedException($label . ': ' . $message);
         }
         // Check: dates are valid?
         $validStart = Cleaner::validate('date', $startDate, false);
         $validEnd = Cleaner::validate('date', $endDate, false);
         if (!$validStart || !$validEnd) {
             $label = Phprojekt::getInstance()->translate('Project id #') . $id;
             if (!$validStart) {
                 $message = Phprojekt::getInstance()->translate('Start date invalid');
             } else {
                 $message = Phprojekt::getInstance()->translate('End date invalid');
             }
             throw new Phprojekt_PublishedException($label . ': ' . $message);
         }
         // Check: start date after end date?
         $startDateTemp = strtotime($startDate);
         $endDateTemp = strtotime($endDate);
         if ($startDateTemp > $endDateTemp) {
             $label = Phprojekt::getInstance()->translate('Project id #') . $id;
             $message = Phprojekt::getInstance()->translate('Start date can not be after End date');
             throw new Phprojekt_PublishedException($label . ': ' . $message);
         }
         $activeRecord->startDate = $startDate;
         $activeRecord->endDate = $endDate;
         if ($rights->getItemRight(1, $id, $userId) >= Phprojekt_Acl::WRITE) {
             $activeRecord->parentSave();
         }
     }
     $message = Phprojekt::getInstance()->translate(self::EDIT_MULTIPLE_TRUE_TEXT);
     $return = array('type' => 'success', 'message' => $message, 'code' => 0, 'id' => 0);
     Phprojekt_Converter_Json::echoConvert($return);
 }
Exemplo n.º 29
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']);
 }
<?php

require __DIR__ . '/../src/Cleaner.php';
set_exception_handler(function ($e) {
    echo "ERROR: {$e->getMessage()}\n";
    exit(1);
});
$cleaner = new Cleaner();
$cleaner->clean();