Exemple #1
0
 /**
  * Sets a header.
  * @param  string
  * @param  string|array  value or pair email => name
  * @param  bool
  * @return MailMimePart  provides a fluent interface
  */
 public function setHeader($name, $value, $append = FALSE)
 {
     if (!$name || preg_match('#[^a-z0-9-]#i', $name)) {
         throw new InvalidArgumentException("Header name must be non-empty alphanumeric string, '{$name}' given.");
     }
     if ($value == NULL) {
         // intentionally ==
         if (!$append) {
             unset($this->headers[$name]);
         }
     } elseif (is_array($value)) {
         // email
         $tmp =& $this->headers[$name];
         if (!$append || !is_array($tmp)) {
             $tmp = array();
         }
         foreach ($value as $email => $recipient) {
             if ($recipient !== NULL && !Strings::checkEncoding($recipient)) {
                 Validators::assert($recipient, 'unicode', "header '{$name}'");
             }
             if (preg_match('#[\\r\\n]#', $recipient)) {
                 throw new InvalidArgumentException("Name must not contain line separator.");
             }
             Validators::assert($email, 'email', "header '{$name}'");
             $tmp[$email] = $recipient;
         }
     } else {
         $value = (string) $value;
         if (!Strings::checkEncoding($value)) {
             throw new InvalidArgumentException("Header is not valid UTF-8 string.");
         }
         $this->headers[$name] = preg_replace('#[\\r\\n]+#', ' ', $value);
     }
     return $this;
 }
