code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter
497632
protected function getVariables(Request $request)
    {
        $token  = $this->securityContext->getToken();
        $user   = null;
        $roles  = [];

        if ($token instanceof TokenInterface) {
            $user = $token->getUser();

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

        $variables = array(
            'token' => $token,
            'user'  => $user,
            // we removed "object" and "request"
            'roles' => array_map(function (RoleInterface $role) { return $role->getRole(); }, $roles),
            'trust_resolver' => $this->trustResolver,
            'security_context' => $this->securityContext,
        );

        // controller variables should also be accessible: repository, entity...
        return array_merge($request->attributes->all(), $variables);
    }
1051689
public function syncToMember()
    {
        $member = $this->Member();
        $sync = $this->config()->sync_fields;
        $write = false;

        if (!$member->exists()) {
            return;
        }

        foreach ($this->getChangedFields() as $field => $change) {
            // If this field is a field to sync, and it is different
            // then update member
            if (in_array($field, $sync) && $member->$field != $this->$field) {
                $member->$field = $this->$field;
                $write = true;
            }
        }

        if ($write) {
            $member->write();
        }
    }
1228353
void poll_attr(final WorkItem to_do) throws DevFailed {
	Util.out5.println("----------> Time = " + now.tv_sec + "," + now.tv_usec + " Dev name = "
		+ to_do.dev.get_name() + ", Attr name = " + to_do.name);

	final TimeVal before_cmd = new TimeVal();
	final TimeVal after_cmd = new TimeVal();
	TimeVal needed_time;
	AttributeValue[] argout;
	// vector<PollObj *>::iterator ite = NULL;
	try {

	    long ctm = System.currentTimeMillis();
	    before_cmd.tv_sec = (int) (ctm / 1000);
	    before_cmd.tv_usec = (int) (ctm - 1000 * before_cmd.tv_sec) * 1000;
	    before_cmd.tv_sec = before_cmd.tv_sec - Tango_DELTA_T;

	    // Read the attributes
	    attr_names[0] = to_do.name;
	    argout = to_do.dev.read_attributes(attr_names);

	    ctm = System.currentTimeMillis();
	    after_cmd.tv_sec = (int) (ctm / 1000);
	    after_cmd.tv_usec = (int) (ctm - 1000 * after_cmd.tv_sec) * 1000;
	    after_cmd.tv_sec = after_cmd.tv_sec - Tango_DELTA_T;

	    needed_time = time_diff(before_cmd, after_cmd);

	    // Insert only if update period > 0
	    to_do.dev.get_dev_monitor().get_monitor();
	    final PollObj poll_obj = to_do.dev.get_polled_obj_by_type_name(to_do.type, to_do.name);
	    if (poll_obj.get_upd() > 0) {
		poll_obj.insert_data(argout[0], before_cmd, needed_time);
	    }
	    to_do.dev.get_dev_monitor().rel_monitor();
	} catch (final DevFailed e) {
	    Except.print_exception(e);

	    final long ctm = System.currentTimeMillis();
	    after_cmd.tv_sec = (int) (ctm / 1000);
	    after_cmd.tv_usec = (int) (ctm - 1000 * after_cmd.tv_sec) * 1000;
	    after_cmd.tv_sec = after_cmd.tv_sec - Tango_DELTA_T;

	    needed_time = time_diff(before_cmd, after_cmd);

	    // to_do.dev.get_dev_monitor().get_monitor();
	    try {
		final PollObj poll_obj = to_do.dev.get_polled_obj_by_type_name(to_do.type,
			to_do.name);
		poll_obj.insert_except(e, before_cmd, needed_time);
	    } catch (final DevFailed ex) {
	    }
	    to_do.dev.get_dev_monitor().rel_monitor();
	}
    }
359516
public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $duplicated_values = $value = [];

    // Load the current Group so we can see if there are existing members.
    $group = _social_group_get_current_group();

    // Grab all the input values so we can get the ID's out of them.
    $input_values = Tags::explode($element['#value']);
    foreach ($input_values as $input) {
      $match = static::extractEntityIdFromAutocompleteInput($input);
      if ($match === NULL) {
        $options = $element['#selection_settings'] + [
          'target_type' => $element['#target_type'],
          'handler' => $element['#selection_handler'],
        ];

        /* @var /Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler */
        $handler = \Drupal::service('plugin.manager.entity_reference_selection')->getInstance($options);
        $autocreate = (bool) $element['#autocreate'] && $handler instanceof SelectionWithAutocreateInterface;
        // Try to get a match from the input string when the user didn't use
        // the autocomplete but filled in a value manually.
        // Got this from the parent::validateEntityAutocomplete.
        $match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
      }

      if ($match !== NULL) {
        $value[$match] = [
          'target_id' => $match,
        ];

        $account = User::load($match);
        // User is already a member, add it to an array for the Form element
        // to render an error after all checks are gone.
        if ($group->getMember($account)) {
          $duplicated_values[] = $input;
        }

        // Validate input for every single user. This way we make sure that
        // The element validates one, or more users added in the autocomplete.
        // This is because Group doesn't allow adding multiple users at once,
        // so we need to validate single users, if they all pass we can add
        // them all in the _social_group_action_form_submit.
        parent::validateEntityAutocomplete($element, $form_state, $complete_form);
      }
    }

    // If we have duplicates, provide an error message.
    if (!empty($duplicated_values)) {
      $usernames = implode(', ', $duplicated_values);

      $message = \Drupal::translation()->formatPlural(count($duplicated_values),
        "@usernames is already member of the group, you can't add them again",
        "@usernames are already members of the group, you can't add them again",
        ['@usernames' => $usernames]
      );

      // We have to kick in a form set error here, or else the
      // GroupContentCardinalityValidator will kick in and show a faulty
      // error message. Alter this later when Group supports multiple members.
      $form_state->setError($element, $message);
      return;
    }

    if ($value) {
      $form_state->setValue('entity_id_new', $value);
    }
  }
