Пример #1
0
 public function validate()
 {
     parent::validate();
     if ($this->from->getDate()->getTimestamp() > $this->until->getDate()->getTimestamp()) {
         throw new InvalidRangeException(Translate::t("The start date must be earlier than or equal to the end date."));
     }
 }
Пример #2
0
 public function createRequestObject($expectedObject, $rawRequest)
 {
     $result = null;
     if (substr($expectedObject, -2) === "[]") {
         if (!is_array($rawRequest)) {
             throw new InvalidObjectException(Translate::t("The request is expected to be an array."));
         }
         $result = [];
         foreach ($rawRequest as $rawRequestElem) {
             $result[] = $this->createRequestObject(substr($expectedObject, 0, -2), $rawRequestElem);
         }
     } else {
         $meta = $this->objectMetaService->getObjectMetas($expectedObject);
         $expectsScalar = $meta->get("Object")->get("scalar");
         if ($expectsScalar) {
             if (!is_scalar($rawRequest)) {
                 throw new InvalidObjectException(Translate::t("The request is expected to be a scalar value."));
             }
             // we fill the scalar object, but only to see if it passes validation.
             // then we return the bare request
             $object = $this->createObject($expectedObject);
             $object->set("_", $rawRequest);
             $object->validate();
             $result = $rawRequest;
         } else {
             $result = $this->createObject($expectedObject);
             if (is_object($rawRequest)) {
                 $this->fill($result, $rawRequest);
             }
             $result->validate();
         }
     }
     return $result;
 }
Пример #3
0
 public function getFormatter($extension)
 {
     if (!$this->formatExists($extension)) {
         throw new FormatterNotFoundException(Translate::t("The requested format is not supported."));
     }
     return $this->formatters[$extension];
 }
 public function registerSeed(SeedEvent $event)
 {
     $capabilities = [["id" => "entity.setting.read", "name" => Translate::noopX("user capability", "Load settings")], ["id" => "entity.setting.write", "name" => Translate::noopX("user capability", "Save settings")]];
     foreach ($capabilities as $capability) {
         $event->addSeedEntry("AgitUserBundle:UserCapability", $capability);
     }
 }
Пример #5
0
 public function delete($id)
 {
     if (!$this instanceof AbstractEntityController) {
         throw new InternalErrorException("This trait must be used in children of the AbstractEntityController.");
     }
     $this->checkPermissions($id, __FUNCTION__);
     try {
         $this->getEntityManager()->beginTransaction();
         $entity = $this->retrieveEntity($this->getEntityClass(), $id);
         if (!$entity instanceof DeletableInterface) {
             throw new InternalErrorException("Only entities which implement the DeletableInterface can be deleted here.");
         }
         if ($entity->isDeleted()) {
             throw new BadRequestException(Translate::t("This entity is already deleted."));
         }
         $entity->setDeleted(true);
         $this->getEntityManager()->persist($entity);
         $this->getEntityManager()->flush();
         $this->getLogger()->log(LogLevel::INFO, "agit.api.entity", sprintf(Translate::tl("Object “%s” of type “%s” has been deleted."), $entity->getId(), $this->getEntityClassName($entity)), true);
         $this->getEntityManager()->commit();
     } catch (Exception $e) {
         $this->getEntityManager()->rollBack();
         throw $e;
     }
     return true;
 }
 public function registerSeed(SeedEvent $event)
 {
     $categories = ["agit.order" => Translate::noopX("logging category", "Order"), "agit.payment" => Translate::noopX("logging category", "Payment")];
     foreach ($categories as $id => $name) {
         $event->addSeedEntry("AgitLoggingBundle:LogentryCategory", ["id" => $id, "name" => $name]);
     }
 }