Exemple #2
0
 /**
  * Create new school
  * 
  * @param Request $r
  * @return array
  * @throws InvalidDatabaseOperationException
  * @throws InvalidParameterException
  */
 public static function apiCreate(Request $r)
 {
     self::authenticateRequest($r);
     Validators::isStringNonEmpty($r["name"], "name");
     Validators::isNumber($r["state_id"], "state_id", false);
     if (!is_null($r["state_id"])) {
         try {
             $r["state"] = StatesDAO::getByPK($r["state_id"]);
         } catch (Exception $e) {
             throw new InvalidDatabaseOperationException($e);
         }
         if (is_null($r["state"])) {
             throw new InvalidParameterException("parameterNotFound", "state");
         }
     }
     // Create school object
     $school = new Schools(array("name" => $r["name"], "state_id" => $r["state_id"]));
     $school_id = 0;
     try {
         $existing = SchoolsDAO::findByName($r["name"]);
         if (count($existing) > 0) {
             $school_id = $existing[0]->getSchoolId();
         } else {
             // Save in db
             SchoolsDAO::save($school);
             $school_id = $school->getSchoolId();
         }
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     return array("status" => "ok", "school_id" => $school_id);
 }
Exemple #3
0
 public static function testStrongPassword($s_Password)
 {
     // Setting max passwd length to 72 to avoid DoS attacks
     Validators::isStringOfMinLength($s_Password, "password", 8);
     Validators::isStringOfMaxLength($s_Password, "password", 72);
     return true;
 }
 public static function handleTagItemsRequest(Tag $Tag)
 {
     $conditions = array('TagID' => $Tag->ID);
     if (!empty($_REQUEST['Class']) && Validators::className($_REQUEST['Class'])) {
         $conditions['ContextClass'] = $_REQUEST['Class'];
     }
     return static::respond('tagItems', array('success' => true, 'data' => TagItem::getAllByWhere($conditions)));
 }
 /**
  * Add contest to a group scoreboard
  * 
  * @param Request $r
  */
 public static function apiAddContest(Request $r)
 {
     self::validateGroupScoreboardAndContest($r);
     Validators::isInEnum($r["only_ac"], "only_ac", array(0, 1));
     Validators::isNumber($r["weight"], "weight");
     try {
         $groupScoreboardContest = new GroupsScoreboardsContests(array("group_scoreboard_id" => $r["scoreboard"]->group_scoreboard_id, "contest_id" => $r["contest"]->contest_id, "only_ac" => $r["only_ac"], "weight" => $r["weight"]));
         GroupsScoreboardsContestsDAO::save($groupScoreboardContest);
         self::$log->info("Contest " . $r["contest_alias"] . "added to scoreboard " . $r["scoreboard_alias"]);
     } catch (Exception $ex) {
         throw new InvalidDatabaseOperationException($ex);
     }
     return array("status" => "ok");
 }
 /**
  * Add contest to a group scoreboard
  *
  * @param Request $r
  */
 public static function apiAddContest(Request $r)
 {
     self::validateGroupScoreboardAndContest($r);
     Validators::isInEnum($r['only_ac'], 'only_ac', array(0, 1));
     Validators::isNumber($r['weight'], 'weight');
     try {
         $groupScoreboardContest = new GroupsScoreboardsContests(array('group_scoreboard_id' => $r['scoreboard']->group_scoreboard_id, 'contest_id' => $r['contest']->contest_id, 'only_ac' => $r['only_ac'], 'weight' => $r['weight']));
         GroupsScoreboardsContestsDAO::save($groupScoreboardContest);
         self::$log->info('Contest ' . $r['contest_alias'] . 'added to scoreboard ' . $r['scoreboard_alias']);
     } catch (Exception $ex) {
         throw new InvalidDatabaseOperationException($ex);
     }
     return array('status' => 'ok');
 }
Exemple #7
0
 /**
  * Entry point to configure omegaup in ec2 mode
  * 
  * @param Request $r
  * @return type
  */
 public static function apiScaleOut(Request $r)
 {
     self::validateRequest($r);
     Validators::isNumber($r["count"], "count");
     $response["grader"] = self::setEmbeddedRunners("false");
     self::$log->info("Bootstrapping more instances: ");
     $ec2_cmd_output = array();
     $return_var = 0;
     $cmd = "ec2-run-instances ami-3e123e7b -k omegaup_backend_test_key -i m1.medium -n " . $r["count"] . " --region us-west-1";
     self::$log->info("Executing: " . $cmd);
     exec($cmd, $ec2_cmd_output, $return_var);
     if ($return_var !== 0) {
         // D:
         self::$log->error($cmd . " returned: " . $return_var);
         throw new InvalidFilesystemOperationException("Error executing ec2-run-instances. Please check log for details");
     }
     $response["ec2-run-instances"] = $ec2_cmd_output;
     return $response;
 }
 /**
  * Resolves the target user for the API. If a username is provided in
  * the request, then we use that one. Otherwise, we use currently logged-in
  * user.
  *
  * Request must be authenticated before this function is called.
  *
  * @param Request $r
  * @return Users
  * @throws InvalidDatabaseOperationException
  * @throws NotFoundException
  */
 protected static function resolveTargetUser(Request $r)
 {
     // By default use current user
     $user = $r['current_user'];
     if (!is_null($r['username'])) {
         Validators::isStringNonEmpty($r['username'], 'username');
         try {
             $user = UsersDAO::FindByUsername($r['username']);
             if (is_null($user)) {
                 throw new InvalidParameterException('parameterNotFound', 'Username');
             }
         } catch (ApiException $e) {
             throw $e;
         } catch (Exception $e) {
             throw new InvalidDatabaseOperationException($e);
         }
     }
     return $user;
 }
 /**
  * Entry point to configure omegaup in ec2 mode
  *
  * @param Request $r
  * @return type
  */
 public static function apiScaleOut(Request $r)
 {
     self::validateRequest($r);
     Validators::isNumber($r['count'], 'count');
     $response['grader'] = self::setEmbeddedRunners('false');
     self::$log->info('Bootstrapping more instances: ');
     $ec2_cmd_output = array();
     $return_var = 0;
     $cmd = 'ec2-run-instances ami-3e123e7b -k omegaup_backend_test_key -i m1.medium -n ' . $r['count'] . ' --region us-west-1';
     self::$log->info('Executing: ' . $cmd);
     exec($cmd, $ec2_cmd_output, $return_var);
     if ($return_var !== 0) {
         // D:
         self::$log->error($cmd . ' returned: ' . $return_var);
         throw new InvalidFilesystemOperationException('Error executing ec2-run-instances. Please check log for details');
     }
     $response['ec2-run-instances'] = $ec2_cmd_output;
     return $response;
 }
Exemple #10
0
 /**
  * Returns the NEON representation of a value.
  * @param  mixed
  * @param  int
  * @return string
  */
 public static function encode($var, $options = NULL)
 {
     if ($var instanceof DateTime) {
         return $var->format('Y-m-d H:i:s O');
     } elseif ($var instanceof NeonEntity) {
         return self::encode($var->value) . '(' . substr(self::encode($var->attributes), 1, -1) . ')';
     }
     if (is_object($var)) {
         $obj = $var;
         $var = array();
         foreach ($obj as $k => $v) {
             $var[$k] = $v;
         }
     }
     if (is_array($var)) {
         $isList = Validators::isList($var);
         $s = '';
         if ($options & self::BLOCK) {
             if (count($var) === 0) {
                 return "[]";
             }
             foreach ($var as $k => $v) {
                 $v = self::encode($v, self::BLOCK);
                 $s .= ($isList ? '-' : self::encode($k) . ':') . (Strings::contains($v, "\n") ? "\n\t" . str_replace("\n", "\n\t", $v) : ' ' . $v) . "\n";
                 continue;
             }
             return $s;
         } else {
             foreach ($var as $k => $v) {
                 $s .= ($isList ? '' : self::encode($k) . ': ') . self::encode($v) . ', ';
             }
             return ($isList ? '[' : '{') . substr($s, 0, -2) . ($isList ? ']' : '}');
         }
     } elseif (is_string($var) && !is_numeric($var) && !preg_match('~[\\x00-\\x1F]|^\\d{4}|^(true|false|yes|no|on|off|null)$~i', $var) && preg_match('~^' . self::$patterns[4] . '$~', $var)) {
         return $var;
     } elseif (is_float($var)) {
         $var = var_export($var, TRUE);
         return Strings::contains($var, '.') ? $var : $var . '.0';
     } else {
         return json_encode($var);
     }
 }
 public static function handleContactRequest()
 {
     // get optional subform name
     $subform = static::shiftPath();
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         // validate
         $Validator = new RecordValidator($_REQUEST);
         foreach (static::$validators as $validatorConfig) {
             // execute callable validator
             if (is_callable($validatorConfig)) {
                 $validatorConfig($Validator, $subform);
             } else {
                 if (!empty($validatorConfig['subforms']) && is_array($validatorConfig['subforms']) && (!$subform || !in_array($subform, $validatorConfig['subforms']))) {
                     // skip if validator specific to other subforms
                     continue;
                 }
                 $Validator->validate($validatorConfig);
             }
         }
         if (!$Validator->hasErrors()) {
             // save to database
             $Submission = new ContactSubmission::$defaultClass();
             $Submission->Data = array_diff_key($_REQUEST, array_flip(static::$excludeFields));
             $Submission->Subform = $subform;
             $Submission->save();
             // generate email report
             if (!empty(static::$emailTo)) {
                 $headers = array();
                 if (!empty($_REQUEST['Email']) && Validators::email($_REQUEST['Email'])) {
                     $headers['Reply-To'] = $_REQUEST['Email'];
                 }
                 Emergence\Mailer\Mailer::sendFromTemplate(static::$emailTo, 'staffNotice', array('Submission' => $Submission, 'formatters' => static::$formatters), array('Headers' => $headers));
             }
             // respond success
             return static::respond('contactSubmitted', array('success' => true, 'subform' => $subform));
         }
     }
     return static::respond('contact', array('validationErrors' => isset($Validator) ? $Validator->getErrors() : array(), 'subform' => $subform));
 }