1153274
public function execute() {
        if (!is_enabled_auth('db')) {
            mtrace('auth_db plugin is disabled, synchronisation stopped', 2);
            return;
        }

        $dbauth = get_auth_plugin('db');
        $config = get_config('auth_db');
        $trace = new \text_progress_trace();
        $update = !empty($config->updateusers);
        $dbauth->sync_users($trace, $update);
    }
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);
        }
    }
59767
public function process(ContainerBuilder $container): void
    {
        // The the path ancestor matcher service.
        $definition = $container->getDefinition(PathAncestorMatcher::class);

        // Find the menu voter services and add them.
        $voters = [];
        foreach ($container->findTaggedServiceIds('knp_menu.voter') as $id => $tags) {
            $tag = $tags[0];

            $priority = isset($tag['priority']) ? (int) $tag['priority'] : 0;
            $voters[$priority][] = new Reference($id);
        }

        // Jump out if there are no voter services.
        if (empty($voters)) {
            return;
        }

        // Sort the voters and add them to the matcher.
        krsort($voters);
        $sortedVoters = call_user_func_array('array_merge', $voters);
        $definition->replaceArgument(0, $sortedVoters);
    }
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;
    }
814432
public function makeAuth()
  {
    if (file_exists('App/Controllers/AuthController.php') || file_exists('templates/auth')) {
      $this->errors[] = 'Authorization has already been carried out or there are custom authorization files in the project!';
    }
    if (!empty($this->errors)) {
      echo array_shift($this->errors);
      exit();
    } else {
      $filename = __DIR__ . '../../App/Bulveyz.php';
      $file = file($filename);
      $file[49] .= file_get_contents(__DIR__ . '../../Auth/templates/Bulveyz.txt');
      file_put_contents($filename, $file);

      $authControllerTemplate = file_get_contents(__DIR__ . '../../Auth/templates/AuthController.txt');
      file_put_contents("App/Controllers/AuthController.php", $authControllerTemplate);

      $authRoutes = file_get_contents(__DIR__ . '../../Auth/templates/authRoutes.txt');
      file_put_contents('./routes/web.php', $authRoutes, FILE_APPEND);

      $headerComponent = file_get_contents(__DIR__ . '../../Auth/templates/header.txt');
      file_put_contents("templates/main/header.tmp", $headerComponent);

      $welcomeTemplate = file_get_contents(__DIR__ . '../../Auth/templates/welcome.txt');
      file_put_contents("templates/welcome.tmp", $welcomeTemplate);

      mkdir('templates/auth');
      copy(__DIR__ . '../../Auth/templates/login.txt', 'templates/auth/login.tmp');
      copy(__DIR__ . '../../Auth/templates/register.txt', 'templates/auth/register.tmp');
      copy(__DIR__ . '../../Auth/templates/reset.txt', 'templates/auth/reset.tmp');
      copy(__DIR__ . '../../Auth/templates/restore.txt', 'templates/auth/restore.tmp');
    }
  }