Пример #7
0
 public function registerSeed(SeedEvent $event)
 {
     $categories = ["agit.api" => Translate::noopX("logging category", "API"), "agit.api.entity" => Translate::noopX("logging category", "Entity API")];
     foreach ($categories as $id => $name) {
         $event->addSeedEntry("AgitLoggingBundle:LogentryCategory", ["id" => $id, "name" => $name]);
     }
 }
 protected function createFieldValue($typeMeta, $key, $value)
 {
     $result = null;
     $expectedType = $typeMeta->getType();
     if (is_scalar($value) || is_null($value) || $expectedType === "polymorphic") {
         $result = $value;
     } elseif (is_array($value)) {
         if ($typeMeta->isObjectType() && $typeMeta->isListType()) {
             $result = [];
             foreach ($value as $listValue) {
                 $childObj = $this->objectMetaService->createObject($typeMeta->getTargetClass());
                 $this->fill($childObj, $listValue);
                 $result[] = $childObj;
             }
         } elseif (in_array($expectedType, ["array", "entity", "entitylist"])) {
             $result = $value;
         } else {
             throw new InvalidObjectValueException(sprintf(Translate::t("Invalid value for the `%s` property."), $key));
         }
     } elseif (is_object($value)) {
         if ($expectedType === "map") {
             $result = (array) $value;
         } else {
             if (!$typeMeta->isObjectType()) {
                 throw new InvalidObjectValueException(sprintf(Translate::t("Invalid value for the `%s` property."), $key));
             }
             $result = $this->objectMetaService->createObject($typeMeta->getTargetClass());
             $this->fill($result, $value);
         }
     }
     return $result;
 }
Пример #9
0
 public function setLocale($locale)
 {
     if (!in_array($locale, $this->availableLocales)) {
         throw new InternalErrorException("The locale `{$locale}` is not available.");
     }
     Translate::_setLocale($locale);
     $this->currentLocale = $locale;
 }
 public function validateField($fieldName, $id, $value)
 {
     try {
         call_user_func_array([$this->validators[$id], 'validate'], array_slice(func_get_args(), 2));
     } catch (InvalidValueException $e) {
         throw new InvalidValueException(sprintf(Translate::t("Invalid value for %s: %s"), $fieldName, $e->getMessage()));
     }
 }
Пример #11
0
 public function validate($value)
 {
     $this->validationService->validate("array", $value);
     if (!count($value)) {
         throw new InvalidSettingValueException(Translate::t("You must select at least one user language."));
     }
     $this->validationService->validate("multiSelection", $value, $this->localeService->getAvailableLocales());
 }
 public function validate($value, $positiveInt = true)
 {
     if (!is_numeric($value)) {
         throw new InvalidValueException(Translate::t("The value must be numeric."));
     }
     if ($positiveInt === true && preg_match('|[^\\d]|', $value)) {
         throw new InvalidValueException(Translate::t("The value must be a positive integer number."));
     }
 }
Пример #13
0
 public function getUser($id)
 {
     $field = is_int($id) ? "id" : "email";
     $user = $this->entityManager->getRepository("AgitUserBundle:UserInterface")->findOneBy([$field => $id, "deleted" => 0]);
     if (!$user) {
         throw new UserNotFoundException(Translate::t("The requested user does not exist."));
     }
     return $user;
 }
Пример #14
0
 protected function checkForbiddenCharacters($value)
 {
     $forbiddenCharacters = ["<" => "<", "" => "null byte"];
     foreach ($forbiddenCharacters as $char => $name) {
         if (strpos($value, $char)) {
             throw new InvalidObjectValueException(sprintf(Translate::t("The “%s” character must not be contained."), $name));
         }
     }
 }
Пример #15
0
 public function paymentFailed(Payment $payment, $logMessage, array $logContext, $extra = "")
 {
     if ($payment->getStatus() === $payment::STATUS_OPEN) {
         $payment->setStatus($payment::STATUS_FAILED);
     }
     $this->persistPayment($payment);
     $this->eventDispatcher->dispatch("agit.payment.failed", new PaymentFailedEvent($payment, $logMessage, $logContext, $extra));
     throw new PaymentProcessorException(vsprintf(Translate::t($logMessage), $logContext));
 }
Пример #16
0
 public function validate($value)
 {
     if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
         throw new InvalidValueException(Translate::t("The e-mail address is malformed."));
     }
     // although technically valid, we don't accept e-mail adresses with capital letters
     if (strtolower($value) !== $value) {
         throw new InvalidValueException(Translate::t("The e-mail address must not contain capital letters."));
     }
 }