Exemple #12
0
 /**
  * Validator for List API
  * 
  * @param Request $r
  * @throws ForbiddenAccessException
  * @throws InvalidDatabaseOperationException
  * @throws NotFoundException
  */
 private static function validateList(Request $r)
 {
     // Defaults for offset and rowcount
     if (!isset($r["offset"])) {
         $r["offset"] = 0;
     }
     if (!isset($r["rowcount"])) {
         $r["rowcount"] = 100;
     }
     if (!Authorization::IsSystemAdmin($r["current_user_id"])) {
         throw new ForbiddenAccessException("userNotAllowed");
     }
     Validators::isNumber($r["offset"], "offset", false);
     Validators::isNumber($r["rowcount"], "rowcount", false);
     Validators::isInEnum($r["status"], "status", array('new', 'waiting', 'compiling', 'running', 'ready'), false);
     Validators::isInEnum($r["verdict"], "verdict", array("AC", "PA", "WA", "TLE", "MLE", "OLE", "RTE", "RFE", "CE", "JE", "NO-AC"), false);
     // Check filter by problem, is optional
     if (!is_null($r["problem_alias"])) {
         Validators::isStringNonEmpty($r["problem_alias"], "problem");
         try {
             $r["problem"] = ProblemsDAO::getByAlias($r["problem_alias"]);
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
         if (is_null($r["problem"])) {
             throw new NotFoundException("problemNotFound");
         }
     }
     Validators::isInEnum($r["language"], "language", array('c', 'cpp', 'cpp11', 'java', 'py', 'rb', 'pl', 'cs', 'pas', 'kp', 'kj', 'cat', 'hs'), false);
     // Get user if we have something in username
     if (!is_null($r["username"])) {
         try {
             $r["user"] = UserController::resolveUser($r["username"]);
         } catch (NotFoundException $e) {
             // If not found, simply ignore it
             $r["username"] = null;
             $r["user"] = null;
         }
     }
 }
Exemple #13
0
<?php

define('DEBUG', false);
define('SERVER_NAME', 'Shivas');
define('SCRIPT_NAME', $_SERVER['SCRIPT_NAME']);
define('DB_HOST', 'localhost');
define('DB_NAME', 'shivas');
define('DB_USER', 'root');
define('DB_PASSWD', '');
define('DB_INSERT_QUERY', 'INSERT INTO accounts(name, password, salt, nickname, question, answer) VALUES(:name, :password, :salt, :nickname, :question, :answer);');
require_once "common.lib.php";
$success = false;
$fields = get_fields(array('name', 'password', 'nickname', 'question', 'answer'), $_POST);
$validators = array('name' => Validators::with($required)->plus($length_between, 4, 15)->build(), 'password' => Validators::with($required)->plus($min_length, 4)->build(), 'nickname' => Validators::with($required)->plus($min_length, 4)->build(), 'question' => Validators::with($required)->plus($min_length, 4)->build(), 'answer' => Validators::with($required)->plus($min_length, 4)->build());
$errors = is_method('POST') ? get_errors($validators, $fields) : array();
if (is_method('POST') && ($success = count($errors) <= 0)) {
    $fields['salt'] = random_string(32);
    $fields['password'] = shivas_encrypt($fields['password'], $fields['salt']);
    try {
        $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWD);
        $db->prepare(DB_INSERT_QUERY)->execute($fields);
    } catch (Exception $e) {
        $success = false;
        $errors['global'] = array($e->getMessage());
    }
}
include "signup.view.php";
 /**
  * Enforces username requirements
  *
  * @param string $parameter
  * @param string $parameterName
  * @param boolean $required
  * @throws InvalidParameterException
  */
 public static function isValidUsername($parameter, $parameterName, $required = true)
 {
     $isPresent = self::throwIfNotPresent($parameter, $parameterName, $required);
     if ($isPresent && preg_match('/[^a-zA-Z0-9_.-]/', $parameter)) {
         throw new InvalidParameterException('parameterInvalidAlias', $parameterName);
     }
     Validators::isStringOfMinLength($parameter, $parameterName, 2);
 }