272826
public function refresh()
    {
        $app = Facade::getFacadeApplication();
        $db = $app->make('database')->connection();
        $pkgHandle = false;
        if ($this->pkgID > 0) {
            $pkgHandle = $this->getPackageHandle();
        }

        $class = \Concrete\Core\Block\BlockType\BlockType::getBlockTypeMappedClass($this->btHandle, $pkgHandle);
        $bta = $app->build($class);

        $this->loadFromController($bta);

        $em = \ORM::entityManager();
        $em->persist($this);
        $em->flush();

        $env = Environment::get();
        $r = $env->getRecord(DIRNAME_BLOCKS . '/' . $this->btHandle . '/' . FILENAME_BLOCK_DB, $this->getPackageHandle());
        if ($r->exists()) {
            $parser = Schema::getSchemaParser(simplexml_load_file($r->file));
            $parser->setIgnoreExistingTables(false);
            $toSchema = $parser->parse($db);

            $fromSchema = $db->getSchemaManager()->createSchema();
            $comparator = new \Doctrine\DBAL\Schema\Comparator();
            $schemaDiff = $comparator->compare($fromSchema, $toSchema);
            $saveQueries = $schemaDiff->toSaveSql($db->getDatabasePlatform());
            foreach ($saveQueries as $query) {
                $db->query($query);
            }
        }
    }
1318922
function compile() {
		$code = $this->match_code($this->value) ;

		$id = $this->varid() ;

		if ( $this->optional ) {
			$code = PHPBuilder::build()
				->l(
				$this->save($id),
				$code->replace( array( 'FAIL' => $this->restore($id,true) ))
				);
		}

		if ( $this->zero_or_more ) {
			$code = PHPBuilder::build()
				->b( 'while (true)',
					$this->save($id),
					$code->replace( array(
						'MATCH' => NULL,
						'FAIL' =>
							$this->restore($id,true)
							->l( 'break;' )
					))
				)
				->l(
				'MATCH'
				);
		}

		if ( $this->one_or_more ) {
			$code = PHPBuilder::build()
				->l(
				'$count = 0;'
				)
				->b( 'while (true)',
					$this->save($id),
					$code->replace( array(
						'MATCH' => NULL,
						'FAIL' =>
							$this->restore($id,true)
							->l( 'break;' )
					)),
					'$count += 1;'
				)
				->b( 'if ($count > 0)', 'MATCH' )
				->b( 'else',            'FAIL' );
		}

		if ( $this->positive_lookahead ) {
			$code = PHPBuilder::build()
				->l(
				$this->save($id),
				$code->replace( array(
					'MATCH' =>
						$this->restore($id)
						->l( 'MATCH' ),
					'FAIL' =>
						$this->restore($id)
						->l( 'FAIL' )
				)));
		}

		if ( $this->negative_lookahead ) {
			$code = PHPBuilder::build()
				->l(
				$this->save($id),
				$code->replace( array(
					'MATCH' =>
						$this->restore($id)
						->l( 'FAIL' ),
					'FAIL' =>
						$this->restore($id)
						->l( 'MATCH' )
				)));
		}

		if ( $this->tag && !($this instanceof TokenRecurse ) ) {
			$code = PHPBuilder::build()
				->l(
				'$stack[] = $result; $result = $this->construct( $matchrule, "'.$this->tag.'" ); ',
				$code->replace(array(
					'MATCH' => PHPBuilder::build()
						->l(
						'$subres = $result; $result = array_pop($stack);',
						'$this->store( $result, $subres, \''.$this->tag.'\' );',
						'MATCH'
						),
					'FAIL' => PHPBuilder::build()
						->l(
						'$result = array_pop($stack);',
						'FAIL'
						)
				)));
		}

		return $code ;
	}
