Handle the creating event for the Ban model.

@param \Cog\Contracts\Ban\Ban $ban
@return void
160636
public function creating(BanContract $ban): void
    {
        $bannedBy = auth()->user();
        if ($bannedBy && is_null($ban->created_by_type) && is_null($ban->created_by_id)) {
            $ban->fill([
                'created_by_type' => $bannedBy->getMorphClass(),
                'created_by_id' => $bannedBy->getKey(),
            ]);
        }
    }
217458
public function createConstraint(Constraint $constraint, $table)
    {
        $this->_execSql($this->_platform->getCreateConstraintSQL($constraint, $table));
    }
401506
public function validate($value, Constraint $constraint): void
    {
        Assert::isInstanceOf($value, AttributeValueInterface::class);

        $defaultLocale = $this->localeProvider->getDefaultLocaleCode();
        $configuration = $value->getAttribute()->getConfiguration();

        if ($defaultLocale === $value->getLocaleCode()) {
            $configuration = array_merge($configuration, ['required' => true]);
        }

        /** @var AttributeTypeInterface $attributeType */
        $attributeType = $this->attributeTypeRegistry->get($value->getType());

        $attributeType->validate($value, $this->context, $configuration);
    }
1266351
public function execute() {
        global $DB;

        if (!get_config('tool_monitor', 'enablemonitor')) {
            return; // The tool is disabled. Nothing to do.
        }

        // Array to store which events have been triggered in which course.
        $courses = array();

        // Firstly, let's go through the site wide rules. There may be multiple rules for the site that rely on
        // the same event being triggered, so we only remove the events when they reach the max timewindow.
        if ($siterules = $DB->get_recordset('tool_monitor_rules', array('courseid' => 0), 'timewindow DESC')) {
            // Go through each rule and check if there are any events we can remove.
            foreach ($siterules as $rule) {
                // Check if we have already processed this event.
                if (isset($courses[$rule->courseid][$rule->eventname])) {
                    continue;
                }
                // Store the timewindow for this event.
                $courses[$rule->courseid][$rule->eventname] = $rule->timewindow;
                // Delete any events that may exist that have exceeded the timewindow.
                $DB->delete_records_select('tool_monitor_events', 'eventname = :eventname AND
                    courseid = :courseid AND timecreated <= :timewindow',
                    array('eventname' => $rule->eventname, 'courseid' => $rule->courseid,
                        'timewindow' => time() - $rule->timewindow));
            }
            // Free resources.
            $siterules->close();
        }

        // Now, get the course rules. The same applies here - there may be multiple rules for the course that rely on
        // the same event being triggered, so we only remove the events when they reach the max timewindow.
        if ($rules = $DB->get_recordset_select('tool_monitor_rules', 'courseid != 0', array(), 'timewindow DESC')) {
            // Go through each rule and check if there are any events we can remove.
            foreach ($rules as $rule) {
                // Check if we have already processed this event for this particular course.
                if (isset($courses[$rule->courseid][$rule->eventname])) {
                    continue;
                }
                // Add the course and event to the list.
                $courses[$rule->courseid][$rule->eventname] = $rule->timewindow;
                // If there is a site wide rule listening for this event do not remove it unless the maximum
                // timewindow between the two has exceeded.
                $timewindow = $rule->timewindow;
                if (isset($courses[0][$rule->eventname]) && ($courses[0][$rule->eventname] > $timewindow)) {
                    $timewindow = $courses[0][$rule->eventname];
                }
                // Delete any events that may exist that have exceeded the timewindow.
                $DB->delete_records_select('tool_monitor_events', 'eventname = :eventname AND
                    courseid = :courseid AND timecreated <= :timewindow',
                        array('eventname' => $rule->eventname, 'courseid' => $rule->courseid,
                            'timewindow' => time() - $timewindow));
            }
            // Free resources.
            $rules->close();
        }

        if ($siterules || $rules) { // Check that there are rules present.
            // Get a list of all the events we have been through.
            $allevents = array();
            foreach ($courses as $key => $value) {
                foreach ($courses[$key] as $event => $notused) {
                    $allevents[] = $event;
                }
            }
            // Remove all the events in the table that are not applicable to any rule. There may be a rule in one course
            // listening for a certain event, but not in another course, so we can delete the event from the course
            // where there is no rule. We also have to consider site wide rules. We may have an event that is triggered
            // in a course we can't remove because there is a site wide rule for this event.
            if ($events = $DB->get_recordset('tool_monitor_events')) {
                // Array to store which events we need to remove.
                $eventstodelete = array();
                // Store the current time.
                $now = time();
                foreach ($events as $event) {
                    // If the event is not required for a course rule and there is no site wide rule for it, or
                    // it has extended past or equal to the timewindow for the site rule - it can be deleted.
                    if (!isset($courses[$event->courseid][$event->eventname]) && (!isset($courses[0][$event->eventname])
                        || $courses[0][$event->eventname] <= ($now - $event->timecreated))) {
                        $eventstodelete[] = $event->id;
                    }
                }
                // Free resources.
                $events->close();

                // Remove the events.
                if (!empty($eventstodelete)) {
                    list($eventidsql, $params) = $DB->get_in_or_equal($eventstodelete);
                    $DB->delete_records_select('tool_monitor_events', "id $eventidsql", $params);
                }
            }

            // Remove all the events in the table that are not used by any rule.
            if (!empty($allevents)) {
                list($eventnamesql, $params) = $DB->get_in_or_equal($allevents, SQL_PARAMS_QM, 'param', false);
                $DB->delete_records_select('tool_monitor_events', "eventname $eventnamesql", $params);
            }
        } else { // No rules, just remove everything.
            $DB->delete_records('tool_monitor_events');
        }
    }
