code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter
559636
private function getVariables(FilterControllerArgumentsEvent $event)
    {
        $request = $event->getRequest();
        $token = $this->tokenStorage->getToken();

        if (null !== $this->roleHierarchy) {
            $roles = $this->roleHierarchy->getReachableRoles($token->getRoles());
        } else {
            $roles = $token->getRoles();
        }

        $variables = [
            'token' => $token,
            'user' => $token->getUser(),
            'object' => $request,
            'subject' => $request,
            'request' => $request,
            'roles' => array_map(function ($role) {
                return $role->getRole();
            }, $roles),
            'trust_resolver' => $this->trustResolver,
            // needed for the is_granted expression function
            'auth_checker' => $this->authChecker,
        ];

        $controllerArguments = $this->argumentNameConverter->getControllerArguments($event);

        if ($diff = array_intersect(array_keys($variables), array_keys($controllerArguments))) {
            foreach ($diff as $key => $variableName) {
                if ($variables[$variableName] === $controllerArguments[$variableName]) {
                    unset($diff[$key]);
                }
            }

            if ($diff) {
                $singular = 1 === \count($diff);
                if (null !== $this->logger) {
                    $this->logger->warning(sprintf('Controller argument%s "%s" collided with the built-in security expression variables. The built-in value%s are being used for the @Security expression.', $singular ? '' : 's', implode('", "', $diff), $singular ? 's' : ''));
                }
            }
        }

        // controller variables should also be accessible
        return array_merge($controllerArguments, $variables);
    }
905054
public function vote(TokenInterface $token, $object, array $attributes)
    {
        //attributes[0] contains the permission (ie create, edit, open, ...)
        $attributes[0] = strtoupper($attributes[0]);

        if (!$this->supports($object) || !$this->supportsAction($attributes[0])) {
            return VoterInterface::ACCESS_ABSTAIN;
        }

        $collection = $this->getCollection($object);

        foreach ($collection as $object) {
            $access = $this->checkPermission($token, $object, $attributes, $collection->getOptions());
            if (VoterInterface::ACCESS_DENIED === $access) {
                return $access;
            }
        }

        //maybe abstain sometimes
        return VoterInterface::ACCESS_GRANTED;
    }
1313157
protected function checkModule() : void
    {
        $namespaced_class = $this->getFullyQualifiedClass($this->response->getModule(), $this->response->getController());
        if (!class_exists($namespaced_class)) {
            $this->response->setStatusCode(404);
            Core::i()->log->warning('Unable to load controller ' . $namespaced_class);
            return;
        }
        if (!call_user_func($namespaced_class . '::can_view')) {
            $this->response->setStatusCode(403);
            Core::i()->log->error('User is not authorized to view ' . $namespaced_class);
            return;
        }
        if (method_exists($namespaced_class, $this->getActionMethodName($this->response->getAction()))) {
            $this->response->setStatusCode(200);
        } elseif (method_exists($namespaced_class, 'indexAction')) {
            Core::i()->log->notice('Requested action ' . $this->response->getAction() . ' not found in ' . $namespaced_class);
            $this->response->setAction('index');
            $this->response->setStatusCode(200);
        } else {
            Core::i()->log->error('Controller ' . $namespaced_class . ' does not have a public indexAction method defined.');
            $this->response->setStatusCode(500);
        }
    }
901811
public function execute() {
        global $DB;
        if (is_enabled_auth('ldap')) {
            $auth = get_auth_plugin('ldap');
            $users = $DB->get_records('user', array('auth' => 'ldap'));
            foreach ($users as $user) {
                $auth->sync_roles($user);
            }
        }
    }
92174
public function sync()
    {
        $service = Injector::inst()->get(LDAPService::class);
        if (!$service->enabled() ||
            !$this->owner->GUID
        ) {
            return;
        }
        $service->updateLDAPFromMember($this->owner);
        $service->updateLDAPGroupsForMember($this->owner);
    }
529150
public function updateAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(static::CONTROLLER_CHECK_RESOURCE, Dealer::getModuleCode(),
                AccessManager::UPDATE)
        ) {
            return $response;
        }

        // Load object if exist
        if (null !== $object = $this->getExistingObject()) {
            // Hydrate the form abd pass it to the parser
            $changeForm = $this->hydrateObjectForm($object);

            // Pass it to the parser
            $this->getParserContext()->addForm($changeForm);
        }

        // Render the edition template.
        return $this->getEditRenderTemplate();
    }