1307693
public function code(): string
    {
        $version = config('doorman.uuid.version', 4);

        $method = 'createVersion' . $version . 'Uuid';

        if (method_exists($this, $method)) {
            return $this->$method();
        }

        throw new InvalidArgumentException("Version [$version] not supported.");
    }
886522
static function authenticationMatch()
    {
        $ini = eZINI::instance();
        $matchArray = $ini->variableArray( 'UserSettings', 'AuthenticateMatch' );
        $match = 0;
        foreach ( $matchArray as $matchItem )
        {
            switch ( $matchItem )
            {
                case "login":
                {
                    $match = ( $match | self::AUTHENTICATE_LOGIN );
                } break;
                case "email":
                {
                    $match = ( $match | self::AUTHENTICATE_EMAIL );
                } break;
            }
        }
        return $match;
    }
1009746
function registerMatchServer($serverLogin, $lobbyLogin, $state, $scriptName, $titleIdString, $currentMap)
	{
		$this->db->execute(
			'INSERT INTO MatchServers (login, lobbyLogin, state, lastLive, scriptName, titleIdString, currentMap) '.
			'VALUES(%s, %s, %d, NOW(), %s, %s, %s) '.
			'ON DUPLICATE KEY UPDATE state=VALUES(state), lobbyLogin=VALUES(lobbyLogin), lastLive=VALUES(lastLive), currentMap=VALUES(currentMap)',
			$this->db->quote($serverLogin),
			$this->db->quote($lobbyLogin),
			$state,
			$this->db->quote($scriptName),
			$this->db->quote($titleIdString),
			$this->db->quote($currentMap)
		);
	}
1002193
protected function compile()
  {

    $arrData = array();

    $strWhere = " WHERE member=0";
    if (FE_USER_LOGGED_IN)
    {
      $this->import('FrontendUser', 'User');
      $strWhere = " WHERE member=" . $this->User->id;
    }

    if ($this->showWithoutFilter)
    {
      $strWhere = "";
    }


    if ($this->showTracks)
    {
      $objTracks = $this->Database->prepare("SELECT tl_c4g_tracking_tracks.*, CONCAT('track') as type, count(*) as count FROM tl_c4g_tracking_tracks LEFT JOIN tl_c4g_tracking_positions ON tl_c4g_tracking_positions.track_uuid=tl_c4g_tracking_tracks.uuid" . $strWhere . " GROUP BY tl_c4g_tracking_tracks.id")
                                  ->execute();
      if ($objTracks->numRows > 0)
      {
        $arrTracks = $objTracks->fetchAllAssoc();
        $arrData = array_merge($arrData, $arrTracks);
      }
    }
    if ($this->showPois)
    {
      $objPois = $this->Database->prepare("SELECT *, CONCAT('poi') as type FROM tl_c4g_tracking_pois" . $strWhere)
                                  ->execute();
      if ($objPois->numRows > 0)
      {
        $arrPois = $objPois->fetchAllAssoc();
        $arrData = array_merge($arrData, $arrPois);
      }
    }

    uasort($arrData, array($this, 'sortByTstamp'));

    $arrDataManipulatet = array();

    $blnUseEditLink = false;
    if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null)
		{
      $blnUseEditLink = true;
      $arrJumpTo = $objJumpTo->row();
		}

    foreach ($arrData as $arrEntry)
    {

      $arrEntry['date'] = \Date::parse(\Date::getNumericDateFormat(),$arrEntry['tstamp']);
      $arrEntry['datim'] = \Date::parse(\Date::getNumericDatimFormat(),$arrEntry['tstamp']);
      if ($blnUseEditLink)
      {
        if ($this->editWithoutFilter || (FE_USER_LOGGED_IN && $this->User->id==$arrEntry['member']))
        {
          $arrEntry['editHref'] = ampersand($this->generateFrontendUrl($arrJumpTo, ((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ?  '/' : '/items/') . $arrEntry['type'] . '_' . $arrEntry['id']));
        }
      }

      //((\Config::get('useAutoItem') && !\Config::get('disableAlias')) ?  '/' : '/items/') . ((!\Config::get('disableAlias') && $objItem->alias != '') ? $objItem->alias : $objItem->id)));

      $arrDataManipulatet[] = $arrEntry;
    }

    //print_r($arrDataManipulatet);
    $this->Template->data = $arrDataManipulatet;

  }
