Esempio n. 1
0
 protected function processUpload(ModelInterface $model)
 {
     /* @var $request \Phalcon\Http\Request */
     $request = $model->getDI()->getRequest();
     if ($request->hasFiles(true)) {
         foreach ($request->getUploadedFiles() as $file) {
             if ($file->getKey() != $this->imageField || !in_array($file->getType(), $this->allowedFormats)) {
                 continue;
             }
             $uniqueFileName = time() . '-' . uniqid() . '.' . strtolower($file->getExtension());
             if (!file_exists($this->uploadPath)) {
                 mkdir($this->uploadPath, 0755, true);
             }
             $file_name = rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $uniqueFileName;
             if (!$file->moveTo($file_name)) {
                 if (!(file_exists($file->getTempName()) && copy($file->getTempName(), $file_name))) {
                     return $this;
                 }
             }
             $model->writeAttribute($this->imageField, $uniqueFileName);
             // Delete old file
             $this->processDelete();
         }
     }
 }
Esempio n. 2
0
 /**
  * Returns validation record messages which stop the transaction
  *
  * @return \Phalcon\Mvc\Model\MessageInterface[]
  */
 public function getRecordMessages()
 {
     if (is_null($this->_record) === false) {
         return $this->_record->getMessages();
     }
     return $this->getMessage();
 }
Esempio n. 3
0
 /**
  * @param \Phalcon\Mvc\ModelInterface $model
  * @return \Phalcon\Db\AdapterInterface
  */
 public function getWriteConnection($model)
 {
     if ($this->getDI()->offsetExists($model->getWriteConnectionService())) {
         $this->setWriteConnectionService($model, $model->getWriteConnectionService());
     } elseif ($this->getDI()->getDbMaster()) {
         $this->setWriteConnectionService($model, 'dbMaster');
     }
     return parent::getWriteConnection($model);
 }
 /**
  * @param ModelInterface $model
  * @param array $rawBody
  * @return \Phalcon\Http\ResponseInterface
  */
 public function modelBadRequest(ModelInterface $model, $rawBody)
 {
     $errors = [];
     foreach ($model->getMessages() as $message) {
         $errors[] = $message->getMessage();
     }
     $response = $this->getResponse();
     $response->setStatusCode(Response::HTTP_STATUS_BAD_REQUEST, 'Bad Request');
     $response->setApiJsonEncode(['code' => Response::HTTP_STATUS_BAD_REQUEST, 'error' => $errors, 'received' => $rawBody]);
     return $response;
 }
 /**
  * @param \Phalcon\Mvc\ModelInterface $model
  *
  * @throws Exception
  */
 public function delete(\Phalcon\Mvc\ModelInterface $model)
 {
     $eventsManager = $this->getEventsManager();
     if ($eventsManager instanceof \Phalcon\Events\ManagerInterface) {
         $eventsManager->fire("search:beforeDelete", $this);
     }
     $response = $this->elasticsearch->delete(["index" => $this->index, "type" => $model->getSource(), "id" => $this->getPrimaryKeyValue($model)]);
     if ($eventsManager instanceof \Phalcon\Events\ManagerInterface) {
         $eventsManager->fire("search:afterDelete", $this);
     }
     return $response;
 }