Пример #17
0
 public function registerPasswordReset($email, $password)
 {
     $user = $this->userService->getUser($email);
     $encPass = $this->userService->encodePassword($user, $password);
     $message = Swift_Message::newInstance()->setSubject(Translate::t("Password reset"))->setFrom([$this->mailFrom => "Customer Service"])->setReplyTo([$this->mailReplyto => "Customer Service"])->setTo([$user->getEmail() => $user->getName()]);
     $trigger = new TriggerData(["id" => $user->getId(), "encPass" => $encPass]);
     $token = $this->triggerService->createTrigger(self::TRIGGER_TAG, $trigger);
     $message->setBody($this->templatingService->render("AgitProfileBundle:Mail:passreset.txt.twig", ["name" => $user->getName(), "url" => $this->pageService->createUrl("/user/newpass") . "#!/confirm?{$token}"]), "text/plain");
     $this->mailerService->send($message);
 }
 public function validate($value, $possibleValues = [])
 {
     if (!is_array($value)) {
         throw new InvalidValueException(Translate::t("The value must be an array."));
     }
     foreach ($value as $val) {
         if (!in_array($val, $possibleValues)) {
             throw new InvalidValueException(sprintf(Translate::t("The value must be one of the following: “%s”."), implode(Translate::x("quotation inside collection", "”, “"), $possibleValues)));
         }
     }
 }
 public function validate($value, $min = null, $max = null)
 {
     if (!is_int($value)) {
         throw new InvalidValueException(Translate::t("The value must be an integer."));
     }
     if (is_int($min) && $value < $min) {
         throw new InvalidValueException(sprintf(Translate::t("The value is too low, it must be higher than %s."), $min));
     }
     if (is_int($max) && $value > $max) {
         throw new InvalidValueException(sprintf(Translate::t("The value is too high, it must be lower than %s."), $max));
     }
 }
Пример #20
0
 public function validate($value, $strict = true)
 {
     if (!filter_var($value, FILTER_VALIDATE_URL) || strpos($value, 'http') !== 0) {
         throw new InvalidValueException(Translate::t("The URL is invalid."));
     }
     $urlParts = parse_url($value);
     if (!$urlParts || !isset($urlParts['scheme']) || !isset($urlParts['host']) || !in_array($urlParts['scheme'], ['http', 'https']) || !preg_match("#^(([a-z]|[a-z][a-z0-9\\-]*[a-z0-9])\\.)*([a-z]|[a-z][a-z0-9\\-]*[a-z0-9])\$#i", $urlParts['host'])) {
         throw new InvalidValueException(Translate::t("The URL is invalid."));
     }
     if ($strict && (isset($urlParts['user']) || isset($urlParts['pass']) || isset($urlParts['port']))) {
         throw new InvalidValueException(Translate::t("The URL is malformed."));
     }
 }
Пример #21
0
 public function exceptionAction(Request $request, FlattenException $exception)
 {
     $status = $exception->getStatusCode();
     $message = $status && $status < 500 ? $exception->getMessage() : Translate::t("Sorry, there has been an internal error. The administrators have been notified and will fix this as soon as possible.");
     try {
         $reqDetails = $this->load($request);
         $pageDetails = $this->get("agit.page")->getPage("_exception");
         $response = $this->createResponse($pageDetails, $reqDetails, ["message" => $message]);
     } catch (Exception $e) {
         $response = $this->render("AgitPageBundle:Special:exception.html.twig", ["locale" => "en_GB", "message" => $message]);
     }
     $response->setStatusCode($status);
     $response->headers->set("X-Frame-Options", "SAMEORIGIN");
     return $response;
 }
 public function validate($pass1, $pass2 = null)
 {
     if (strlen($pass1) < 8) {
         throw new InvalidValueException(sprintf(Translate::t("The password must have at least %d characters."), 8));
     }
     if (!preg_match('|\\d|', $pass1) || !preg_match('|[a-z]|i', $pass1)) {
         throw new InvalidValueException(Translate::t("The password must contain at least one letter and one number."));
     }
     if (preg_match('|[^a-z0-9' . preg_quote($this->allowedSpecialChars, '|') . ']|i', $pass1)) {
         throw new InvalidValueException(sprintf(Translate::t("The password must only consist of letters, numbers and the characters %s."), $this->allowedSpecialChars));
     }
     if (!is_null($pass2) && $pass1 !== $pass2) {
         throw new InvalidValueException(Translate::t("Both passwords must be identical."));
     }
 }
 public function validate($value)
 {
     try {
         $this->arrayValidator->validate($value, 2);
         $lat = reset($value);
         $lon = end($value);
         $this->latitudeValidator->validate($lat);
         $this->longitudeValidator->validate($lon);
         if ($lat > -2 && $lat < 2 && $lon > -2 && $lon < 2) {
             throw new InvalidValueException(Translate::t("The location is off-shore."));
         }
     } catch (InvalidValueException $e) {
         throw new InvalidValueException(sprintf(Translate::t("The geographical location is invalid: %s"), $e->getMessage()));
     }
 }