Exemple #15
0
 /**
  * Rangle validator: is a control's value number in specified range?
  * @param  TextBase
  * @param  array  min and max value pair
  * @return bool
  */
 public static function validateRange(TextBase $control, $range)
 {
     return Validators::isInRange($control->getValue(), $range);
 }
 /**
  * Returns a detailed report of the contest
  *
  * @param Request $r
  * @return array
  */
 public static function apiReport(Request $r)
 {
     self::authenticateRequest($r);
     self::validateStats($r);
     $scoreboard = new Scoreboard($r["contest"]->getContestId(), true, $r["auth_token"]);
     // Check the filter if we have one
     Validators::isStringNonEmpty($r["filterBy"], "filterBy", false);
     $contestReport = $scoreboard->generate(true, true, isset($r["filterBy"]) ? null : $r["filterBy"]);
     $contestReport["status"] = "ok";
     return $contestReport;
 }
Exemple #17
0
 public function insert($data)
 {
     if ($data instanceof Traversable && !$data instanceof TableSelection) {
         $data = iterator_to_array($data);
     }
     if (Validators::isList($data)) {
         foreach (array_keys($data) as $key) {
             $data[$key][$this->column] = $this->active;
         }
     } else {
         $data[$this->column] = $this->active;
     }
     return parent::insert($data);
 }