Esempio n. 6
0
 public function validate(ModelInterface $record)
 {
     $field = $this->getOption('field');
     if (false === is_string($field)) {
         throw new Exception('Field name must be a string');
     }
     $fieldValue = $record->readAttribute($field);
     $value = preg_replace('/[^\\d]/', '', $fieldValue);
     if ($this->isSetOption('type')) {
         $type = $this->getOption('type');
         $result = true;
         switch ($type) {
             case CardNumber::AMERICAN_EXPRESS:
                 $issuer = substr($value, 0, 2);
                 $result = true === in_array($issuer, array(34, 37));
                 break;
             case CardNumber::MASTERCARD:
                 $issuer = substr($value, 0, 2);
                 $result = true === in_array($issuer, array(51, 52, 53, 54, 55));
                 break;
             case CardNumber::VISA:
                 $issuer = $value[0];
                 $result = $issuer == 4;
                 break;
             default:
                 throw new Exception('Incorrect type specifier');
         }
         if (false === $result) {
             $message = $this->getOption('message') ?: 'Credit card number is invalid';
             $this->appendMessage($message, $field, "CardNumber");
             return false;
         }
     }
     $value = strrev($value);
     $checkSum = 0;
     for ($i = 0; $i < strlen($value); $i++) {
         if ($i % 2 == 0) {
             $temp = $value[$i];
         } else {
             $temp = $value[$i] * 2;
             if ($temp > 9) {
                 $temp -= 9;
             }
         }
         $checkSum += $temp;
     }
     if ($checkSum % 10 != 0) {
         $message = $this->getOption('message') ?: 'Credit card number is invalid';
         $this->appendMessage($message, $field, "CardNumber");
         return false;
     }
     return true;
 }
 /**
  * {@inheritdoc}
  *
  * @param  \Phalcon\Mvc\ModelInterface $record
  * @return boolean
  */
 public function validate($record)
 {
     $field = $this->getOption('field');
     $fieldConfirmation = $this->getOption('field_confirmation');
     $fieldValue = $record->readAttribute($field);
     $fieldConfirmationValue = $record->readAttribute($fieldConfirmation);
     $message = $this->getOption('message') ? $this->getOption('message') : 'Both fields should contain equal values';
     if ($fieldConfirmationValue) {
         if ($fieldValue !== $fieldConfirmationValue) {
             $this->appendMessage($message, $fieldConfirmation, 'ConfirmationOf');
             return false;
         }
     }
     return true;
 }
Esempio n. 8
0
 /**
  * Returns the messages produced by a failed operation
  *
  * @return \Phalcon\Mvc\Model\MessageInterface[]
  */
 public function getMessages()
 {
     if (is_object($this->_model) === true) {
         return $this->_model->getMessages();
     }
     return array();
 }
Esempio n. 9
0
 private function cascadeDelete(ModelInterface $model)
 {
     $modelsManager = $model->getModelsManager();
     $hasManyRelations = $modelsManager->getHasMany($model);
     foreach ($hasManyRelations as $relation) {
         $relOptions = $relation->getOptions();
         $foreignKey = $relOptions['foreignKey'];
         if (isset($foreignKey['action']) && $foreignKey['action'] === Relation::ACTION_CASCADE) {
             $alias = $relOptions['alias'];
             $relatedModels = $model->{"get{$alias}"}();
             foreach ($relatedModels as $relModel) {
                 $relModel->delete();
             }
         }
     }
 }
Esempio n. 10
0
 public function validate(ModelInterface $record)
 {
     $field = $this->getOption('field');
     if (false === is_string($field)) {
         throw new Exception('Field name must be a string');
     }
     $value = $record->readAttribute($field);
     $version = $this->getOption('version') ?: FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6;
     $allowPrivate = $this->getOption('allowPrivate') ? 0 : FILTER_FLAG_NO_PRIV_RANGE;
     $allowReserved = $this->getOption('allowReserved') ? 0 : FILTER_FLAG_NO_RES_RANGE;
     $options = array('options' => array('default' => false), 'flags' => $version | $allowPrivate | $allowReserved);
     $result = filter_var($value, FILTER_VALIDATE_IP, $options);
     if (false === $result) {
         $message = $this->getOption('message') ?: 'IP address is incorrect';
         $this->appendMessage($message, $field, "IP");
     }
     return (bool) $result;
 }
 public function validate(\Phalcon\Mvc\ModelInterface $model)
 {
     $field = $this->getOption('field');
     $allowZero = $this->getOption('allowZero');
     $min = $this->getOption('min');
     $max = $this->getOption('max');
     $value = $model->{$field};
     $len = mb_strlen($value, 'utf-8');
     if ($len > $max || $len < $min) {
         if (!empty($value)) {
             $this->appendMessage("Длина поля \"{$model->getLabel($field)}\" должна быть от {$min} до {$max}", $field, "MaxMinValidator");
             return false;
         } elseif ($allowZero) {
             return true;
         }
     }
     return true;
 }