Пример #24
0
 public function callAction(Request $request, $namespace, $class, $method, $_ext)
 {
     $time = microtime(true);
     $mem = memory_get_peak_usage(true);
     $eventDispatcher = $this->container->get("event_dispatcher");
     $response = new Response();
     $isDev = $this->container->getParameter("kernel.environment") === "dev";
     // we must init the variables we’re using for the success and error events
     $endpointName = $requestData = $resultData = null;
     try {
         $this->setLocale();
         $this->checkHeaderAuth($request);
         $formatter = $this->container->get("agit.api.formatter")->getFormatter($_ext);
         $endpointService = $this->container->get("agit.api.endpoint");
         $endpointName = "{$namespace}/{$class}.{$method}";
         $endpointMeta = $endpointService->getEndpointMetaContainer($endpointName);
         $controller = $endpointService->createEndpointController($endpointName);
         $requestObject = null;
         if (!$isDev && !$endpointMeta->get("Security")->get("allowCrossOrigin")) {
             $this->container->get("agit.api.csrf")->checkToken($this->getCsrfToken($request));
         }
         if ($request->getMethod() !== "OPTIONS") {
             $requestData = $this->createRequestObject($endpointMeta->get("Endpoint")->get("request"), $request->get("request"));
             $resultData = $controller->{$method}($requestData);
             $response = $formatter->createResponse($request, $resultData);
         }
         if ($endpointMeta->get("Security")->get("allowCrossOrigin")) {
             $response->headers->set("Access-Control-Allow-Origin", "*");
         }
         $eventDispatcher->dispatch("agit.api.request.success", new ApiRequestSuccessEvent($request, $response, $endpointName, $requestData, $resultData, microtime(true) - $time, memory_get_peak_usage(true) - $mem));
     } catch (Exception $e) {
         $publicException = $e instanceof AgitException && !$e instanceof InternalErrorException;
         $message = $isDev || $publicException ? $e->getMessage() : Translate::t("Sorry, there has been an internal error. The administrators have been notified and will fix this as soon as possible.");
         if (!$publicException && $this->container->has("logger")) {
             $this->container->get("logger")->log(LogLevel::ERROR, $e->getMessage(), [$e->getTraceAsString()]);
         }
         if ($isDev && !$publicException) {
             $message .= "\n\n" . $e->getTraceAsString();
         }
         $response->setContent($message);
         $response->setStatusCode($publicException ? $e->getStatusCode() : 500);
         $response->headers->set("Content-Type", "text/plain; charset=UTF-8", true);
         $eventDispatcher->dispatch("agit.api.request.error", new ApiRequestErrorEvent($request, $response, $endpointName, $requestData, $e, microtime(true) - $time, memory_get_peak_usage(true) - $mem));
     }
     $response->headers->set("Cache-Control", "no-cache, must-revalidate, max-age=0", true);
     $response->headers->set("Pragma", "no-store", true);
     return $response;
 }
 public function validate($object, array $properties = null, $onlyGivenProperties = true)
 {
     if (!is_object($object)) {
         throw new InvalidValueException(Translate::t("The value must be an object."));
     }
     if (!is_null($properties)) {
         $objectKeys = array_keys(get_object_vars($object));
         if ($onlyGivenProperties && count($objectKeys) !== count($properties)) {
             throw new InvalidValueException(Translate::t("The object has an invalid set of properties."));
         }
         foreach ($properties as $property) {
             if (!in_array($property, $objectKeys)) {
                 throw new InvalidValueException(sprintf(Translate::t("The object is missing the mandatory “%s” property."), $property));
             }
         }
     }
 }