508885
public function indexAction() {
		$clientSettings = $this->configurationManager->getConfiguration(\TYPO3\Flow\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Flowpack.SingleSignOn.Client');
		$clientSettingsYaml = \Symfony\Component\Yaml\Yaml::dump($clientSettings, 99, 2);
		$this->view->assign('clientSettings', $clientSettingsYaml);

		$authenticationSettings = $this->configurationManager->getConfiguration(\TYPO3\Flow\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow.security.authentication');
		$authenticationSettingsYaml = \Symfony\Component\Yaml\Yaml::dump($authenticationSettings, 99, 2);
		$this->view->assign('authenticationSettings', $authenticationSettingsYaml);
	}
606319
protected function processToken(): void
    {
        $prevStatement = null;

        foreach ($this->useStatements as $useStatement) {
            if ($prevStatement && ($this->compareUseStatements($prevStatement, $useStatement) > 0)) {
                $exception = new CodeError(
                    static::CODE_INCORRECT_ORDER,
                    'Use statements should be sorted alphabetically. The first wrong one is %s.',
                    $useStatement->getPointer()
                );

                $exception
                    ->setPayload([$useStatement->getFullyQualifiedTypeName()])
                    ->isFixable(true);

                throw $exception;
            }

            $prevStatement = $useStatement;
        }
    }
377453
public function podiumEdit()
    {
        $transaction = static::getDb()->beginTransaction();
        try {
            if (!$this->save()) {
                throw new Exception('Poll saving error!');
            }

            foreach ($this->editAnswers as $answer) {
                foreach ($this->answers as $oldAnswer) {
                    if ($answer == $oldAnswer->answer) {
                        continue(2);
                    }
                }
                $pollAnswer = new PollAnswer();
                $pollAnswer->poll_id = $this->id;
                $pollAnswer->answer = $answer;
                if (!$pollAnswer->save()) {
                    throw new Exception('Poll Answer saving error!');
                }
            }
            foreach ($this->answers as $oldAnswer) {
                foreach ($this->editAnswers as $answer) {
                    if ($answer == $oldAnswer->answer) {
                        continue(2);
                    }
                }
                if (!$oldAnswer->delete()) {
                    throw new Exception('Poll Answer deleting error!');
                }
            }

            $transaction->commit();
            Log::info('Poll updated', $this->id, __METHOD__);
            return true;
        } catch (Exception $e) {
            $transaction->rollBack();
            Log::error($e->getMessage(), null, __METHOD__);
        }
        return false;
    }
1094368
function _requestVotes () {
    let { host, coordinationPort } = node.settings
    let message = {
      type: 'voteRequest',
      data: {}
    }
    return new Promise((resolve, reject) => {
      let resolveStart = Date.now()
      dns.resolve4(host, (err, addresses) => {
        if (err) {
          debug(`cannot resolve host '${host}'. Check DNS infrastructure.`)
          return reject(err)
        }
        debug(`resolved ${addresses.length} IP(s) for host '${host}' in ${Date.now() - resolveStart} ms`)
        debug(`requesting votes from ${addresses.length} nodes`)
        Promise.all(
          addresses.map(address => new Promise((resolve, reject) => {
            let voteRequestTime = Date.now()
            let messenger = zmq.socket('req')
            messenger.connect(`tcp://${address}:${coordinationPort}`)
            messenger.send(JSON.stringify({
              ...message,
              toAddress: address,
              from: node.name
            }))

            let _resolved = false
            function onEnd (candidateBuffer) {
              if (_resolved) return
              _resolved = true
              messenger.removeListener('message', onEnd)
              messenger.close()

              let candidate = candidateBuffer && JSON.parse(candidateBuffer)
              if (candidate) {
                let elapsed = Date.now() - voteRequestTime
                candidate.candidate && debug(`received vote by ${candidate.name === node.name ? 'myself' : candidate.name}${candidate.isMaster ? ' (master)' : ''} in ${elapsed} ms`)
              } else {
                debug(`missed vote by peer at ${address}`)
              }
              resolve(candidate)
            }

            messenger.on('message', onEnd)
            setTimeout(onEnd, node.settings.voteTimeout)
          }))
        )
        .then(nodes => compact(nodes))
        .then(nodes => resolve(nodes.filter(({candidate}) => candidate)))
      })
    })
  }
1309050
function pollDo(fn, timeOut, doName, obj) {
  var siv = null;

  if (!obj) {
    obj = window;
  }
  if (timeOut == null) {
    timeOut = 100;
  }

  //If the previous poll operation is exist,then make it cancel.
  if (doName && obj[doName]) {
    clearInterval(obj[doName]);
  }

  //Polling execution operations every interval a period of time.
  siv = setInterval(function () {
    if (fn.call(obj) === false) {
      clearInterval(siv);
    }
  }, timeOut);

  if (doName) {
    obj[doName] = siv;
  }

  return siv;
}
802514
protected function configureCorsIfEnabled(): void
    {
        $reflection = new \ReflectionClass($this);
        $reader = new AnnotationReader();

        $annotation = $reader->getClassAnnotation($reflection, CORS::class);

        if (empty($annotation)) {
            return;
        }

        $corsConfig = [
            'Access-Control-Allow-Origin' => $annotation->origins ?? '*',
            'Access-Control-Allow-Methods' => $annotation->methods ?? 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => $annotation->headers ?? '*',
            'Access-Control-Allow-Credentials' => $annotation->credentials ?? true,
            'Access-Control-Allow-Max-Age' => $annotation->maxAge ?? 3600
        ];

        foreach ($corsConfig as $key => $value) {
            $this->getResponse()->headers->set($key, $value);
        }
    }
941511
function createVote (secret, delegates, secondSecret) {
	var keys = crypto.getKeys(secret);

	var transaction = {
		type: 3,
		amount: 0,
		fee: constants.fees.vote,
		recipientId: crypto.getAddress(keys.publicKey),
		senderPublicKey: keys.publicKey,
		timestamp: slots.getTime(),
		asset: {
			votes: delegates
		}
	};

	crypto.sign(transaction, keys);

	if (secondSecret) {
		var secondKeys = crypto.getKeys(secondSecret);
		crypto.secondSign(transaction, secondKeys);
	}

	transaction.id = crypto.getId(transaction);

	return transaction;
}
918077
public function edit()
    {
        $this->defaultData();
        $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class);
        $user = $this->getUserResource();

        $types = $user->getTypes();
        $myFormContainer = new tao_actions_form_Users(reset($types), $user);
        $myForm = $myFormContainer->getForm();

        if ($myForm->isSubmited()) {
            if ($myForm->isValid()) {
                $values = $myForm->getValues();
                if (!empty($values['password2']) && !empty($values['password3'])) {
                    $plainPassword =  $values['password2'];
                    $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password2']);
                }

                unset($values['password2']);
                unset($values['password3']);

                if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_UILG]))) {
                    unset($values[GenerisRdf::PROPERTY_USER_UILG]);
                }
                if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_DEFLG]))) {
                    unset($values[GenerisRdf::PROPERTY_USER_DEFLG]);
                }

                $userService->checkCurrentUserAccess($values[GenerisRdf::PROPERTY_USER_ROLES]);

                // leave roles which are not in the allowed list for current user
                $oldRoles = $userService->getUserRoles($user);
                $allowedRoles = $userService->getPermittedRoles($userService->getCurrentUser(), $oldRoles, false);
                $staticRoles = array_diff($oldRoles, $allowedRoles);
                $values[GenerisRdf::PROPERTY_USER_ROLES] = array_merge($values[GenerisRdf::PROPERTY_USER_ROLES], $staticRoles);

                $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($user);

                if ($binder->bind($values)) {
                    $data = [];
                    if (isset($plainPassword)){
                        $data = ['hashForKey' => UserHashForEncryption::hash($plainPassword)];
                    }
                    $this->getEventManager()->trigger(new UserUpdatedEvent(
                        $user,
                        array_merge($values, $data))
                    );
                    $this->setData('message', __('User saved'));
                }
            }
        }

        $this->setData('formTitle', __('Edit a user'));
        $this->setData('myForm', $myForm->render());
        $this->setView('user/form.tpl');
    }
