sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function parse_array_rules( array $rules ) { $parse_rules = []; foreach ( $rules as $key => $value ) { if ( is_int( $key ) ) { $parse_rules[] = [ $this->normalize( $value ), [] ]; continue; } $key = $this->normalize( $key ); if ( ! is_array( $value ) ) { $value = [ $value ]; } $parse_rules[] = [ $key, $this->wrap_parameters( $key, $value ) ]; } return $parse_rules; }
Parse an array based rule. @param array $rules Array rules set. @return array
entailment
protected function parse_string_rules( $rules ) { $split_rules = explode( '|', $rules ); $parse_rules = []; foreach ( $split_rules as $rule ) { $parameters = []; // Format rule and parameters follows {rule}:{parameters}. if ( strpos( $rule, ':' ) !== false ) { list( $rule, $parameter ) = explode( ':', $rule, 2 ); $parameter = false !== strpos( $parameter, ',' ) ? str_getcsv( $parameter ) : [ $parameter ]; $parameters = $this->wrap_parameters( $rule, $parameter ); } $parse_rules[] = [ $this->normalize( $rule ), $parameters ]; } return $parse_rules; }
Parse a string based rules. @param string $rules String rules set. @return array
entailment
public function handleConfig($routeId, $path, $result, UserContext $context) { $availableMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']; foreach ($result as $version) { // check version $ver = isset($version['version']) ? intval($version['version']) : 0; if ($ver <= 0) { throw new StatusCode\BadRequestException('Version must be a positive integer'); } // check status $status = isset($version['status']) ? $version['status'] : 0; if (!in_array($status, [Resource::STATUS_DEVELOPMENT, Resource::STATUS_ACTIVE, Resource::STATUS_DEPRECATED, Resource::STATUS_CLOSED])) { throw new StatusCode\BadRequestException('Invalid status value'); } $existingMethods = $this->methodTable->getMethods($routeId, $ver, null); if ($status == Resource::STATUS_DEVELOPMENT) { // invalidate resource cache if ($this->listing instanceof CachedListing) { $this->listing->invalidateResource($path, $ver); } // delete all responses from existing responses foreach ($existingMethods as $existingMethod) { $this->responseTable->deleteAllFromMethod($existingMethod['id']); } // delete all methods from existing versions $this->methodTable->deleteAllFromRoute($routeId, $ver); // parse methods $methods = isset($version['methods']) ? $version['methods'] : []; foreach ($methods as $method => $config) { // check method if (!in_array($method, $availableMethods)) { throw new StatusCode\BadRequestException('Invalid request method'); } // create method $methodId = $this->createMethod($routeId, $method, $ver, $status, $config); // create responses $this->createResponses($methodId, $config); } } else { // update only existing methods foreach ($existingMethods as $existingMethod) { if ($existingMethod['status'] == Resource::STATUS_DEVELOPMENT && $status == Resource::STATUS_ACTIVE) { // deploy method to active $this->deployService->deploy($existingMethod); // dispatch event $this->eventDispatcher->dispatch(RoutesEvents::DEPLOY, new DeployedEvent($routeId, $existingMethod, $context)); } elseif ($existingMethod['status'] != $status) { // we can not transition directly from development to // deprecated or closed if ($existingMethod['status'] == Resource::STATUS_DEVELOPMENT && in_array($status, [Resource::STATUS_DEPRECATED, Resource::STATUS_CLOSED])) { throw new StatusCode\BadRequestException('A route can only transition from development to production'); } // change only the status if not in development $this->methodTable->update([ 'id' => $existingMethod['id'], 'status' => $status, ]); } } } } // invalidate resource cache if ($this->listing instanceof CachedListing) { $this->listing->invalidateResourceIndex(new ExternalFilter()); $this->listing->invalidateResourceCollection(null, new ExternalFilter()); $this->listing->invalidateResource($path); } }
Method which handles data change of each API method. Basically an API method can only change if it is in development mode. In every other case we can only change the status @param integer $routeId @param string $path @param \PSX\Record\RecordInterface $result
entailment
public function authenticateUser($username, $password, array $status) { if (empty($password)) { return null; } // allow login either through username or email if (preg_match('/' . BackendSchema\User::NAME_PATTERN . '/', $username)) { $column = 'name'; } else { $column = 'email'; } $condition = new Condition(); $condition->equals($column, $username); $condition->in('status', $status); $user = $this->userTable->getOneBy($condition); if (!empty($user)) { // we can authenticate only local users if ($user['provider'] != ProviderInterface::PROVIDER_SYSTEM) { return null; } if ($user['status'] == Table\User::STATUS_DISABLED) { throw new StatusCode\BadRequestException('The assigned account is disabled'); } if ($user['status'] == Table\User::STATUS_DELETED) { throw new StatusCode\BadRequestException('The assigned account is deleted'); } // check password if (password_verify($password, $user['password'])) { return $user['id']; } else { $this->eventDispatcher->dispatch(UserEvents::FAIL_AUTHENTICATION, new FailedAuthenticationEvent(UserContext::newContext($user['id']))); } } return null; }
Authenticates a user based on the username and password. Returns the user id if the authentication was successful else null @param string $username @param string $password @param array $status @return integer|null
entailment
public function getDefaultScopes() { $scopes = $this->configService->getValue('scopes_default'); return array_filter(array_map('trim', Service\Scope::split($scopes)), function ($scope) { // we filter out the backend scope since this would be a major // security issue return !empty($scope) && $scope != 'backend'; }); }
Returns the default scopes which every new user gets automatically assigned @return array
entailment
protected function yearOrYearNo($year) { if (is_scalar($year)) { return $this->getYear($year); } if (!$year instanceof Year) { throw new InvalidArgumentException( '$year must be an instance of BmCalendar\Year; got "' . get_class($year) . '"' ); } return $year; }
Checks the type of the provided parameter and returns the appropriate Year. @param int|Year $year @return Year @throws InvalidArgumentException
entailment
public function getMonth($year, $monthNo) { $year = $this->yearOrYearNo($year); return new Month($year, $monthNo); }
Returns the appropriate Month object. @param int|Year $year @param int $monthNo @return Month
entailment
public function getMonths($year) { $year = $this->yearOrYearNo($year); $months = array(); for ($monthNo = 1; $monthNo <= 12; $monthNo++) { $months[$monthNo] = new Month($year, $monthNo); } return $months; }
Get this months for the given year. @param int|Year $year @return Month[]
entailment
public function getDay(Month $month, $dayNo) { $dayNo = (int) $dayNo; if (null === $this->dayProvider) { return new Day($month, $dayNo); } $day = $this->dayProvider->createDay($month, $dayNo); if (!$day instanceof DayInterface) { throw new DomainException( '$day must be instance of BmCalendar\DayInterface; got ' . is_object($day) ? get_class($day) : gettype($day) ); } if ($day->value() !== $dayNo) { throw new DomainException( "The value of the day is wrong, it should be $dayNo but is actually " . $day->value() ); } if ($day->getMonth() !== $month) { throw new DomainException( 'The day returned from the day provider contains the wrong Month.' ); } return $day; }
Returns the requested day object. @param Month $month @param int $dayNo @return DayInterface
entailment
public function getDays(Month $month) { $days = array(); for ($dayNo = 1; $dayNo <= $month->numberOfDays(); $dayNo++) { $days[$dayNo] = $this->getDay($month, $dayNo); } return $days; }
Returns all the days for the given month. @param Month $month @return DayInterface[]
entailment
private function getPathFromUri($uri) { $uriParser = new UriParser($uri); // Prepare uri $uriParser->encode(); $uri = $uriParser->stripFragment(); if (strpos($uri, '/') === 0) { // URI is already an path return $uri; } if (!$uriParser->validate()) { throw new \InvalidArgumentException('Invalid URI'); } $path = (($path = parse_url($uri, PHP_URL_PATH)) === null) ? '/' : $path; $query = (($query = parse_url($uri, PHP_URL_QUERY)) === null) ? '' : '?' . $query; return $path . $query; }
Get path and query @param string $uri @return string @throws \InvalidArgumentException
entailment
private function isBetween($timestamp, $fromTime, $toTime, $format = 'Hi') { $dateTime = new DateTime(); $timezone = new DateTimeZone('UTC'); $dtRef = $dateTime->createFromFormat('U', $timestamp, $timezone); $dtFrom = $dateTime->createFromFormat($format, $fromTime, $timezone); $dtTo = $dateTime->createFromFormat($format, $toTime, $timezone); if ($dtFrom > $dtTo) { $dtTo->modify('+1 day'); } return ( $dtFrom <= $dtRef && $dtRef <= $dtTo ) || ( $dtFrom <= $dtRef->modify('+1 day') && $dtRef <= $dtTo ); }
Is time between @param int $timestamp @param string $fromTime @param string $toTime @param string $format @return bool
entailment
private function checkPaths($path, array $paths) { $reserved = [ '?' => '\?', '.' => '\.', '*' => '.*', '+' => '\+', '(' => '\(', ')' => '\)', '[' => '\[', ']' => '\]', ]; $errorHandler = new ErrorHandler(); set_error_handler([$errorHandler, 'callback'], E_NOTICE | E_WARNING); foreach ($paths as $rule) { $escaped = str_replace(array_keys($reserved), array_values($reserved), $rule); if (preg_match('#^' . $escaped . '#', $path) === 1) { restore_error_handler(); return mb_strlen($rule); } } restore_error_handler(); return false; }
Check path rule @param string $path @param string[] $paths @return int|false
entailment
public function add_rule( $name, $rules ) { $parsed = ( new Validation_Parser() )->parse( $rules ); foreach ( $parsed as $rule ) { $this->rule( $rule[0], $name, ...$rule[1] ); } return $this; }
Add a single validation rule. @param string $name The field name. @param array|string $rules The rules. @return $this
entailment
public function add_rules( array $rules ) { foreach ( $rules as $name => $rule ) { $this->add_rule( $name, $rule ); } return $this; }
Sets a multiple rules for the validation. @param array $rules Array rules. @return $this
entailment
public function handle(Delay\ManageInterface $handler) { return $handler->base($this->base, $this->product, $this->getValue()); }
Handle delay @param Delay\ManageInterface $handler @return Delay\BaseInterface
entailment
public function jsonSerialize() { return array( 'type' => $this->getType(), 'bodyText' => $this->getBodyText(), 'bodyHtml' => $this->getBodyHtml(), 'recipients' => $this->getRecipients(), 'from' => $this->getFrom(), 'subject' => $this->getSubject(), 'text' => quoted_printable_decode($this->getBodyText(true)), 'html' => quoted_printable_decode($this->getBodyHtml(true)) ); }
Specify data which should be serialized to JSON @link http://php.net/manual/en/jsonserializable.jsonserialize.php @return mixed data which can be serialized by <b>json_encode</b>, which is a value of any type other than a resource. @since 5.4.0
entailment
private function rmdir($dir) { // remove all files $files = scandir($dir); foreach ($files as $file) { if ($file == '.' || $file == '..') { continue; } $path = $dir . '/' . $file; if (is_dir($path)) { $this->rmdir($path); } elseif (is_file($path)) { unlink($path); } } rmdir($dir); }
Removes all files inside a directory recursively @param string $dir
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('four_labs_gamp'); $rootNode ->children() ->integerNode('protocol_version') ->defaultValue(1) ->end() ->scalarNode('tracking_id') ->isRequired() ->cannotBeEmpty() ->end() ->booleanNode('use_ssl') ->defaultTrue() ->end() ->booleanNode('anonymize_ip') ->defaultFalse() ->end() ->booleanNode('async_requests') ->defaultTrue() ->end() ->booleanNode('sandbox') ->defaultFalse() ->end() ->end() ; return $treeBuilder; }
{@inheritdoc}
entailment
protected function _initSelect() { $request = $this->_objectManager->get('Magento\Framework\App\RequestInterface'); $this->getSelect()->from(['main_table' => $this->getMainTable()]); if(!empty($customerId = $request->getParam('id'))) { $this->getSelect()->where('customer_id = ?', $customerId); } return $this; }
Init collection select @return $this
entailment
public function isVisitTime($timestamp = null) { $timestamp = is_int($timestamp) ? $timestamp : time(); foreach ($this->times as $time) { if ($this->isBetween($timestamp, $time['from'], $time['to'], 'Hi')) { return true; } } return empty($this->times); }
Is visit-time @param int|null $timestamp @return bool
entailment
public function hasSchema($schemaId) { $sql = ' SELECT COUNT(resp.id) AS cnt FROM fusio_routes_response resp INNER JOIN fusio_routes_method method ON resp.method_id = method.id INNER JOIN fusio_routes routes ON routes.id = method.route_id WHERE routes.status = 1 AND (method.parameters = :schema_id OR method.request = :schema_id OR resp.response = :schema_id)'; $count = $this->connection->fetchColumn($sql, [ 'schema_id' => $schemaId, ]); return $count > 0; }
Returns whether a schema id is in use by a route. In the worst case this gets reported by the database constraints but we use this method to report a proper error message @param integer $schemaId @return boolean
entailment
public function hasAction($actionId) { $sql = ' SELECT COUNT(method.id) AS cnt FROM fusio_routes_method method INNER JOIN fusio_routes routes ON routes.id = method.route_id WHERE routes.status = 1 AND method.action = :action_id'; $count = $this->connection->fetchColumn($sql, [ 'action_id' => $actionId, ]); return $count > 0; }
Returns whether a action id is in use by a route. In the worst case this gets reported by the database constraints but we use this method to report a proper error message @param integer $actionId @return boolean
entailment
public function getMethods($routeId, $version = null, $active = true, $cache = false) { $fields = ['method.id', 'method.route_id', 'method.version', 'method.status', 'method.method', 'method.active', 'method.public', 'method.description', 'method.parameters', 'method.request', 'method.action', 'method.costs']; if ($cache) { $fields[] = 'method.schema_cache'; } $sql = ' SELECT ' . implode(',', $fields) . ' FROM fusio_routes_method method WHERE method.route_id = :route_id'; $params = ['route_id' => $routeId]; if ($active !== null) { $sql.= ' AND method.active = ' . ($active ? '1' : '0'); } if ($version !== null) { $sql.= ' AND method.version = :version'; $params['version'] = $version; } $sql.= ' ORDER BY method.version ASC, method.id ASC'; return $this->project($sql, $params); }
Returns only active methods for the route @param integer $routeId @param integer $version @param boolean $active @param boolean $cache @return array
entailment
public function sanitization( $value ) { return Utils::sanitize_recursive( $this->parse_value( $value ), function ( $_value ) { return sanitize_text_field( wp_unslash( $_value ) ); } ); }
{@inheritdoc}
entailment
public function parse_value( $value ) { if ( is_array( $this->defaults ) ) { $value = is_array( $value ) ? wp_parse_args( $value, $this->defaults ) : $this->defaults; } return $value; }
Parse the value, merge with $defaults. @param mixed $value @return array|mixed
entailment
public function detectWithCommon($uri, array $customParam = []) { $pairs = array_merge_recursive( $this->cleanParam, $this->appendPath($this->commonParam), $this->appendPath($customParam) ); return $this->parse($uri, $pairs); }
Has robots.txt defined dynamic or common dynamic parameters check @param string $uri @param string[] $customParam @return string[]
entailment
protected function parse($uri, array $pairs) { $path = $this->getPathFromUri($uri); $result = []; foreach ($pairs as $param => $paths) { if (( strpos($uri, "?$param=") || strpos($uri, "&$param=") ) && $this->checkPaths($path, $paths) !== false ) { $result[] = $param; } } sort($result); return $result; }
Parse uri and return detected parameters @param string $uri @param array $pairs @return string[]
entailment
private function request($options = []) { $curl = curl_init(); $caPathOrFile = CaBundle::getSystemCaRootBundlePath(); // Set default cURL options curl_setopt_array($curl, [ CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_ENCODING => 'identity', CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_NONE, CURLOPT_IPRESOLVE => CURL_IPRESOLVE_WHATEVER, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_TIMEOUT => 120, CURLOPT_USERAGENT => self::CURL_USER_AGENT, (is_dir($caPathOrFile) || ( is_link($caPathOrFile) && is_dir(readlink($caPathOrFile)) ) ) ? CURLOPT_CAPATH : CURLOPT_CAINFO => $caPathOrFile ]); if (PHP_VERSION_ID >= 70700) { curl_setopt($curl, CURLOPT_SSL_VERIFYSTATUS, true); } // Apply custom cURL options curl_setopt_array($curl, $options); // Initialize the header parser $this->headerParser = new Parser\HeaderParser($curl); // Make sure these cURL options stays untouched curl_setopt_array($curl, [ CURLOPT_FAILONERROR => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_FTPSSLAUTH => CURLFTPAUTH_DEFAULT, CURLOPT_HEADER => false, CURLOPT_HEADERFUNCTION => [$this->headerParser, 'curlCallback'], CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_MAXREDIRS => self::MAX_REDIRECTS, CURLOPT_NOBODY => false, CURLOPT_PROTOCOLS => CURLPROTO_FTP | CURLPROTO_FTPS | CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_SFTP, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_FTP | CURLPROTO_FTPS | CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_SFTP, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $this->base . self::PATH, CURLOPT_USERPWD => 'anonymous:anonymous@', ]); // Execute cURL request if (($this->rawContents = curl_exec($curl)) === false) { // Request failed return false; } $this->time = time(); $this->rawStatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); // also works with FTP status codes $uriParser = new UriParser(curl_getinfo($curl, CURLINFO_EFFECTIVE_URL)); $this->effective = $uriParser->base(); curl_close($curl); $this->rawEncoding = $this->headerParser->getCharset(); $this->rawMaxAge = $this->headerParser->getMaxAge(); return true; }
cURL request @param array $options @return bool
entailment
public function getStatusCode() { $statusCodeParser = new StatusCodeParser($this->rawStatusCode, parse_url($this->effective, PHP_URL_SCHEME)); return $statusCodeParser->isValid() ? $this->rawStatusCode : null; }
Status code @return int|null
entailment
public function nextUpdate() { if ($this->rawStatusCode === 503 && strpos($this->base, 'http') === 0 ) { return $this->time + min(self::CACHE_TIME, $this->headerParser->getRetryAfter($this->time)); } return $this->time + self::CACHE_TIME; }
Next update timestamp @return int
entailment
private function sort() { if ($this->sort) { return $this->sort; }; return $this->sort = array_multisort($this->cleanParam) && ksort($this->cleanParam); }
Sort by length @return bool
entailment
public function add($line) { $path = '/'; // split into parameter and path $array = array_map('trim', mb_split('\s+', $line, 2)); if (isset($array[1])) { // strip any invalid characters from path prefix $uriParser = new UriParser(preg_replace('/[^A-Za-z0-9\.-\/\*\_]/', '', $array[1])); $path = rtrim($uriParser->encode(), '*'); // make sure path is valid $path = in_array(substr($path, 0, 1), [ '/', '*', ]) ? $path : '/'; } $param = array_map('trim', explode('&', $array[0])); foreach ($param as $key) { $this->cleanParam[$key][] = $path; } return true; }
Add @param string $line @return bool
entailment
public function render(RenderHandler $handler) { $this->sort(); return $handler->getLevel() == 2 ? $this->renderExtensive($handler) : $this->renderCompressed($handler); }
Render @param RenderHandler $handler @return bool
entailment
private function renderExtensive(RenderHandler $handler) { foreach ($this->cleanParam as $param => $paths) { foreach ($paths as $path) { $handler->add(self::DIRECTIVE_CLEAN_PARAM, $param . ' ' . $path); } } return true; }
Render extensive @param RenderHandler $handler @return bool
entailment
private function renderCompressed(RenderHandler $handler) { $pair = $this->cleanParam; while (($currentPair = current($pair)) !== false) { $equalParams = array_keys($pair, $currentPair); foreach ($currentPair as $path) { $handler->add(self::DIRECTIVE_CLEAN_PARAM, implode('&', $equalParams) . ' ' . $path); } foreach ($equalParams as $param) { unset($pair[$param]); } } return true; }
Render compressed @param RenderHandler $handler @return bool
entailment
public function setParams($arr = []) { foreach ($arr as $key => $value) { $this->params[$key] = $value; } }
/* Sets custom params @param array $arr @return void
entailment
private function generate($level, $eol) { $handler = new RenderHandler($level, $eol); if ($level == 2) { $this->root->userAgent->render($handler); } $this->root->host->render($handler); $this->root->cleanParam->render($handler); $this->root->sitemap->render($handler); if ($level != 2) { $this->root->userAgent->render($handler); } return $handler->generate(); }
Generate an rule string array @param int $level @param string $eol @return string
entailment
public function execute() { $mailId = $this->_request->getParam('id'); $this->_mail = $this->_objectManager->get('\Shockwavemk\Mail\Base\Model\Mail'); $this->_mail->load($mailId); $this->_view->loadLayout(); $this->_view->getPage()->getConfig()->getTitle()->prepend(__($this->_mail->getSubject())); $this->_view->renderLayout(); }
Preview Newsletter template @return void|$this
entailment
public function addChild(RoleInterface $role) { if (!$this->hasChild($role)) { $role->setParent($this); $this->children->add($role); } }
{@inheritdoc}
entailment
public function removeChild(RoleInterface $role) { if ($this->hasChild($role)) { $role->setParent(null); $this->children->removeElement($role); } }
{@inheritdoc}
entailment
public function addPermission(PermissionInterface $permission) { if (!$this->hasPermission($permission)) { $this->permissions->add($permission); } }
{@inheritdoc}
entailment
public function removePermission(PermissionInterface $permission) { if ($this->hasPermission($permission)) { $this->permissions->removeElement($permission); } }
{@inheritdoc}
entailment
protected function getWsdlElementAttributes($comment) { $nillable = $minOccurs = $maxOccurs = null; if (preg_match('/{(.+)}/', $comment, $attr)) { if (preg_match_all('/((\w+)\s*=\s*(\w+))/mi', $attr[1], $attr)) { foreach ($attr[2] as $id => $prop) { $prop = strtolower($prop); $val = strtolower($attr[3][$id]); if ($prop == 'nillable') { if ($val == 'false' || $val == 'true') { $nillable = $val; } else { $nillable = $val ? 'true' : 'false'; } } elseif ($prop == 'minoccurs') { $minOccurs = intval($val); } elseif ($prop == 'maxoccurs') { $maxOccurs = ($val == 'unbounded') ? 'unbounded' : intval($val); } } } } return [ 'nillable' => $nillable, 'minOccurs' => $minOccurs, 'maxOccurs' => $maxOccurs ]; }
Parse attributes nillable, minOccurs, maxOccurs @param string $comment Extracted PHPDoc comment @return array
entailment
protected function injectDom(\DOMDocument $dom, \DOMElement $target, \DOMNode $source) { if ($source->nodeType != XML_ELEMENT_NODE) { return; } $import = $dom->createElement($source->nodeName); foreach ($source->attributes as $attr) { $import->setAttribute($attr->name, $attr->value); } foreach ($source->childNodes as $child) { $this->injectDom($dom, $import, $child); } $target->appendChild($import); }
Import custom XML source node into WSDL document under specified target node @param \DOMDocument $dom XML WSDL document being generated @param \DOMElement $target XML node, to which will be appended $source node @param \DOMNode $source Source XML node to be imported
entailment
public function buildHtmlDocs($return = false) { $html = '<html><head>'; $html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'; $html .= '<style type="text/css"> table{border-collapse: collapse;background-color: #DDDDDD;} tr{background-color: #FFFFFF;} th{background-color: #EEEEEE;} th, td{font-size: 12px;font-family: courier;padding: 3px;} </style>'; $html .= '</head><body>'; $html .= '<h2>WSDL documentation for service ' . $this->serviceName . '</h2>'; $html .= '<p>Generated on ' . date('d.m.Y H:i:s') . '</p>'; $html .= '<table border="0" cellspacing="1" cellpadding="1">'; $html .= '<tr><td>'; if (!empty($this->types)) { foreach ($this->types as $object => $options) { if (!is_array($options) || empty($options) || !is_array($options['properties']) || empty($options['properties'])) { continue; } $params = $options['properties']; $html .= "\n\n<h3>Object: {$object}</h3>"; $html .= '<table border="1" cellspacing="1" cellpadding="1">'; $html .= '<tr><th>#</th><th>Attribute</th><th>Type</th><th>Nill</th><th>Min</th><th>Max</th><th>Description</th><th>Example</th></tr>'; $c = 0; foreach ($params as $param => $prop) { ++$c; $html .= <<<HTML <tr> <td>{$c}</td> <td>{$param}</td> <td>{(str_replace('xsd:', '', $prop[0]))}</td> <td>{$prop[2]}</td> <td>{($prop[3] == null ? '&nbsp;' : $prop[3])}</td> <td>{($prop[4] == null ? '&nbsp;' : $prop[4])}</td> <td>{$prop[1]}</td> <td>{(trim($prop[5]) == '' ? '&nbsp;' : $prop[5])}</td> </tr> HTML; } $html .= '\n</table><br/>'; } } else { $html .= 'No complex data type found!'; } $html .= '</td></tr></table></body></html>'; if ($return) { return $html; } echo $html; Yii::$app->end(); // end the app to avoid conflict with text/xml header }
Generate human friendly HTML documentation for complex data types. This method can be invoked either by inserting URL parameter "&makedoc" into URL link, e.g. "http://www.mydomain.com/soap/create?makedoc", or simply by calling from another script with argument $return=true. Each complex data type is described in a separate HTML table containing following columns: <ul> <li># - attribute ID</li> <li>Attribute - attribute name, e.g. firstname</li> <li>Type - attribute type, e.g. integer, date, tns:SoapPovCalculationResultArray</li> <li>Nill - true|false - whether the attribute is nillable</li> <li>Min - minimum number of occurrences</li> <li>Max - maximum number of occurrences</li> <li>Description - Detailed description of the attribute.</li> <li>Example - Attribute example value if provided via PHPDoc property @example.</li> </ul> @param bool $return If true, generated HTML output will be returned rather than directly sent to output buffer @return string @throws \yii\base\ExitException
entailment
public function supports(ExampleNode $example): bool { return count($this->getRequirements($this->getDocComment($example))) > 0; }
{@inheritdoc}
entailment
public function prepare( ExampleNode $example, Specification $context, MatcherManager $matchers, CollaboratorManager $collaborators ): void { foreach ($this->getRequirements($this->getDocComment($example)) as $requirement) { if (!class_exists($requirement) && !interface_exists($requirement)) { throw new SkippingException( sprintf('"%s" is not available', $requirement) ); } } }
{@inheritdoc}
entailment
private function getRequirements(string $docComment): array { return array_map( function($tag) { preg_match('#@require ([^ ]*)#', $tag, $match); return $match[1]; }, array_filter( array_map( 'trim', explode( "\n", str_replace( "\r\n", "\n", $docComment ) ) ), function($docline) { return 0 === strpos($docline, '* @require'); } ) ); }
Get required interfaces @param string $docComment @return array
entailment
public function client() { return new HostClient($this->base, $this->effective, isset($this->host[0]) ? [$this->host[0]] : []); }
Client @return HostClient
entailment
public function render(RenderHandler $handler) { if (isset($this->host[0])) { $handler->add(self::DIRECTIVE_HOST, $this->host[0]); } return true; }
Render @param RenderHandler $handler @return bool
entailment
protected function initFilters() { if (!empty($this->filters)) { foreach ($this->filters as $name => $handler) { $this->addFilter($name, $handler); } } }
Add custom filters from ViewRenderer `filters` parameter.
entailment
protected function initCachePath() { $cachePath = empty($this->cachePath) ? false : Yii::getAlias($this->cachePath); if (!empty($cachePath) && !file_exists($cachePath)) { FileHelper::createDirectory($cachePath); } return $cachePath; }
Create if needed and return the cache path calculated from ViewRenderer `cachePath` parameter. @throws \yii\base\Exception @return bool|string
entailment
public function init() { $cachePath = $this->initCachePath(); // @codeCoverageIgnoreStart if (!empty($cachePath) && !is_readable($cachePath)) { throw new Exception(Yii::t('app', 'Pug cache path is not readable.')); } if (!empty($cachePath) && !is_writable($cachePath)) { throw new Exception(Yii::t('app', 'Pug cache path is not writable.')); } // @codeCoverageIgnoreEnd $className = empty($this->renderer) ? 'Pug\\Pug' : $this->renderer; $baseDir = realpath(Yii::getAlias($this->viewPath)); $this->pug = new $className(array_merge([ 'cache' => $cachePath, // pug-php 2 'cache_dir' => $cachePath, // phug / pug-php 3 'cache_path' => $cachePath, // tale-pug 'basedir' => $baseDir, // pug-php 2 'paths' => [$baseDir], // phug / pug-php 3 ], $this->options)); $this->initFilters(); }
Create the pug renderer engine. @throws Exception @throws \yii\base\Exception
entailment
public function render($view, $file, $params) { $method = method_exists($this->pug, 'renderFile') ? [$this->pug, 'renderFile'] : [$this->pug, 'render']; // @codeCoverageIgnoreStart if ($this->pug instanceof \Tale\Pug\Renderer && !($this->pug instanceof \Phug\Renderer)) { $this->pug->compile(''); // Init ->files $path = realpath(Yii::getAlias($this->viewPath)); $pieces = explode($path, realpath($file), 2); if (count($pieces) === 2) { $file = ltrim($pieces[1], '\\/'); } } // @codeCoverageIgnoreEnd $systemVariables = [ 'app' => Yii::$app, 'view' => $view, ]; if ($this->systemVariable) { $systemVariables = [ $this->systemVariable => (object) $systemVariables, ]; } return call_user_func($method, $file, array_merge($systemVariables, $params)); }
Renders a view file. This method is invoked by [[View]] whenever it tries to render a view. Child classes must implement this method to render the given view file. @param View $view the view object used for rendering the file. @param string $file the view file. @param array $params the parameters to be passed to the view file. @return string the rendering result
entailment
public function addFilter($name, $handler) { if (is_string($handler) && !is_callable($handler)) { $handler = new $handler(); } $this->pug->filter($name, $handler); }
Adds custom filter. @param string $name @param callable $handler
entailment
public function execute() { // Get request data $mailId = $this->_request->getParam('id'); $recalculate = $this->_request->getParam('resend_type'); // Email address to re-send mail $email = $this->_request->getParam('email'); /** @var \Shockwavemk\Mail\Base\Model\Mail $mail */ $mail = $this->_objectManager->get('Shockwavemk\Mail\Base\Model\Mail'); $mail->load($mailId); /** @noinspection IsEmptyFunctionUsageInspection */ if(empty($mailId) || empty($mail->getId())) { $redirectUrl = $this->_buildUrl( 'customer/mail/edit', ['_secure' => true, 'id' => $mailId] ); $this->messageManager->addException(new \Exception( __('Mail can not be loaded.')), __('Mail can not be loaded.') ); return $this->resultRedirectFactory ->create() ->setUrl( $this->_redirect->error($redirectUrl) ); } try { // Get information of parent mail /** @var MessageInterface $parentMessage */ $parentMessage = $mail->getMessage(); /** @var AttachmentInterface[] $parentAttachments */ $parentAttachments = $mail->getAttachments(); $parentCustomerId = $mail->getCustomerId(); // Set parent id to allow parent links in frontend $mail->setParentId( $mail->getId() ); // On given $email if(!empty($email)) { $recipients = [$email]; } else { $recipients = $mail->getRecipients(); } // Derive a transportBuilder from existing Mail $transportBuilder = $this->deriveTransportBuilderFromExistingMail($mail); $this->applyRecipientsOnTransportBuilder($recipients, $transportBuilder); /** @noinspection IsEmptyFunctionUsageInspection */ if(!empty($recalculate) && $recalculate === 'recalculate') { $transport = $transportBuilder->getTransport(); } else { $transport = $transportBuilder->getBackupTransport($parentMessage); } $transport->getMail() ->setAttachments($parentAttachments) ->setCustomerId($parentCustomerId) ; /** @var \Shockwavemk\Mail\Base\Model\Transports\TransportInterface $transport */ $transport->sendMessage(); $this->messageManager->addSuccess(__('Mail re-sent to customer.')); $url = $this->_buildUrl( 'customer/mail/edit', [ '_secure' => true, 'id' => $transport->getMail()->getId() ] ); return $this->resultRedirectFactory->create()->setUrl($this->_redirect->success($url)); } catch (InputException $e) { $this->messageManager->addError($e->getMessage()); foreach ($e->getErrors() as $error) { $this->messageManager->addError( $error->getMessage() ); } } catch (\Exception $e) { $this->messageManager->addException( $e, __($e->getMessage()) ); } $redirectUrl = $this->_buildUrl( 'customer/mail/send', ['_secure' => true, 'id' => $mailId] ); return $this->resultRedirectFactory->create()->setUrl( $this->_redirect->error($redirectUrl) ); }
Resend mail @return void|$this
entailment
protected function deriveTransportBuilderFromExistingMail($mail) { return $this->transportBuilder ->setTemplateIdentifier($mail->getTemplateIdentifier()) ->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => $mail->getStoreId()]) ->setTemplateVars($mail->getVars()) ->setFrom($mail->getSenderMail()); }
TODO @param \Shockwavemk\Mail\Base\Model\Mail $mail @return TransportBuilder @throws \Magento\Framework\Exception\MailException
entailment
public function getStyle() { $style = ''; // Always add fixed height as a fallback if autosetting or JS fails. $height = $this->FixedHeight; if (!$height) { $height = 800; } $style .= "height: {$height}px; "; if ($this->AutoWidth) { $style .= "width: 100%; "; } elseif ($this->FixedWidth) { $style .= "width: {$this->FixedWidth}px; "; } return $style; }
Compute style from the size parameters.
entailment
public function validate() { $result = parent::validate(); //whitelist allowed URL schemes $allowed_schemes = array('http', 'https'); if ($matches = parse_url($this->IFrameURL)) { if (isset($matches['scheme']) && !in_array($matches['scheme'], $allowed_schemes)) { $result->addError(_t(__CLASS__ . '.VALIDATION_BANNEDURLSCHEME', "This URL scheme is not allowed.")); } } return $result; }
Ensure that the IFrameURL is a valid url and prevents XSS @throws ValidationException @return ValidationResult
entailment
protected function prepareMessage() { $template = $this->getTemplate(); $types = [ TemplateTypesInterface::TYPE_TEXT => MessageInterface::TYPE_TEXT, TemplateTypesInterface::TYPE_HTML => MessageInterface::TYPE_HTML, ]; // Bugfix for not translated cron scheduled mails $areaObject = $this->areaList->getArea($template->getDesignConfig()->getArea()); $areaObject->load(\Magento\Framework\App\Area::PART_TRANSLATE); $body = $template->processTemplate(); $this->message->setMessageType($types[$template->getType()]) ->setBody($body) ->setSubject($template->getSubject()); return $this; }
Prepare message @return $this @throws \Zend_Mail_Exception
entailment
public function getMail() { /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($this->_mail)) { $this->_mail = $this->objectManager ->create('Shockwavemk\Mail\Base\Model\Mail'); /** @var \Shockwavemk\Mail\Base\Model\Mail\AttachmentCollection $attachmentCollection */ $attachmentCollection = $this->objectManager ->get('Shockwavemk\Mail\Base\Model\Mail\AttachmentCollection'); foreach ($attachmentCollection as $attachment) { $this->_mail->addAttachment($attachment); } } return $this->_mail; }
Get mail @return \Shockwavemk\Mail\Base\Model\Mail @throws \Magento\Framework\Exception\MailException
entailment
public function setFrom($from) { $result = $this->_senderResolver->resolve($from, $this->getStoreId()); $this->setSenderMail($result); $this->message->setFrom($result['email'], $result['name']); return $this; }
Set mail from address @param string|array $from @return $this @throws \Magento\Framework\Exception\MailException
entailment
public function execute() { $encodedId = $this->_request->getParam('id'); /** @var \Shockwavemk\Mail\Base\Model\Mail $_mail */ $mail = $this->_objectManager->get('\Shockwavemk\Mail\Base\Model\Mail'); $mail->load(base64_decode($encodedId)); $encodedPath = $this->_request->getParam('path'); $localPath = base64_decode($encodedPath); /** @var \Shockwavemk\Mail\Base\Model\Mail\Attachment[] $attachments */ $attachments = $mail->getAttachments(); /** @var \Shockwavemk\Mail\Base\Model\Mail\Attachment $attachment */ /** @noinspection IsEmptyFunctionUsageInspection */ if(empty($attachment = $attachments[$localPath])) { $this->messageManager->addError( __('Sorry, there was an error getting requested content. Please contact the store owner.') ); return $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); } try { $this->_processDownload($attachment); exit(0); } catch (\Exception $e) { $this->messageManager->addError( __('Sorry, there was an error getting requested content. Please contact the store owner: ' . $e->getMessage()) ); } return $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); }
Preview Newsletter template @return void|$this
entailment
public static function compare(LocaleInterface $x, LocaleInterface $y) { return strcmp($x->endonymSortable(), $y->endonymSortable()); }
Callback for PHP sort functions - allows lists of locales to be sorted. Diacritics are removed and text is capitalized to allow fast/simple sorting. @param LocaleInterface $x @param LocaleInterface $y @return int
entailment
public static function create($code) { $class = __NAMESPACE__ . '\Locale\Locale' . implode(array_map(function ($x) { return ucfirst(strtolower($x)); }, preg_split('/[^a-zA-Z0-9]+/', $code))); if (class_exists($class)) { return new $class(); } throw new DomainException($code); }
Create a locale from a language tag (or locale code). @param string $code @return LocaleInterface @throws DomainException
entailment
public static function httpAcceptLanguage(array $server, array $available, LocaleInterface $default) { if (!empty($server['HTTP_ACCEPT_LANGUAGE'])) { $http_accept_language = strtolower(str_replace(' ', '', $server['HTTP_ACCEPT_LANGUAGE'])); preg_match_all('/(?:([a-z][a-z0-9_-]+)(?:;q=([0-9.]+))?)/', $http_accept_language, $match); $preferences = array_map(function ($x) { return $x === '' ? 1.0 : (float) $x; }, array_combine($match[1], $match[2])); // Need a stable sort, as the original order is significant $preferences = array_map(function ($x) { static $n = 0; return array($x, --$n); }, $preferences); arsort($preferences); $preferences = array_map(function ($x) { return $x[0]; }, $preferences); // "Common sense" logic for badly configured clients. $preferences = self::httpAcceptChinese($preferences); $preferences = self::httpAcceptDowngrade($preferences); foreach (array_keys($preferences) as $code) { try { $locale = Locale::create($code); if (in_array($locale, $available)) { return $locale; } } catch (DomainException $ex) { // An unknown locale? Ignore it. } } } return $default; }
Create a locale from a language tag (or locale code). @param string[] $server The $_SERVER array @param LocaleInterface[] $available All locales supported by the application @param LocaleInterface $default Locale to show in no matching locales @return LocaleInterface
entailment
private static function httpAcceptDowngrade($preferences) { foreach ($preferences as $code => $priority) { // Three parts: "zh-hans-cn" => "zh-hans" and "zh" if (preg_match('/^(([a-z]+)-[a-z]+)-[a-z]+$/', $code, $match)) { if (!isset($preferences[$match[2]])) { $preferences[$match[2]] = $priority * 0.5; } if (!isset($preferences[$match[1]])) { $preferences[$match[1]] = $priority * 0.5; } } // Two parts: "de-de" => "de" if (preg_match('/^([a-z]+)-[a-z]+$/', $code, $match) && !isset($preferences[$match[1]])) { $preferences[$match[1]] = $priority * 0.5; } } return $preferences; }
If a client requests "de-DE" (but not "de"), then add "de" as a lower-priority fallback. @param $preferences @return int[]
entailment
private static function httpAcceptChinese($preferences) { foreach (self::$http_accept_chinese as $old => $new) { if (array_key_exists($old, $preferences) && !array_key_exists($new, $preferences)) { $preferences[$new] = $preferences[$old] * 0.5; } } return $preferences; }
Some browsers allow the user to select "Chinese (simplified)", but then use zh-CN instead of zh-Hans. This goes against the advice of w3.org. @param int[] $preferences @return int[]
entailment
public function get_field( $field, $field_group = null, $deprecated = false ) { if ( $field instanceof \CMB2_Field ) { $field = $field->id( true ); } $field = is_array( $field ) ? $field['id'] : (string) $field; if ( $field_group ) { return $this->get_field_in_group( $field_group, $field ); } return $this->get_new_field( $this->get_field_raw( $field ) ); }
{@inheritdoc}
entailment
public function get_field_in_group( $field_group, $sub_field ) { if ( ! $field_group instanceof Field_Contract ) { $field_group = $this->get_field( $field_group ); } if ( ! $field_group || 'group' !== $field_group->get_type() ) { return null; } $sub_fields = $field_group->prop( 'fields', [] ); if ( ! array_key_exists( $sub_field, $sub_fields ) ) { return null; } return $this->get_new_field( $sub_fields[ $sub_field ], $field_group ); }
Gets a field in a group. @param \WPLibs\Form\Contracts\Field|string $field_group @param string $sub_field @return \WPLibs\Form\Contracts\Field|null
entailment
public function get_field_raw( $field ) { if ( array_key_exists( $field, $this->prop( 'fields' ) ) ) { return $this->prop( 'fields' )[ $field ]; } return null; }
Return the field raw @param string $field @return array|null
entailment
protected function get_new_field( $field_args, $field_group = null ) { if ( 'group' === $field_args['type'] ) { return new Field_Group( $this, $this->get_default_args( $field_args ) ); } return new Field( $this, $this->get_default_args( $field_args, $field_group ) ); }
{@inheritdoc}
entailment
public function get($type) { if ($type === self::TYPE_MAILER) { $name = $this->configService->getValue('system_mailer'); } elseif ($type === self::TYPE_DISPATCHER) { $name = $this->configService->getValue('system_dispatcher'); } else { throw new \InvalidArgumentException('Provided type does not exist'); } if (empty($name)) { return null; } return $this->connector->getConnection($name); }
Returns a configured connection from the provided type @param string $type @return mixed|null
entailment
public function add_group( $args, $position = 0 ) { $args['type'] = 'group'; $id = $this->add_field( $args, $position ); return new Group_Builder( $this, $id ); }
{@inheritdoc}
entailment
public function skip_fill_types( $types ) { $this->skip_fill_types = array_unique( array_merge( $this->skip_fill_types, $types ) ); return $this; }
{@inheritdoc}
entailment
public function set_option( $name, $value ) { $this->throws_if_locked(); $this->set_prop( $name, $value ); return $this; }
{@inheritdoc}
entailment
protected function initSources(array $sources) { foreach ($sources as $source) { $this->sources[] = new EntitySource($this, $source); } }
Populate the sources array. This is called from the constructor, and can be overridden in subclasses. @param array $sources The sources as an array of \SimpleSAML\Configuration objects. @return void
entailment
public static function getAggregator($id) { assert('is_string($id)'); $config = Configuration::getConfig('module_aggregator2.php'); return new Aggregator($id, $config->getConfigItem($id)); }
Return an instance of the aggregator with the given id. @param string $id The id of the aggregator. @return Aggregator
entailment
public function addCacheItem($id, $data, $expires, $tag = null) { assert('is_string($id)'); assert('is_string($data)'); assert('is_int($expires)'); assert('is_null($tag) || is_string($tag)'); $cacheFile = strval($this->cacheDirectory).'/'.$id; try { System::writeFile($cacheFile, $data); } catch (\Exception $e) { Logger::warning($this->logLoc.'Unable to write to cache file '.var_export($cacheFile, true)); return; } $expireInfo = (string)$expires; if ($tag !== null) { $expireInfo .= ':'.$tag; } $expireFile = $cacheFile.'.expire'; try { System::writeFile($expireFile, $expireInfo); } catch (\Exception $e) { Logger::warning($this->logLoc.'Unable to write expiration info to '.var_export($expireFile, true)); } }
Add an item to the cache. @param string $id The identifier of this data. @param string $data The data. @param int $expires The timestamp the data expires. @param string|null $tag An extra tag that can be used to verify the validity of the cached data. @return void
entailment
public function isCacheValid($id, $tag = null) { assert('is_string($id)'); assert('is_null($tag) || is_string($tag)'); $cacheFile = strval($this->cacheDirectory).'/'.$id; if (!file_exists($cacheFile)) { return false; } $expireFile = $cacheFile.'.expire'; if (!file_exists($expireFile)) { return false; } $expireData = @file_get_contents($expireFile); if ($expireData === false) { return false; } $expireData = explode(':', $expireData, 2); $expireTime = intval($expireData[0]); if ($expireTime <= time()) { return false; } if (count($expireData) === 1) { $expireTag = null; } else { $expireTag = $expireData[1]; } if ($expireTag !== $tag) { return false; } return true; }
Check validity of cached data. @param string $id The identifier of this data. @param string $tag The tag that was passed to addCacheItem. @return bool TRUE if the data is valid, FALSE if not.
entailment
public function getCacheItem($id, $tag = null) { assert('is_string($id)'); assert('is_null($tag) || is_string($tag)'); if (!$this->isCacheValid($id, $tag)) { return null; } $cacheFile = strval($this->cacheDirectory).'/'.$id; return @file_get_contents($cacheFile); }
Get the cache item. @param string $id The identifier of this data. @param string $tag The tag that was passed to addCacheItem. @return string|null The cache item, or NULL if it isn't cached or if it is expired.
entailment
public function getCacheFile($id) { assert('is_string($id)'); $cacheFile = strval($this->cacheDirectory).'/'.$id; if (!file_exists($cacheFile)) { return null; } return $cacheFile; }
Get the cache filename for the specific id. @param string $id The identifier of the cached data. @return string|null The filename, or NULL if the cache file doesn't exist.
entailment
protected function addSignature(SignedElement $element) { if ($this->signKey === null) { return; } /** @var string $this->signAlg */ $privateKey = new XMLSecurityKey($this->signAlg, ['type' => 'private']); if ($this->signKeyPass !== null) { $privateKey->passphrase = $this->signKeyPass; } $privateKey->loadKey($this->signKey, false); $element->setSignatureKey($privateKey); if ($this->signCert !== null) { $element->setCertificates([$this->signCert]); } }
Sign the generated EntitiesDescriptor. @return void
entailment
private static function extractEntityDescriptors(EntitiesDescriptor $entity) { $results = []; foreach ($entity->children as $child) { if ($child instanceof EntityDescriptor) { $results[] = $child; continue; } $results = array_merge($results, self::extractEntityDescriptors($child)); } return $results; }
Recursively browse the children of an EntitiesDescriptor element looking for EntityDescriptor elements, and return an array containing all of them. @param \SAML2\XML\md\EntitiesDescriptor $entity The source EntitiesDescriptor that holds the entities to extract. @return array An array containing all the EntityDescriptors found.
entailment
protected function getEntitiesDescriptor() { $ret = new EntitiesDescriptor(); $now = time(); // add RegistrationInfo extension if enabled if (!empty($this->regInfo)) { $ri = new RegistrationInfo(); $ri->registrationInstant = $now; foreach ($this->regInfo as $riName => $riValues) { switch ($riName) { case 'authority': $ri->registrationAuthority = $riValues; break; case 'instant': $ri->registrationInstant = Utils::xsDateTimeToTimestamp($riValues); break; case 'policies': $ri->RegistrationPolicy = $riValues; break; } } $ret->Extensions[] = $ri; } foreach ($this->sources as $source) { $m = $source->getMetadata(); if ($m === NULL) { continue; } if ($m instanceof EntityDescriptor) { $ret->children[] = $m; } elseif ($m instanceof EntitiesDescriptor) { $ret->children = array_merge($ret->children, self::extractEntityDescriptors($m)); } } $ret->children = array_unique($ret->children, SORT_REGULAR); $ret->validUntil = $now + $this->validLength; return $ret; }
Retrieve all entities as an EntitiesDescriptor. @return \SAML2\XML\md\EntitiesDescriptor The entities.
entailment
protected function exclude(EntitiesDescriptor $descriptor) { if (empty($this->excluded)) { return $descriptor; } $filtered = []; foreach ($descriptor->children as $child) { if ($child instanceof EntityDescriptor) { if (in_array($child->entityID, $this->excluded)) { continue; } $filtered[] = $child; } if ($child instanceof EntitiesDescriptor) { $filtered[] = $this->exclude($child); } } $descriptor->children = $filtered; return $descriptor; }
Recursively traverse the children of an EntitiesDescriptor, removing those entities listed in the $entities property. Returns the EntitiesDescriptor with the entities filtered out. @param \SAML2\XML\md\EntitiesDescriptor $descriptor The EntitiesDescriptor from where to exclude entities. @return \SAML2\XML\md\EntitiesDescriptor The EntitiesDescriptor with excluded entities filtered out.
entailment
protected function filter(EntitiesDescriptor $descriptor) { if ($this->roles === null || $this->protocols === null) { return $descriptor; } $enabled_roles = array_keys($this->roles, true); $enabled_protos = array_keys($this->protocols, true); $filtered = []; foreach ($descriptor->children as $child) { if ($child instanceof EntityDescriptor) { foreach ($child->RoleDescriptor as $role) { if (in_array(get_class($role), $enabled_roles)) { // we found a role descriptor that is enabled by our filters, check protocols if (array_intersect($enabled_protos, $role->protocolSupportEnumeration) !== []) { // it supports some protocol we have enabled, add it $filtered[] = $child; break; } } } } if ($child instanceof EntitiesDescriptor) { $filtered[] = $this->filter($child); } } $descriptor->children = $filtered; return $descriptor; }
Recursively traverse the children of an EntitiesDescriptor, keeping only those entities with the roles listed in the $roles property, and support for the protocols listed in the $protocols property. Returns the EntitiesDescriptor containing only those entities. @param \SAML2\XML\md\EntitiesDescriptor $descriptor The EntitiesDescriptor to filter. @return \SAML2\XML\md\EntitiesDescriptor The EntitiesDescriptor with only the entities filtered.
entailment
public function excludeEntities($entities) { assert('is_array($entities) || is_null($entities)'); if ($entities === null) { return; } $this->excluded = $entities; sort($this->excluded); $this->cacheId = sha1($this->cacheId.serialize($this->excluded)); }
Set this aggregator to exclude a set of entities from the resulting aggregate. @param array|null $entities The entity IDs of the entities to exclude. @return void
entailment
public function setFilters($set) { assert('is_array($set) || is_null($set)'); if ($set === null) { return; } // configure filters $this->protocols = [ Constants::NS_SAMLP => true, 'urn:oasis:names:tc:SAML:1.1:protocol' => true, ]; $this->roles = [ 'SAML2_XML_md_IDPSSODescriptor' => true, 'SAML2_XML_md_SPSSODescriptor' => true, 'SAML2_XML_md_AttributeAuthorityDescriptor' => true, ]; // now translate from the options we have, to specific protocols and roles // check SAML 2.0 protocol $options = ['saml2', 'saml20-idp', 'saml20-sp', 'saml20-aa']; $this->protocols[Constants::NS_SAMLP] = (array_intersect($set, $options) !== []); // check SHIB 1.3 protocol $options = ['shib13', 'shib13-idp', 'shib13-sp', 'shib13-aa']; $this->protocols['urn:oasis:names:tc:SAML:1.1:protocol'] = (array_intersect($set, $options) !== []); // check IdP $options = ['saml2', 'shib13', 'saml20-idp', 'shib13-idp']; $this->roles['SAML2_XML_md_IDPSSODescriptor'] = (array_intersect($set, $options) !== []); // check SP $options = ['saml2', 'shib13', 'saml20-sp', 'shib13-sp']; $this->roles['SAML2_XML_md_SPSSODescriptor'] = (array_intersect($set, $options) !== []); // check AA $options = ['saml2', 'shib13', 'saml20-aa', 'shib13-aa']; $this->roles['SAML2_XML_md_AttributeAuthorityDescriptor'] = (array_intersect($set, $options) !== []); $this->cacheId = sha1($this->cacheId.serialize($this->protocols).serialize($this->roles)); }
Set the internal filters according to one or more options: - 'saml2': all SAML2.0-capable entities. - 'shib13': all SHIB1.3-capable entities. - 'saml20-idp': all SAML2.0-capable identity providers. - 'saml20-sp': all SAML2.0-capable service providers. - 'saml20-aa': all SAML2.0-capable attribute authorities. - 'shib13-idp': all SHIB1.3-capable identity providers. - 'shib13-sp': all SHIB1.3-capable service providers. - 'shib13-aa': all SHIB1.3-capable attribute authorities. @param array|null $set An array of the different roles and protocols to filter by. @return void
entailment
public function updateCachedMetadata() { $ed = $this->getEntitiesDescriptor(); $ed = $this->exclude($ed); $ed = $this->filter($ed); $this->addSignature($ed); $xml = $ed->toXML(); $xml = $xml->ownerDocument->saveXML($xml); if ($this->cacheGenerated !== null) { Logger::debug($this->logLoc.'Saving generated metadata to cache.'); $this->addCacheItem($this->cacheId, $xml, time() + $this->cacheGenerated, $this->cacheTag); } return $xml; }
Retrieve the complete, signed metadata as text. This function will write the new metadata to the cache file, but will not return the cached metadata. @return string The metadata, as text.
entailment
public function getMetadata() { if ($this->cacheGenerated !== null) { $xml = $this->getCacheItem($this->cacheId, $this->cacheTag); if ($xml !== null) { Logger::debug($this->logLoc.'Loaded generated metadata from cache.'); return $xml; } } return $this->updateCachedMetadata(); }
Retrieve the complete, signed metadata as text. @return string The metadata, as text.
entailment
public function add($directive, $line) { $this->previous = $this->directive; $this->directive = $directive; $this->strings[] = rtrim($this->prefix() . $line); return true; }
Add line @param string $directive @param string $line @return bool
entailment
private function prefix() { $result = $this->lineBreak() . $this->directive . ':'; if ($this->level === 0) { return $result; } return ucwords($result) . ' '; }
Advanced beautifier @return string
entailment
private function lineBreak() { if ($this->previousRoot !== $this->directive && in_array($this->directive, array_keys(RobotsTxtParser::TOP_LEVEL_DIRECTIVES)) || $this->previous !== self::DIRECTIVE_USER_AGENT && $this->directive === self::DIRECTIVE_USER_AGENT ) { $this->previousRoot = $this->directive; if ($this->level >= 1) { return $this->eol; } } return ''; }
Returns an line separator if required @return string
entailment
public function getConfig() { if ($this->config) { return $this->config; } $config = $this->getDefaultConfig(); // read from database $result = $this->connection->fetchAll('SELECT type, class FROM fusio_provider ORDER BY class ASC'); foreach ($result as $row) { $this->mergeClass($config, $row['type'], $row['class']); } // read from file if (!empty($this->file)) { $result = include($this->file); if (is_array($result)) { foreach ($result as $type => $classes) { foreach ($classes as $class) { $this->mergeClass($config, $type, $class); } } } } return $this->config = new ProviderConfig($config); }
Returns the provider config of the system @return \Fusio\Impl\Provider\ProviderConfig
entailment
public function write($cacheFile, $content) { // 添加写入时间 $content = $_SERVER['REQUEST_TIME'] . $content; if (!$this->mc->set($cacheFile, $content, 0)) { throw new Exception('sae mc write error:' . $cacheFile); } else { $this->contents[$cacheFile] = $content; return true; } }
写入编译缓存 @param string $cacheFile 缓存的文件名 @param string $content 缓存的内容 @return void|array
entailment
public function read($cacheFile, $vars = []) { if (!empty($vars) && is_array($vars)) { extract($vars, EXTR_OVERWRITE); } eval('?>' . $this->get($cacheFile, 'content')); }
读取编译编译 @param string $cacheFile 缓存的文件名 @param array $vars 变量数组 @return void
entailment
public function check($cacheFile, $cacheTime) { $mtime = $this->get($cacheFile, 'mtime'); if (0 != $cacheTime && $_SERVER['REQUEST_TIME'] > $mtime + $cacheTime) { // 缓存是否在有效期 return false; } return true; }
检查编译缓存是否有效 @param string $cacheFile 缓存的文件名 @param int $cacheTime 缓存时间 @return boolean
entailment
private function get($filename, $name) { if (!isset($this->contents[$filename])) { $this->contents[$filename] = $this->mc->get($filename); } $content = $this->contents[$filename]; if (false === $content) { return false; } $info = array( 'mtime' => substr($content, 0, 10), 'content' => substr($content, 10), ); return $info[$name]; }
读取文件信息 @access private @param string $filename 文件名 @param string $name 信息名 mtime或者content @return boolean
entailment