789901
protected function _BanFilter($Ban) {
      $BanModel = $this->_BanModel;
      $BanWhere = $BanModel->BanWhere($Ban);
      foreach ($BanWhere as $Name => $Value) {
         if (!in_array($Name, array('u.Admin', 'u.Deleted')))
            return "$Name $Value";
      }
   }
1330001
public function onYiiEvent()
    {
        Event::on(ActiveRecord::className(), ActiveRecord::EVENT_INIT, function ($event) {
            /** @var ActiveRecord $model */
            $model = $event->sender;
            $model->getTableSchema();
        });
    }
992446
protected function createRule($ruleName, $definition)
    {
        echo "    > create rule $ruleName ...";
        $time = microtime(true);

        if (is_array($definition)) {
            $definition['name'] = $ruleName;
        } else {
            $definition = [
                'class' => $definition,
                'name' => $ruleName,
            ];
        }

        /** @var Rule $rule */
        $rule = \Yii::createObject($definition);

        $this->authManager->add($rule);
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";

        return $rule;
    }
126657
protected function registerConsoleCommands(): void
    {
        if ($this->app->runningInConsole()) {
            $this->app->bind('command.ban:delete-expired', DeleteExpiredBans::class);

            $this->commands([
                'command.ban:delete-expired',
            ]);
        }
    }
1364087
public function handle($boris)
    {
        $args = getopt('hvr:', array(
            'help',
            'version',
            'require:'
        ));
        
        foreach ($args as $option => $value) {
            switch ($option) {
                /*
                 * Sets files to load at startup, may be used multiple times,
                 * i.e: boris -r test.php,foo/bar.php -r ba/foo.php --require hey.php
                 */
                case 'r':
                case 'require':
                    $this->_handleRequire($boris, $value);
                    break;
                
                /*
                 * Show Usage info
                 */
                case 'h':
                case 'help':
                    $this->_handleUsageInfo();
                    break;
                
                /*
                 * Show version
                 */
                case 'v':
                case 'version':
                    $this->_handleVersion();
                    break;
            }
        }
    }
863228
public function fire()
    {
        parent::fire();

        if ($this->option('install-ruleset')) {
            if ($this->installRuleset()) {
                $this->info('Copied ruleset to '.$this->pathRulesetLocal);
            }
        }

        $this->info('Runing PHP Mess Detector...');

        $command = $this->pathCli.' ';
        $command.= base_path().'/'.$this->option('path').' ';
        $command.= 'text ';
        $command.= $this->pathRuleset;

        passthru($command, $exitCode);

        $this->info('Done.');

        return $exitCode;
    }