186829
public function podiumNew()
    {
        $transaction = static::getDb()->beginTransaction();
        try {
            if (!$this->save()) {
                throw new Exception('Thread saving error!');
            }

            $loggedIn = User::loggedId();

            if ($this->pollAdded && Podium::getInstance()->podiumConfig->get('allow_polls')) {
                $poll = new Poll();
                $poll->thread_id = $this->id;
                $poll->question = $this->pollQuestion;
                $poll->votes = $this->pollVotes;
                $poll->hidden = $this->pollHidden;
                $poll->end_at = !empty($this->pollEnd) ? Podium::getInstance()->formatter->asTimestamp($this->pollEnd . ' 23:59:59') : null;
                $poll->author_id = $loggedIn;
                if (!$poll->save()) {
                    throw new Exception('Poll saving error!');
                }

                foreach ($this->pollAnswers as $answer) {
                    $pollAnswer = new PollAnswer();
                    $pollAnswer->poll_id = $poll->id;
                    $pollAnswer->answer = $answer;
                    if (!$pollAnswer->save()) {
                        throw new Exception('Poll Answer saving error!');
                    }
                }
                Log::info('Poll added', $poll->id, __METHOD__);
            }

            $this->forum->updateCounters(['threads' => 1]);

            $post = new Post();
            $post->content = $this->post;
            $post->thread_id = $this->id;
            $post->forum_id = $this->forum_id;
            $post->author_id = $loggedIn;
            $post->likes = 0;
            $post->dislikes = 0;
            if (!$post->save()) {
                throw new Exception('Post saving error!');
            }

            $post->markSeen();
            $this->forum->updateCounters(['posts' => 1]);
            $this->updateCounters(['posts' => 1]);

            $this->touch('new_post_at');
            $this->touch('edited_post_at');

            if ($this->subscribe) {
                $subscription = new Subscription();
                $subscription->user_id = $loggedIn;
                $subscription->thread_id = $this->id;
                $subscription->post_seen = Subscription::POST_SEEN;
                if (!$subscription->save()) {
                    throw new Exception('Subscription saving error!');
                }
            }

            $transaction->commit();
            PodiumCache::clearAfter('newThread');
            Log::info('Thread added', $this->id, __METHOD__);
            return true;
        } catch (Exception $e) {
            $transaction->rollBack();
            Log::error($e->getMessage(), null, __METHOD__);
        }
        return false;
    }
891583
public function vote(TokenInterface $token, $object, array $attributes)
    {
        if (!$object instanceof Group && !$object instanceof GroupCollection) return VoterInterface::ACCESS_ABSTAIN;
        $groups = $object instanceof GroupCollection ? $object->getGroups(): array($object);
        $action = strtolower($attributes[0]);

        switch ($action) {
            case self::CREATE: return $this->checkCreation($token);
            case self::EDIT:   return $this->checkEdit($token, $groups);
            case self::DELETE: return $this->checkDelete($token, $groups);
            case self::VIEW:   return $this->checkView($token, $groups);
        }

        return VoterInterface::ACCESS_ABSTAIN;
    }