Пример #26
0
 public function remove($id)
 {
     if (!$this instanceof AbstractEntityController) {
         throw new InternalErrorException("This trait must be used in children of the AbstractEntityController.");
     }
     $this->checkPermissions($id, __FUNCTION__);
     $entity = $this->retrieveEntity($this->getEntityClass(), $id);
     try {
         $this->getEntityManager()->beginTransaction();
         $this->getEntityManager()->remove($entity);
         $this->getEntityManager()->flush();
         $this->getLogger()->log(LogLevel::INFO, "agit.api.entity", sprintf(Translate::tl("Object %s of type %s has been removed permanently."), $entity->getId(), $this->getEntityClassName($entity)), true);
         $this->getEntityManager()->commit();
     } catch (Exception $e) {
         $this->getEntityManager()->rollBack();
         throw new BadRequestException(Translate::t("This object cannot be removed, because there are other objects depending on it."));
     }
 }
Пример #27
0
 public static function u($string, $locale = null)
 {
     if (!$locale) {
         $locale = Translate::getLocale();
     }
     $lang = substr($locale, 0, 2);
     $langs = self::multilangStringToArray($string);
     if (isset($langs[$lang])) {
         $newString = $langs[$lang];
     } elseif (isset($langs["en"])) {
         $newString = $langs["en"];
     } elseif (count($langs)) {
         $newString = reset($langs);
     } else {
         $newString = $string;
     }
     return $newString;
 }
Пример #28
0
 public function create(AbstractEntityObject $requestObject)
 {
     if (!$this instanceof AbstractEntityController) {
         throw new InternalErrorException("This trait must be used in children of the AbstractEntityController.");
     }
     $this->checkPermissions($requestObject, __FUNCTION__);
     $this->validate($requestObject);
     try {
         $this->getEntityManager()->beginTransaction();
         $className = $this->getEntityManager()->getClassMetadata($this->getEntityClass())->getName();
         $entity = $this->saveEntity(new $className(), $requestObject);
         $this->getLogger()->log(LogLevel::INFO, "agit.api.entity", sprintf(Translate::tl("New object %s of type %s has been created."), $entity->getId(), $this->getEntityClassName($entity)), true);
         $this->getEntityManager()->commit();
     } catch (Exception $e) {
         $this->getEntityManager()->rollBack();
         throw $e;
     }
     return $this->createObject($this->getResponseObjectApiClass(), $entity);
 }
 public function validate($value, $minLength = null, $maxLength = null, $allowLinebreaks = false)
 {
     if (!is_string($value)) {
         throw new InvalidValueException(Translate::t("The value must be a string."));
     }
     if (is_int($minLength) && strlen($value) < $minLength) {
         throw new InvalidValueException(sprintf(Translate::t("The value is too short, it must have at least %s characters."), $minLength));
     }
     if (is_int($maxLength) && strlen($value) > $maxLength) {
         throw new InvalidValueException(sprintf(Translate::t("The value is too long, it must have at most %s characters."), $maxLength));
     }
     // filtering for control characters, but maybe allow \n, \r and \t
     $allowedCntrlChars = $allowLinebreaks ? [9, 10, 13] : [];
     if (preg_match_all('/[[:cntrl:]]/', $value, $matches)) {
         foreach ($matches[0] as $match) {
             if (!in_array(ord($match), $allowedCntrlChars)) {
                 throw new InvalidValueException(Translate::t("The value contains invalid characters."));
             }
         }
     }
 }
 public function validate($value, $minLength = null, $maxLength = null, $allowLinebreaks = false)
 {
     // make sure there are no untranslated parts at the beginning, unless the string is entirely empty
     if ($value !== "") {
         $this->regexValidator->validate($value, "|^\\[:[a-z]{2}\\]|");
     }
     $availableLanguages = array_map(function ($locale) {
         return substr($locale, 0, 2);
     }, $this->localeService->getAvailableLocales());
     $parts = Multilang::multilangStringToArray($value);
     if (!count($parts) && $minLength) {
         throw new InvalidValueException(Translate::t("The field must be translated into at least one language."));
     }
     foreach ($parts as $lang => $string) {
         if (!in_array($lang, $availableLanguages)) {
             throw new InvalidValueException(sprintf(Translate::t("`%s` is not a valid language."), $lang));
         }
         if ($string || $minLength) {
             $this->stringValidator->validate($string, $minLength, $maxLength, $allowLinebreaks);
         }
     }
 }