82594
public function Ban($UserID, $Unban = FALSE) {
      $this->Permission('Garden.Moderation.Manage');
      
      $User = Gdn::UserModel()->GetID($UserID, DATASET_TYPE_ARRAY);
      if (!$User)
         throw NotFoundException($User);
      
//      $this->Form = new Gdn_Form();
      
      $UserModel = Gdn::UserModel();

      // Block banning the superadmin or System accounts
      $User = $UserModel->GetID($UserID);
      if (GetValue('Admin', $User) == 2)
         throw ForbiddenException("@You may not ban a System user.");
      elseif (GetValue('Admin', $User))
         throw ForbiddenException("@You may not ban a user with the Admin flag set.");


      if ($this->Form->AuthenticatedPostBack()) {
         if ($Unban) {
            $UserModel->Unban($UserID, array('RestoreContent' => $this->Form->GetFormValue('RestoreContent')));
         } else {
            if (!ValidateRequired($this->Form->GetFormValue('Reason'))) {
               $this->Form->AddError('ValidateRequired', 'Reason');
            }
            if ($this->Form->GetFormValue('Reason') == 'Other' && !ValidateRequired($this->Form->GetFormValue('ReasonText'))) {
               $this->Form->AddError('ValidateRequired', 'Reason Text');
            }

            if ($this->Form->ErrorCount() == 0) {
               if ($this->Form->GetFormValue('Reason') == 'Other')
                  $Reason = $this->Form->GetFormValue('ReasonText');
               else
                  $Reason = $this->Form->GetFormValue('Reason');

               $UserModel->Ban($UserID, array('Reason' => $Reason, 'DeleteContent' => $this->Form->GetFormValue('DeleteContent')));
            }
         }
         
         if ($this->Form->ErrorCount() == 0) {
            // Redirect after a successful save.
            if ($this->Request->Get('Target')) {
               $this->RedirectUrl = $this->Request->Get('Target');
            } elseif ($this->DeliveryType() == DELIVERY_TYPE_ALL) {
               $this->RedirectUrl = Url(UserUrl($User));
            } else {
               $this->JsonTarget('', '', 'Refresh');
            }
         }
      }
      
      $this->SetData('User', $User);
      $this->AddSideMenu();
      $this->Title($Unban ? T('Unban User') : T('Ban User'));
      if ($Unban)
         $this->View = 'Unban';
      $this->Render();
   }
924301
public function extendLoginBan() :void {
		// log the action
		Log::warning("Account {$this->get('login', true)} got its ban period extended due to wrong password");
		// updathe the account
		$this->set([
			'last_failure_date'		=>time(),
			'last_failure_agent'	=>Sec::getSafeUserAgent()
		])->save();
	}
785049
public function unban()
	{
		if ($this->banned)
		{
			$this->banned = false;
			$this->banned_at = null;
			$this->save();
		}
	}
984147
public function setRule($rule)
	{
		if(null === $rule)
		{
			$rule = Dispatch::module() . '/' . Dispatch::control() . '/' . Dispatch::action();
		}
		$this->rule = $rule;
	}
837102
private function execute() {

		if(false === $this -> getExecuted()) {

			foreach($this -> rules as $rule) {

				$file = $this -> getFile($rule -> field, $rule -> prefix);

				//Execute custom extended validator
				if($rule -> closure) {

					if(false === call_user_func($rule -> closure, $rule -> field, $file)) {

						$this -> setPasses(false);

						$instance = $this -> getMessageInstance();
						$instance :: setFieldnames([$rule -> field]);
						$instance :: setError($rule -> prefix, $rule -> field, $rule -> message);
					}

					continue;
				}

				//Execute build in validator
				$class = $this -> getRuleClass($rule -> rule);
				$class = new $class();

				//Set rule data
				$class -> setField($rule -> field);
				$class -> setFile($file);
				$class -> setPrefix($rule -> prefix);
				$class -> setParameters($rule -> parameters);

				//Check if rule passes
				if(false === $this -> isRequired($rule -> field, $file) && false === $class -> isValid()) {

					$this -> setPasses(false);
					$this -> setErrorMessage($rule, $class);
				}
			}

			$this -> setExecuted(true);
		}
	}
123549
public function fire()
    {
        // Disable the exception/error handlers so Boris can handle them
        restore_error_handler();
        restore_exception_handler();
        $this->laravel->make('artisan')->setCatchExceptions(false);

        // Stop the shutdown handler outputting a JSON error object
        $this->laravel->error(function() { return ''; });

        // Run Boris
        $boris = new Boris;
        $boris->start();
    }
801976
public function validate($domainName, Constraint $constraint): void
    {
        if (null === $domainName) {
            return;
        }
        if (false === filter_var($domainName, FILTER_VALIDATE_DOMAIN)
            || false === \ts\stringContains($domainName, '.')
            || false !== \ts\stringContains($domainName, '//')
        ) {
            $this->context->buildViolation(sprintf(DomainName::MESSAGE, $this->formatValue($domainName)))
                          ->setParameter('{{ value }}', $this->formatValue($domainName))
                          ->setCode(DomainName::INVALID_DOMAIN_ERROR)
                          ->addViolation();
        }
    }