1360335
public function beforeCompile(): void
	{
		$builder = $this->getContainerBuilder();

		if ($builder->getByType(User::class) === null) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', User::class));
		}

		if ($builder->getByType(EventDispatcherInterface::class) === null) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', EventDispatcherInterface::class));
		}

		$user = $builder->getDefinition($builder->getByType(User::class));
		$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcherInterface::class));

		$user->addSetup('?->onLoggedIn[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			SecurityEvents::ON_LOGGED_IN,
			new PhpLiteral(LoggedInEvent::class),
		]);
		$user->addSetup('?->onLoggedOut[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			SecurityEvents::ON_LOGGED_OUT,
			new PhpLiteral(LoggedOutEvent::class),
		]);
	}
1267275
public static function do(ConnectorInterface $connector, $voter, $publicWif, $author, $permlink, $weight)
    {
        $chainName = $connector->getPlatform();
        /** @var CommandQueryData $tx */
        $tx = Transaction::init($connector);
        $tx->setParamByKey(
            '0:operations:0',
            [
                'vote',
                [
                    'voter'    => $voter,
                    'author'   => $author,
                    'permlink' => $permlink,
                    'weight'   => $weight
                ]
            ]
        );

        $command = new BroadcastTransactionCommand($connector);////        echo '<pre>' . var_dump($commandQueryData->getParams(), $properties2) . '<pre>'; die; //FIXME delete it
        Transaction::sign($chainName, $tx, ['posting' => $publicWif]);

        $answer = $command->execute(
            $tx
        );

        return $answer;
    }