Esempio n. 12
0
 /**
  * @throws \Exception
  */
 public function missingMethod(ModelInterface $model, $method, $arguments = null)
 {
     if (!method_exists($this, $method)) {
         return null;
     }
     if (!$this->db) {
         if ($model->getDi()->has('db')) {
             $this->db = $model->getDi()->get('db');
         } else {
             throw new \Exception('Undefined database handler.');
         }
     }
     $this->setOwner($model);
     $result = call_user_func_array(array($this, $method), $arguments);
     if ($result === null) {
         return '';
     }
     return $result;
 }
Esempio n. 13
0
 /**
  * {@inheritdoc}
  *
  * @param $record
  *
  * @return boolean
  * @throws Exception
  */
 public function validate(ModelInterface $record)
 {
     $field = $this->getOption('field');
     if (false === is_string($field)) {
         throw new Exception('Field name must be a string');
     }
     $value = $record->readAttribute($field);
     if (true === $this->isSetOption('allowEmpty') && empty($value)) {
         return true;
     }
     if (false === $this->isSetOption('min') || false === $this->isSetOption('max')) {
         throw new Exception('A minimum and maximum must be set');
     }
     $maximum = $this->getOption('max');
     $minimum = $this->getOption('min');
     if ($value < $minimum || $value > $maximum) {
         // Check if the developer has defined a custom message
         $message = $this->getOption('message') ?: sprintf('%s is not between a valid range', $field);
         $this->appendMessage($message, $field, 'Between');
         return false;
     }
     return true;
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  *
  * @param $record
  * @return boolean
  * @throws Exception
  */
 public function validate(ModelInterface $record)
 {
     $field = $this->getOption('field');
     if (false === is_string($field)) {
         throw new Exception('Field name must be a string');
     }
     $value = $record->readAttribute($field);
     if (true === $this->isSetOption('allowEmpty') && empty($value)) {
         return true;
     }
     if (false === $this->isSetOption('places')) {
         throw new Exception('A number of decimal places must be set');
     }
     $places = $this->getOption('places');
     if ($this->isSetOption('digits')) {
         // Specific number of digits
         $digits = '{' . (int) $this->getOption('digits') . '}';
     } else {
         // Any number of digits
         $digits = '+';
     }
     if ($this->isSetOption('point')) {
         $decimal = $this->getOption('point');
     } else {
         // Get the decimal point for the current locale
         list($decimal) = array_values(localeconv());
     }
     $regexp = (bool) preg_match('#^[+-]?[0-9]' . $digits . preg_quote($decimal) . '[0-9]{' . (int) $places . '}$#', $value);
     if (!$regexp) {
         // Check if the developer has defined a custom message
         $message = $this->getOption('message') ?: sprintf('%s must contain valid decimal value', $field);
         $this->appendMessage($message, $field, 'Decimal');
         return false;
     }
     return true;
 }
Esempio n. 15
0
 /**
  * Audits an UPDATE operation
  *
  * @param  \Phalcon\Mvc\ModelInterface $model
  * @return boolean
  */
 public function auditAfterUpdate(ModelInterface $model)
 {
     $changedFields = $model->getChangedFields();
     if (count($changedFields) == 0) {
         return null;
     }
     //Create a new audit
     $audit = $this->createAudit('U', $model);
     //Date the model had before modifications
     $originalData = $model->getSnapshotData();
     $details = array();
     foreach ($changedFields as $field) {
         $auditDetail = new AuditDetail();
         $auditDetail->field_name = $field;
         $auditDetail->old_value = $originalData[$field];
         $auditDetail->new_value = $model->readAttribute($field);
         $details[] = $auditDetail;
     }
     $audit->details = $details;
     return $audit->save();
 }
Esempio n. 16
0
 /**
  * @param  \Phalcon\Mvc\ModelInterface $target
  * @param  int $key
  * @param  int $levelUp
  * @param  array $attributes
  *
  * @return boolean
  * @throws PMMException
  */
 private function addNode($target, $key, $levelUp, $attributes)
 {
     $owner = $this->getOwner();
     if (!$target) {
         throw new PMMException('The node cannot be inserted because target is not defined.');
     }
     if (!$this->getIsNewRecord()) {
         throw new PMMException('The node cannot be inserted because it is not new.');
     }
     if ($this->getIsDeletedRecord()) {
         throw new PMMException('The node cannot be inserted because it is deleted.');
     }
     if ($target->getIsDeletedRecord()) {
         throw new PMMException('The node cannot be inserted because target node is deleted.');
     }
     if ($owner == $target) {
         throw new PMMException('The target node should not be self.');
     }
     if (!$levelUp && $target->isRoot()) {
         throw new PMMException('The target node should not be root.');
     }
     if ($this->hasManyRoots) {
         $owner->{$this->rootAttribute} = $target->{$this->rootAttribute};
     }
     $this->shiftLeftRight($key, 2);
     $owner->{$this->leftAttribute} = $key;
     $owner->{$this->rightAttribute} = $key + 1;
     $owner->{$this->levelAttribute} = $target->{$this->levelAttribute} + $levelUp;
     $this->ignoreEvent = true;
     $result = $owner->create($attributes);
     $this->ignoreEvent = false;
     return $result;
 }
Esempio n. 17
0
 /**
  * Appends target to node as last child.
  *
  * @param \Phalcon\Mvc\ModelInterface $target the target.
  * @param array $attributes list of attributes.
  * @return boolean whether the appending succeeds.
  */
 public function append($target, $attributes = null)
 {
     return $target->appendTo($this->getOwner(), $attributes);
 }
Esempio n. 18
0
 /**
  * Audits an UPDATE operation
  *
  * @param  \Phalcon\Mvc\ModelInterface $model
  * @return boolean
  */
 public function auditAfterUpdate(ModelInterface $model)
 {
     $changedFields = $model->getChangedFields();
     if (count($changedFields) == 0) {
         return null;
     }
     //Create a new audit
     $audit = $this->createAudit('U', $model);
     if (is_object($audit)) {
         //Date the model had before modifications
         $originalData = $model->getSnapshotData();
         $details = [];
         $random = new Random();
         foreach ($changedFields as $field) {
             $auditDetail = new AuditDetail();
             $auditDetail->setId($random->uuid());
             $auditDetail->setFieldName($field);
             $auditDetail->setOldValue($originalData[$field]);
             $newValue = $model->readAttribute($field) ?: 'empty';
             $auditDetail->setNewValue($newValue);
             $details[] = $auditDetail;
         }
         $audit->details = $details;
         if (!$audit->save()) {
             ModelBase::saveLoger($audit->getMessages());
         }
     }
 }
Esempio n. 19
0
 /**
  * @param  ModelInterface $target
  * @param  int $key
  * @param  int $levelUp
  * @param  array $attributes
  *
  * @return boolean
  * @throws \Exception
  */
 private function addNode(ModelInterface $target, $key, $levelUp, array $attributes = null)
 {
     $owner = $this->getOwner();
     if (!$this->getIsNewRecord()) {
         throw new Exception('The node cannot be inserted because it is not new.');
     }
     if ($this->getIsDeletedRecord()) {
         throw new Exception('The node cannot be inserted because it is deleted.');
     }
     if ($target->getIsDeletedRecord()) {
         throw new Exception('The node cannot be inserted because target node is deleted.');
     }
     if ($owner == $target) {
         throw new Exception('The target node should not be self.');
     }
     if (!$levelUp && $target->isRoot()) {
         throw new Exception('The target node should not be root.');
     }
     if ($this->hasManyRoots) {
         $owner->{$this->rootAttribute} = $target->{$this->rootAttribute};
     }
     $db = $this->getDbHandler($owner);
     $db->begin();
     try {
         $this->ignoreEvent = true;
         $this->shiftLeftRight($key, 2);
         $this->ignoreEvent = false;
         $owner->{$this->leftAttribute} = $key;
         $owner->{$this->rightAttribute} = $key + 1;
         $owner->{$this->levelAttribute} = $target->{$this->levelAttribute} + $levelUp;
         $this->ignoreEvent = true;
         $result = $owner->create($attributes);
         $this->ignoreEvent = false;
         if (!$result) {
             $db->rollback();
             $this->ignoreEvent = false;
             return false;
         }
         $db->commit();
     } catch (\Exception $e) {
         $db->rollback();
         $this->ignoreEvent = false;
         throw $e;
     }
     return true;
 }
Esempio n. 20
0
 protected function processUpload($media, ModelInterface $model)
 {
     $request = $model->getDI()->getRequest();
     if (true == $request->hasFiles(true)) {
         foreach ($request->getUploadedFiles() as $file) {
             $key = $file->getKey();
             $type = $file->getType();
             // Check extension allowed
             if (!in_array($type, $this->allowedFormats)) {
                 throw new \Exception(sprintf('File %s has invalid extension. Allowable only: %s', $file->getName(), str_replace('image/', ' ', implode(',', $this->allowedFormats))));
             }
             // Check allowed min size
             $this->checkMinSize($file, $this->allowMinSize);
             // Check allowed max size
             $this->checkMaxsize($file, $this->allowMaxSize);
             // Create full path image
             $fullPath = rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath;
             // Check upload directory
             if (is_writable($fullPath) === false) {
                 throw new \Exception(sprintf('The specified directory %s is not writable', $fullPath));
             }
             if ($key != $this->imageField) {
                 continue;
             }
             $uniqueFileName = md5($file->getName()) . '-' . uniqid() . '.' . strtolower($file->getExtension());
             $fullPath .= $uniqueFileName;
             if ($file->moveTo($fullPath)) {
                 $model->writeAttribute($this->imageField, $this->datePath . $uniqueFileName);
                 // Resize images big
                 $myImageResize = new ImageResize(rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath, $uniqueFileName, rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath, $uniqueFileName, $media->imageMaxWidth, $media->imageMaxHeight, '', $media->imageQuality);
                 $myImageResize->output();
                 unset($myImageResize);
                 // Resize images medium
                 $nameMediumPart = substr($uniqueFileName, 0, strrpos($uniqueFileName, '.'));
                 $nameMedium = $nameMediumPart . '-medium.' . strtolower($file->getExtension());
                 $myImageResize = new ImageResize(rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath, $uniqueFileName, rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath, $nameMedium, $media->imageMediumWidth, $media->imageMediumHeight, '', $media->imageQuality);
                 $myImageResize->output();
                 unset($myImageResize);
                 // Resize images small
                 $nameThumbPart = substr($uniqueFileName, 0, strrpos($uniqueFileName, '.'));
                 $nameThumb = $nameThumbPart . '-small.' . strtolower($file->getExtension());
                 $myImageResize = new ImageResize(rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath, $uniqueFileName, rtrim($this->uploadPath, '/\\') . DIRECTORY_SEPARATOR . $this->datePath, $nameThumb, $media->imageThumbWidth, $media->imageThumbHeight, '', $media->imageQuality);
                 $myImageResize->output();
                 unset($myImageResize);
                 // Delete old file
                 $this->processDelete();
             }
         }
     }
     return $this;
 }
Esempio n. 21
0
 /**
  * @param Response       $response
  * @param ModelInterface $book
  */
 private function createErrorResponse(Response $response, ModelInterface $book)
 {
     $response->setStatusCode(409, "Conflict");
     $errors = [];
     foreach ($book->getMessages() as $message) {
         $errors[] = $message->getMessage();
     }
     $response->setJsonContent(['status' => 'ERROR', 'messages' => $errors]);
 }
Esempio n. 22
0
 /**
  * @param \Phalcon\Mvc\ModelInterface $user
  * @param string                      $newPassword
  * 
  * @return boolean
  */
 public function changePassword(\Phalcon\Mvc\ModelInterface $user, $newPassword)
 {
     $eventsManager = $this->getEventsManager();
     if ($eventsManager instanceof \Phalcon\Events\ManagerInterface) {
         if ($eventsManager->fire("auth:beforeChangePassword", $this) === false) {
             return false;
         }
     }
     $user->writeAttribute($this->passwordField, $this->getDI()->getShared("security")->hash($newPassword));
     $success = $user->update();
     if ($eventsManager instanceof \Phalcon\Events\ManagerInterface) {
         $eventsManager->fire("auth:afterChangePassword", $this);
     }
     return $success;
 }