Exemple #18
0
 private function getSection(array $data, $key, $file)
 {
     Validators::assertField($data, $key, 'array|null', "section '%' in file '{$file}'");
     $item = $data[$key];
     if ($parent = ConfigHelpers::takeParent($item)) {
         $item = ConfigHelpers::merge($item, $this->getSection($data, $parent, $file));
     }
     return $item;
 }
 /**
  * Validator for List API
  *
  * @param Request $r
  * @throws ForbiddenAccessException
  * @throws InvalidDatabaseOperationException
  * @throws NotFoundException
  */
 private static function validateList(Request $r)
 {
     // Defaults for offset and rowcount
     if (!isset($r['offset'])) {
         $r['offset'] = 0;
     }
     if (!isset($r['rowcount'])) {
         $r['rowcount'] = 100;
     }
     if (!Authorization::IsSystemAdmin($r['current_user_id'])) {
         throw new ForbiddenAccessException('userNotAllowed');
     }
     Validators::isNumber($r['offset'], 'offset', false);
     Validators::isNumber($r['rowcount'], 'rowcount', false);
     Validators::isInEnum($r['status'], 'status', array('new', 'waiting', 'compiling', 'running', 'ready'), false);
     Validators::isInEnum($r['verdict'], 'verdict', array('AC', 'PA', 'WA', 'TLE', 'MLE', 'OLE', 'RTE', 'RFE', 'CE', 'JE', 'NO-AC'), false);
     // Check filter by problem, is optional
     if (!is_null($r['problem_alias'])) {
         Validators::isStringNonEmpty($r['problem_alias'], 'problem');
         try {
             $r['problem'] = ProblemsDAO::getByAlias($r['problem_alias']);
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
         if (is_null($r['problem'])) {
             throw new NotFoundException('problemNotFound');
         }
     }
     Validators::isInEnum($r['language'], 'language', array('c', 'cpp', 'cpp11', 'java', 'py', 'rb', 'pl', 'cs', 'pas', 'kp', 'kj', 'cat', 'hs'), false);
     // Get user if we have something in username
     if (!is_null($r['username'])) {
         try {
             $r['user'] = UserController::resolveUser($r['username']);
         } catch (NotFoundException $e) {
             // If not found, simply ignore it
             $r['username'] = null;
             $r['user'] = null;
         }
     }
 }
 /**
  * Updates the main email of the current user
  *
  * @param Request $r
  */
 public static function apiUpdateMainEmail(Request $r)
 {
     self::authenticateRequest($r);
     Validators::isEmail($r['email'], 'email');
     try {
         // Update email
         $email = EmailsDAO::getByPK($r['current_user']->getMainEmailId());
         $email->setEmail($r['email']);
         EmailsDAO::save($email);
         // Add verification_id if not there
         if ($r['current_user']->getVerified() == '0') {
             self::$log->info('User not verified.');
             if ($r['current_user']->getVerificationId() == null) {
                 self::$log->info('User does not have verification id. Generating.');
                 try {
                     $r['current_user']->setVerificationId(self::randomString(50));
                     UsersDAO::save($r['current_user']);
                 } catch (Exception $e) {
                     // best effort, eat exception
                 }
             }
         }
     } catch (Exception $e) {
         // If duplicate in DB
         if (strpos($e->getMessage(), '1062') !== false) {
             throw new DuplicatedEntryInDatabaseException('mailInUse');
         } else {
             throw new InvalidDatabaseOperationException($e);
         }
     }
     // Delete profile cache
     Cache::deleteFromCache(Cache::USER_PROFILE, $r['current_user']->getUsername());
     // Send verification email
     $r['user'] = $r['current_user'];
     self::sendVerificationEmail($r);
     return array('status' => 'ok');
 }
Exemple #21
0
 /**
  * Create a scoreboard set to a group
  * 
  * @param Request $r
  */
 public static function apiCreateScoreboard(Request $r)
 {
     self::validateGroup($r);
     Validators::isValidAlias($r["alias"], "alias", true);
     Validators::isStringNonEmpty($r["name"], "name", true);
     Validators::isStringNonEmpty($r["description"], "description", false);
     try {
         $groupScoreboard = new GroupsScoreboards(array("group_id" => $r["group"]->group_id, "name" => $r["name"], "description" => $r["description"], "alias" => $r["alias"], "create_time" => gmdate('Y-m-d H:i:s', time())));
         GroupsScoreboardsDAO::save($groupScoreboard);
         self::$log->info("New scoreboard created " . $r["alias"]);
     } catch (Exception $ex) {
         throw new InvalidDatabaseOperationException($ex);
     }
     return array("status" => "ok");
 }
 /**
  * Validate update API request
  * 
  * @param Request $r
  * @throws InvalidDatabaseOperationException
  * @throws ForbiddenAccessException
  */
 private static function validateUpdate(Request $r)
 {
     Validators::isNumber($r["clarification_id"], "clarificaion_id");
     Validators::isStringNonEmpty($r["answer"], "answer", false);
     Validators::isInEnum($r["public"], "public", array('0', '1'), false);
     Validators::isStringNonEmpty($r["message"], "message", false);
     // Check that clarification exists
     try {
         $r['clarification'] = ClarificationsDAO::GetByPK($r["clarification_id"]);
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     if (!Authorization::CanEditClarification($r["current_user_id"], $r["clarification"])) {
         throw new ForbiddenAccessException();
     }
 }
Exemple #23
0
 static function with($validator, $param1 = null, $param2 = null)
 {
     $validators = new Validators();
     $validators->plus($validator, $param1, $param2);
     return $validators;
 }
 /**
  * Given a contest_alias, sets the recommended flag on/off.
  * Only omegaUp admins can call this API.
  *
  * @param Request $r
  * @return array
  */
 public static function apiSetRecommended(Request $r)
 {
     self::authenticateRequest($r);
     if (!Authorization::IsSystemAdmin($r['current_user_id'])) {
         throw new ForbiddenAccessException('userNotAllowed');
     }
     // Validate & get contest_alias
     try {
         $r['contest'] = ContestsDAO::getByAlias($r['contest_alias']);
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     if (is_null($r['contest'])) {
         throw new NotFoundException('contestNotFound');
     }
     // Validate value param
     Validators::isInEnum($r['value'], 'value', array('0', '1'));
     $r['contest']->recommended = $r['value'];
     try {
         ContestsDAO::save($r['contest']);
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     return array('status' => 'ok');
 }
 private static function getUniqueUsernameFromEmail($s_Email)
 {
     $idx = strpos($s_Email, '@');
     $username = substr($s_Email, 0, $idx);
     try {
         Validators::isValidUsername($username, 'username');
     } catch (InvalidParameterException $e) {
         // How can we know whats wrong with the username?
         // Things that could go wrong:
         //		generated email is too short
         $username = '******';
     }
     $suffix = '';
     for (;;) {
         // Maybe we can bring all records from db
         // with prefix $username, beacuse this:
         $userexists = UsersDAO::FindByUsername($username . $suffix);
         // will query db every single time probably.
         if (empty($userexists)) {
             break;
         }
         if (empty($suffix)) {
             $suffix = 1;
         } else {
             $suffix++;
         }
     }
     return $username . $suffix;
 }
Exemple #26
0
 /**
  * Formats PHP code for class instantiating, function calling or property setting in PHP.
  * @return string
  * @internal
  */
 public function formatStatement(DIStatement $statement, $self = NULL)
 {
     $entity = $this->normalizeEntity($statement->entity);
     $arguments = $statement->arguments;
     if (is_string($entity) && Strings::contains($entity, '?')) {
         // PHP literal
         return $this->formatPhp($entity, $arguments, $self);
     } elseif ($service = $this->getServiceName($entity)) {
         // factory calling or service retrieving
         if ($this->definitions[$service]->shared) {
             if ($arguments) {
                 throw new ServiceCreationException("Unable to call service '{$entity}'.");
             }
             return $this->formatPhp('$this->getService(?)', array($service));
         }
         $params = array();
         foreach ($this->definitions[$service]->parameters as $k => $v) {
             $params[] = preg_replace('#\\w+$#', '\\$$0', is_int($k) ? $v : $k) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
         }
         $rm = new FunctionReflection(create_function(implode(', ', $params), ''));
         $arguments = DIHelpers::autowireArguments($rm, $arguments, $this);
         return $this->formatPhp('$this->?(?*)', array(DIContainer::getMethodName($service, FALSE), $arguments), $self);
     } elseif ($entity === 'not') {
         // operator
         return $this->formatPhp('!?', array($arguments[0]));
     } elseif (is_string($entity)) {
         // class name
         if ($constructor = ClassReflection::from($entity)->getConstructor()) {
             $this->addDependency($constructor->getFileName());
             $arguments = DIHelpers::autowireArguments($constructor, $arguments, $this);
         } elseif ($arguments) {
             throw new ServiceCreationException("Unable to pass arguments, class {$entity} has no constructor.");
         }
         return $this->formatPhp("new {$entity}" . ($arguments ? '(?*)' : ''), array($arguments), $self);
     } elseif (!Validators::isList($entity) || count($entity) !== 2) {
         throw new InvalidStateException("Expected class, method or property, " . PhpHelpers::dump($entity) . " given.");
     } elseif ($entity[0] === '') {
         // globalFunc
         return $this->formatPhp("{$entity['1']}(?*)", array($arguments), $self);
     } elseif (Strings::contains($entity[1], '$')) {
         // property setter
         Validators::assert($arguments, 'list:1', "setup arguments for '" . Callback::create($entity) . "'");
         if ($this->getServiceName($entity[0], $self)) {
             return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]), $self);
         } else {
             return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]), $self);
         }
     } elseif ($service = $this->getServiceName($entity[0], $self)) {
         // service method
         if ($this->definitions[$service]->class) {
             $arguments = $this->autowireArguments($this->definitions[$service]->class, $entity[1], $arguments);
         }
         return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments), $self);
     } else {
         // static method
         $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
         return $this->formatPhp("{$entity['0']}::{$entity['1']}(?*)", array($arguments), $self);
     }
 }
 /**
  * Validate list request
  *
  * @param Request $r
  */
 private static function validateList(Request $r)
 {
     Validators::isNumber($r["offset"], "offset", false);
     Validators::isNumber($r["rowcount"], "rowcount", false);
     // Defaults for offset and rowcount
     if (!isset($r['page'])) {
         if (!isset($r["offset"])) {
             $r["offset"] = 0;
         }
         if (!isset($r["rowcount"])) {
             $r["rowcount"] = 1000;
         }
     }
     Validators::isStringNonEmpty($r["query"], "query", false);
 }
 /**
  * Create a scoreboard set to a group
  *
  * @param Request $r
  */
 public static function apiCreateScoreboard(Request $r)
 {
     self::validateGroup($r);
     Validators::isValidAlias($r['alias'], 'alias', true);
     Validators::isStringNonEmpty($r['name'], 'name', true);
     Validators::isStringNonEmpty($r['description'], 'description', false);
     try {
         $groupScoreboard = new GroupsScoreboards(array('group_id' => $r['group']->group_id, 'name' => $r['name'], 'description' => $r['description'], 'alias' => $r['alias'], 'create_time' => gmdate('Y-m-d H:i:s', time())));
         GroupsScoreboardsDAO::save($groupScoreboard);
         self::$log->info('New scoreboard created ' . $r['alias']);
     } catch (Exception $ex) {
         throw new InvalidDatabaseOperationException($ex);
     }
     return array('status' => 'ok');
 }