1167932
public function buildExpression()
    {
        /** @var EditableFormField $formFieldWatch */
        $formFieldWatch = $this->ConditionField();
        //Encapsulated the action to the object
        $action = $formFieldWatch->getJsEventHandler();

        // is this field a special option field
        $checkboxField = $formFieldWatch->isCheckBoxField();
        $radioField = $formFieldWatch->isRadioField();
        $target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly());
        $fieldValue = Convert::raw2js($this->FieldValue);

        $conditionOptions = [
            'ValueLessThan'         => '<',
            'ValueLessThanEqual'    => '<=',
            'ValueGreaterThan'      => '>',
            'ValueGreaterThanEqual' => '>='
        ];

        // and what should we evaluate
        switch ($this->ConditionOption) {
            case 'IsNotBlank':
            case 'IsBlank':
                $expression = ($checkboxField || $radioField) ? "!{$target}.is(\":checked\")" : "{$target}.val() == ''";
                if ((string) $this->ConditionOption === 'IsNotBlank') {
                    //Negate
                    $expression = "!({$expression})";
                }
                break;
            case 'HasValue':
            case 'ValueNot':
                if ($checkboxField) {
                    if ($formFieldWatch->isCheckBoxGroupField()) {
                        $expression = sprintf(
                            "$.inArray('%s', %s.filter(':checked').map(function(){ return $(this).val();}).get()) > -1",
                            $fieldValue,
                            $target
                        );
                    } else {
                        $expression = "{$target}.prop('checked')";
                    }
                } elseif ($radioField) {
                    // We cannot simply get the value of the radio group, we need to find the checked option first.
                    $expression = sprintf(
                        '%s.closest(".field, .control-group").find("input:checked").val() == "%s"',
                        $target,
                        $fieldValue
                    );
                } else {
                    $expression = sprintf('%s.val() == "%s"', $target, $fieldValue);
                }

                if ((string) $this->ConditionOption === 'ValueNot') {
                    //Negate
                    $expression = "!({$expression})";
                }
                break;
            case 'ValueLessThan':
            case 'ValueLessThanEqual':
            case 'ValueGreaterThan':
            case 'ValueGreaterThanEqual':
                $expression = sprintf(
                    '%s.val() %s parseFloat("%s")',
                    $target,
                    $conditionOptions[$this->ConditionOption],
                    $fieldValue
                );
                break;
            default:
                throw new LogicException("Unhandled rule {$this->ConditionOption}");
                break;
        }

        $result = [
            'operation' => $expression,
            'event'     => $action,
        ];

        return $result;
    }