Exemple #29
0
 /**
  * Parses single service from configuration file.
  * @return void
  */
 public static function parseService(DIServiceDefinition $definition, $config, $shared = TRUE)
 {
     if ($config === NULL) {
         return;
     } elseif (!is_array($config)) {
         $config = array('class' => NULL, 'factory' => $config);
     }
     $known = $shared ? array('class', 'factory', 'arguments', 'setup', 'autowired', 'run', 'tags') : array('class', 'factory', 'arguments', 'setup', 'autowired', 'tags', 'internal', 'parameters');
     if ($error = array_diff(array_keys($config), $known)) {
         throw new InvalidStateException("Unknown key '" . implode("', '", $error) . "' in definition of service.");
     }
     $arguments = array();
     if (array_key_exists('arguments', $config)) {
         Validators::assertField($config, 'arguments', 'array');
         $arguments = self::filterArguments($config['arguments']);
         $definition->setArguments($arguments);
     }
     if (array_key_exists('class', $config) || array_key_exists('factory', $config)) {
         $definition->class = NULL;
         $definition->factory = NULL;
     }
     if (array_key_exists('class', $config)) {
         Validators::assertField($config, 'class', 'string|stdClass|null');
         if ($config['class'] instanceof stdClass) {
             $definition->setClass($config['class']->value, self::filterArguments($config['class']->attributes));
         } else {
             $definition->setClass($config['class'], $arguments);
         }
     }
     if (array_key_exists('factory', $config)) {
         Validators::assertField($config, 'factory', 'callable|stdClass|null');
         if ($config['factory'] instanceof stdClass) {
             $definition->setFactory($config['factory']->value, self::filterArguments($config['factory']->attributes));
         } else {
             $definition->setFactory($config['factory'], $arguments);
         }
     }
     if (isset($config['setup'])) {
         if (ConfigHelpers::takeParent($config['setup'])) {
             $definition->setup = array();
         }
         Validators::assertField($config, 'setup', 'list');
         foreach ($config['setup'] as $id => $setup) {
             Validators::assert($setup, 'callable|stdClass', "setup item #{$id}");
             if ($setup instanceof stdClass) {
                 Validators::assert($setup->value, 'callable', "setup item #{$id}");
                 $definition->addSetup($setup->value, self::filterArguments($setup->attributes));
             } else {
                 $definition->addSetup($setup);
             }
         }
     }
     $definition->setShared($shared);
     if (isset($config['parameters'])) {
         Validators::assertField($config, 'parameters', 'array');
         $definition->setParameters($config['parameters']);
     }
     if (isset($config['autowired'])) {
         Validators::assertField($config, 'autowired', 'bool');
         $definition->setAutowired($config['autowired']);
     }
     if (isset($config['internal'])) {
         Validators::assertField($config, 'internal', 'bool');
         $definition->setInternal($config['internal']);
     }
     if (isset($config['run'])) {
         $config['tags']['run'] = (bool) $config['run'];
     }
     if (isset($config['tags'])) {
         Validators::assertField($config, 'tags', 'array');
         if (ConfigHelpers::takeParent($config['tags'])) {
             $definition->tags = array();
         }
         foreach ($config['tags'] as $tag => $attrs) {
             if (is_int($tag) && is_string($attrs)) {
                 $definition->addTag($attrs);
             } else {
                 $definition->addTag($tag, $attrs);
             }
         }
     }
 }
 /**
  * Validate list request
  *
  * @param Request $r
  */
 private static function validateList(Request $r)
 {
     Validators::isNumber($r['offset'], 'offset', false);
     Validators::isNumber($r['rowcount'], 'rowcount', false);
     // Defaults for offset and rowcount
     if (!isset($r['page'])) {
         if (!isset($r['offset'])) {
             $r['offset'] = 0;
         }
         if (!isset($r['rowcount'])) {
             $r['rowcount'] = 1000;
         }
     }
     Validators::isStringNonEmpty($r['query'], 'query', false);
 }