sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function add_panel( $id, $args = [] ) { $panel = $id instanceof Panel ? $id : new Panel( $this, $id, $args ); $this->panels[ $panel->id ] = $panel; return $panel; }
{@inheritdoc}
entailment
public function get_panel( $id ) { return isset( $this->panels[ $id ] ) ? $this->panels[ $id ] : null; }
{@inheritdoc}
entailment
public function save($selection = null) { // prepare the selection if (func_num_args()) { if (is_array($selection)) { $filter = array(); foreach ($this->container as $file) { $match = true; foreach($selection as $item => $value) { if ($value != $file->{$item}) { $match = false; break; } } $match and $filter[] = $file; } $selection = $filter; } else { $selection = array($this[$selection]); } } else { $selection = $this->container; } // loop through all selected files foreach ($selection as $file) { $file->save(); } }
Runs save on all loaded file objects @param integer|string|array $selection
entailment
public function isValid() { // loop through all files foreach ($this->container as $file) { // return false at the first non-valid file if ( ! $file->isValid()) { return false; } } // only return true if there are uploaded files, and they are all valid return empty($this->container) ? false : true; }
Returns a consolidated status of all uploaded files @return boolean
entailment
public function getAllFiles($index = null) { // return the selection if ($selection = (func_num_args() and ! is_null($index)) ? $this[$index] : $this->container) { // make sure selection is an array is_array($selection) or $selection = array($selection); } else { $selection = array(); } return $selection; }
Returns the list of uploaded files @param integer|string $index @return File[]
entailment
public function getValidFiles($index = null) { // prepare the selection if (is_numeric($index)) { $selection = $this->container; } else { $selection = (func_num_args() and ! is_null($index)) ? $this[$index] : $this->container; } // storage for the results $results = array(); if ($selection) { // make sure selection is an array is_array($selection) or $selection = array($selection); // loop through all files foreach ($selection as $file) { // store only files that are valid $file->isValid() and $results[] = $file; } } // return the results if (is_numeric($index)) { // a specific valid file was requested return isset($results[$index]) ? array($results[$index]) : array(); } else { return $results; } }
Returns the list of uploaded files that valid @param integer|string $index @return File[]
entailment
public function register($event, $callback) { // check if this is a valid event type if ( ! isset($this->callbacks[$event])) { throw new \InvalidArgumentException($event.' is not a valid event'); } // check if the callback is acually callable if ( ! is_callable($callback)) { throw new \InvalidArgumentException('Callback passed is not callable'); } // store it $this->callbacks[$event][] = $callback; }
Registers a callback for a given event @param string $event @param mixed $callback @throws \InvalidArgumentException if not valid event or not callable second parameter
entailment
public function setConfig($item, $value = null) { // unify the parameters is_array($item) or $item = array($item => $value); // update the configuration foreach ($item as $name => $value) { // is this a valid config item? then update the defaults array_key_exists($name, $this->defaults) and $this->defaults[$name] = $value; } // and push it to all file objects in the containers foreach ($this->container as $file) { $file->setConfig($item); } }
Sets the configuration for this file @param string|array $item @param mixed $value
entailment
public function processFiles(array $selection = null) { // normalize the multidimensional fields in the $_FILES array foreach($_FILES as $name => $file) { // was it defined as an array? if (is_array($file['name'])) { $data = $this->unifyFile($name, $file); foreach ($data as $entry) { if ($selection === null or in_array($entry['element'], $selection)) { $this->addFile($entry); } } } else { // normal form element, just create a File object for this uploaded file if ($selection === null or in_array($name, $selection)) { $this->addFile(array_merge(array('element' => $name, 'filename' => null), $file)); } } } }
Processes the data in the $_FILES array, unify it, and create File objects for them @param mixed $selection
entailment
protected function unifyFile($name, $file) { // storage for results $data = array(); // loop over the file array foreach ($file['name'] as $key => $value) { // we're not an the end of the element name nesting yet if (is_array($value)) { // recurse with the array data we have at this point $data = array_merge( $data, $this->unifyFile($name.'.'.$key, array( 'filename' => null, 'name' => $file['name'][$key], 'type' => $file['type'][$key], 'tmp_name' => $file['tmp_name'][$key], 'error' => $file['error'][$key], 'size' => $file['size'][$key], ) ) ); } else { $data[] = array( 'filename' => null, 'element' => $name.'.'.$key, 'name' => $file['name'][$key], 'type' => $file['type'][$key], 'tmp_name' => $file['tmp_name'][$key], 'error' => $file['error'][$key], 'size' => $file['size'][$key], ); } } return $data; }
Converts the silly different $_FILE structures to a flattened array @param string $name @param array $file @return array
entailment
protected function addFile(array $entry) { // add the new file object to the container $this->container[] = new File($entry, $this->callbacks); // and load it with a default config end($this->container)->setConfig($this->defaults); }
Adds a new uploaded file structure to the container @param array $entry
entailment
public function display( $field, $value, $builder ) { $value = $this->parse_value( $value ); $html_builder = $builder->get_html_builder(); $system_fonts = wp_list_pluck( Webfonts::get_system_fonts(), 'label', 'name' ); $defaults = [ 'font-family' => true, 'font-size' => true, 'font-weight' => true, 'font-style' => true, 'font-backup' => false, 'subsets' => true, 'custom_fonts' => true, 'text-align' => true, 'text-transform' => false, 'font-variant' => false, 'text-decoration' => false, 'preview' => true, 'line-height' => true, 'word-spacing' => false, 'letter-spacing' => false, 'google_fonts' => true, ]; ?> <div class="wplibs-control-typography"> <div class="wplibs-control-typography__row"> <div class="wplibs-control-typography__family"> <label for="<?php echo esc_attr( $builder->_input_id( '_family' ) ); ?>"><?php echo esc_html__( 'Font Family', 'wplibs-form' ); ?></label> <?php print $html_builder->select( $builder->_name( '[family]' ), [], $value['family'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_family' ), 'data-element' => 'family', ] ); ?> </div> <div class="wplibs-control-typography__backup"> <label for="<?php echo esc_attr( $builder->_input_id( '_backup' ) ); ?>"><?php echo esc_html__( 'Backup Font Family', 'wplibs-form' ); ?></label> <?php print $html_builder->select( $builder->_name( '[backup]' ), $system_fonts, $value['backup'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_backup' ), 'data-element' => 'backup', ] ); ?> </div> <div class="wplibs-control-typography__weight"> <label for="<?php echo esc_attr( $builder->_input_id( '_font_weight' ) ); ?>"><?php echo esc_html__( 'Font Weight', 'wplibs-form' ); ?></label> <?php print $html_builder->select( $builder->_name( '[font-weight]' ), $this->get_font_weights(), $value['font-weight'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_font_weight' ), 'data-element' => 'weight', ] ); ?> </div> </div> <div class="wplibs-control-typography__row"> <div class="wplibs-control-typography__size"> <label for="<?php echo esc_attr( $builder->_input_id( '_font_size' ) ); ?>"><?php echo esc_html__( 'Font Size', 'wplibs-form' ); ?></label> <?php print $html_builder->number( $builder->_name( '[font-size]' ), $value['font-size'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_font_size' ), 'step' => '1', 'data-element' => 'size', ] ); ?> </div> <div class="wplibs-control-typography__line-height"> <label for="<?php echo esc_attr( $builder->_input_id( '_line_height' ) ); ?>"><?php echo esc_html__( 'Line Height', 'wplibs-form' ); ?></label> <?php print $html_builder->number( $builder->_name( '[line-height]' ), $value['line-height'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_line_height' ), 'step' => '0.1', 'data-element' => 'line_height', ] ); ?> </div> <div class="wplibs-control-typography__word-spacing"> <label for="<?php echo esc_attr( $builder->_input_id( '_word_spacing' ) ); ?>"><?php echo esc_html__( 'Word Spacing', 'wplibs-form' ); ?></label> <?php print $html_builder->number( $builder->_name( '[word-spacing]' ), $value['word-spacing'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_word_spacing' ), 'step' => '1', 'data-element' => 'word_spacing', ] ); ?> </div> <div class="wplibs-control-typography__letter-spacing"> <label for="<?php echo esc_attr( $builder->_input_id( '_letter_spacing' ) ); ?>"><?php echo esc_html__( 'Letter Spacing', 'wplibs-form' ); ?></label> <?php print $html_builder->number( $builder->_name( '[letter-spacing]' ), $value['letter-spacing'], [ // @WPCS: XSS OK. 'id' => $builder->_input_id( '_letter_spacing' ), 'step' => '1', 'data-element' => 'letter_spacing', ] ); ?> </div> </div> </div> <?php }
{@inheritdoc}
entailment
public function getPermissions(RoleInterface $role) { $permissions = new ArrayCollection(); $iterator = new \RecursiveIteratorIterator( new RecursivePermissionIterator($role->getPermissions()), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $permission) { if (!$permissions->contains($permission)) { $permissions->add($permission); } } return $permissions; }
{@inheritdoc}
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder ->root('piedweb_cms') ->children() ->scalarNode('media_dir_absolute') // NOT USED ?? ->defaultValue('%kernel.project_dir%/media') ->cannotBeEmpty() ->end() ->scalarNode('locale')->defaultValue('%locale%')->cannotBeEmpty()->end() ->scalarNode('locales')->defaultValue('fr|en')->end() ->scalarNode('dir') // not explicit = public dir/web dir ->defaultValue('%kernel.project_dir%/public') ->cannotBeEmpty() ->end() ->scalarNode('name')->defaultValue('PiedWeb.com')->end() ->scalarNode('color')->defaultValue('#1fa67a')->end() ->booleanNode('default_locale_without_prefix')->defaultTrue()->end() ->scalarNode('default_page_template') ->defaultValue('@PiedWebCMS/page/page.html.twig') ->cannotBeEmpty() ->end() ->scalarNode('entity_page')->defaultValue('App\Entity\Page')->cannotBeEmpty()->end() ->scalarNode('entity_media')->defaultValue('App\Entity\Media')->cannotBeEmpty()->end() ->scalarNode('entity_user')->defaultValue('App\Entity\User')->cannotBeEmpty()->end() ->scalarNode('entity_pagehasmedia') ->defaultValue('App\Entity\PageHasMedia') ->cannotBeEmpty() ->end() // For Fos User and maybe other bundle ->scalarNode('email_sender')->defaultValue('[email protected]')->cannotBeEmpty()->end() ->scalarNode('email_sender_name')->defaultValue('PiedWebCMS')->cannotBeEmpty()->end() ->end() ; return $treeBuilder; }
php bin/console config:dump-reference PiedWebCMSBundle.
entailment
public function render(RenderHandler $handler) { foreach ($this->comments as $comment) { $handler->add(self::DIRECTIVE_COMMENT, $comment); } return true; }
Render @param RenderHandler $handler @return bool
entailment
public function saveMessage($mail) { try { return $this->_storage->saveMessage($mail); } catch (\Exception $e) { throw new MailException( new Phrase($e->getMessage()), $e) ; } }
Send a mail using this transport @param \Shockwavemk\Mail\Base\Model\Mail $mail @return $id @throws MailException
entailment
public function saveAttachment($attachment) { try { return $this->_storage->saveAttachment($attachment); } catch (\Exception $e) { throw new MailException( new Phrase($e->getMessage()), $e) ; } }
TODO @param AttachmentInterface $attachment @return string $id @throws MailException
entailment
public function loadMail($id) { try { return $this->_storage->loadMail($id); } catch (\Exception $e) { throw new MailException( new Phrase($e->getMessage()), $e) ; } }
Use the concrete storage implementation to load the mail to storage @return \Shockwavemk\Mail\Base\Model\Mail @throws MailException
entailment
public function loadAttachment($mail, $path) { try { return $this->_storage->loadAttachment($mail, $path); } catch (\Exception $e) { throw new MailException( new Phrase($e->getMessage()), $e) ; } }
TODO @param \Shockwavemk\Mail\Base\Model\Mail $mail @param string $path @return AttachmentInterface @throws MailException
entailment
public function getMailFolderPathById($mailId) { try { return $this->_storage->getMailFolderPathById($mailId); } catch (\Exception $e) { throw new MailException( new Phrase($e->getMessage()), $e) ; } }
TODO @return string @throws MailException
entailment
public function jsonSerialize() { $data = $this->getData(); $data['binary'] = ''; $data['mail'] = $this->getMail()->getId(); return $data; }
Return all data, except binary @return array
entailment
public function toMimePart() { /** @var Zend_Mime_Part $attachmentMimePart */ $attachmentMimePart = new Zend_Mime_Part($this->getBinary()); $attachmentMimePart->type = $this->getMimeType(); $attachmentMimePart->disposition = $this->getDisposition(); $attachmentMimePart->encoding = $this->getEncoding(); $attachmentMimePart->filename = $this->getFileName(); return $attachmentMimePart; }
Returns a mime part converted attachment @return Zend_Mime_Part
entailment
public function getBinary() { /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($this->getData('binary'))) { $attachmentBinary = file_get_contents( $this->getFilePath() ); $this->setData( 'binary', $attachmentBinary ); } return $this->getData('binary'); }
Returns binary data of a single attachment file @return string binary data of attachment file @throws \Magento\Framework\Exception\MailException
entailment
public function getDisposition() { /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($this->getData('disposition'))) { $this->setData( 'disposition', Zend_Mime::DISPOSITION_ATTACHMENT ); } return $this->getData('disposition'); }
Returns current setting of how to integrate attachment into message @return string
entailment
public function active() { // Default to showing the section. $show = true; // Use the callback to determine showing the section, if it exists. if ( is_callable( $this->active_callback ) ) { $show = call_user_func( $this->active_callback, $this ); } return $show; }
Check whether section is active to current screen. @return bool
entailment
public function check_capabilities() { if ( $this->capability && ! call_user_func_array( 'current_user_can', (array) $this->capability ) ) { return false; } if ( $this->theme_supports && ! call_user_func_array( 'current_theme_supports', (array) $this->theme_supports ) ) { return false; } return true; }
Checks required user capabilities and whether the theme has the feature support required by the section. @return bool
entailment
public function icon() { if ( ! $this->icon ) { return ''; } if ( 0 === strpos( $this->icon, 'dashicons-' ) ) { $icon_html = '<span class="wplibs-menu-icon dashicons ' . esc_attr( $this->icon ) . '"></span>'; } elseif ( 0 === strpos( $this->icon, 'suru-icon-' ) ) { $icon_html = '<span class="wplibs-menu-icon suru-icon ' . esc_attr( $this->icon ) . '"></span>'; } elseif ( preg_match( '/^(http.*\.)(jpe?g|png|[tg]iff?|svg)$/', $this->icon ) ) { $icon_html = '<span class="wplibs-menu-icon" style="background-image:url(\'' . esc_attr( $this->icon ) . '\'"></span>'; } else { $icon_html = '<span class="wplibs-menu-icon ' . esc_attr( $this->icon ) . '"></span>'; } return $icon_html; }
Show the section/panel icon as HTML. @return string
entailment
public function addChild(PermissionInterface $permission) { if (!$this->hasChild($permission)) { $permission->setParent($this); $this->children->add($permission); } }
{@inheritdoc}
entailment
public function removeChild(PermissionInterface $permission) { if ($this->hasChild($permission)) { $permission->setParent(null); $this->children->removeElement($permission); } }
{@inheritdoc}
entailment
public function buildZip($file, $basePath) { yield 'Generating zip file ' . $file; $zip = new \ZipArchive(); $res = $zip->open($file, \ZipArchive::CREATE); if ($res === true) { $this->buildZipArchive($basePath, $zip, $basePath, 0); $zip->close(); yield 'Generation completed file size ' . (round(filesize($file) / 1024, 2)) . 'kb'; } else { throw new \RuntimeException('Could not create zip file ' . $file); } }
Creates a zip archive for the provided file using all files located at the base path @param string $file @param string $basePath @return \Generator
entailment
public static function check( array $fields, array $data ) { $dependency = new static( $data ); foreach ( $fields as $field ) { if ( ! $field->get_option( 'deps' ) ) { continue; } $satisfied = $dependency->apply( $deps = $field->get_option( 'deps' ) ); $field->set_option( 'row_attributes', $field->get_option( 'row_attributes' ) + [ 'data-deps' => esc_attr( json_encode( $deps, JSON_HEX_APOS ) ), 'data-satisfied' => $satisfied ? 'true' : 'false', ] ); $field->set_option( 'active', $satisfied ); } }
Check the fields dependencies. @param \WPLibs\Form\Contracts\Field[] $fields @param array $data @return void
entailment
public function apply( $rules ) { $satisfied = true; if ( empty( $rules ) || ! is_array( $rules ) ) { return $satisfied; } // If no any valid rules, consider as satisfied. if ( ! is_null( $rule = $this->get_rule( $rules ) ) ) { return $rule->apply( $this->data ); } return $satisfied; }
Check rules is satisfied the conditions. @param array $rules @return bool
entailment
public function get_rule( array $rules ) { $logical = static::LOGICAL_AND; if ( static::is_group_rules( $rules ) ) { list( $logical, $rules ) = $this->parse_group_logical( $rules ); } return $this->create_rule( $rules, $logical ); }
Gets the rule. @param array $rules @return \WPLibs\Rules\Rule|null
entailment
public function create_rule( array $rules, $logical = 'and' ) { if ( empty( $rules ) ) { return null; } if ( static::is_proposition( $rules ) ) { $rules = [ $rules ]; } if ( ! $props = $this->build_propositions( $rules ) ) { return null; } // Correct the "or" logical in case we have only one prop. if ( static::LOGICAL_OR === $logical && count( $props ) === 1 ) { $logical = static::LOGICAL_AND; } $logical = static::$logicals[ $logical ]; return new Rule( new $logical( $props ) ); }
Create new rule based on an array of rules. @param array $rules @param string $logical @return \WPLibs\Rules\Rule|null
entailment
protected function build_propositions( array $rules ) { $props = []; foreach ( $rules as $rule ) { if ( ! is_array( $rule ) || ! static::is_proposition( $rule ) ) { continue; } try { $props[] = $this->create_proposition( ... $rule ); } catch ( \Exception $e ) { continue; } } return array_filter( $props ); }
Build propositions based given array rules. @param array $rules @return array
entailment
protected function create_proposition( $parent_name, $operator = null, $check_value = null ) { list( $operator, $check_value ) = $this->normalize_proposition( $operator, $check_value ); // Allow check value can be a reference value of a variable in the context. // This can be done with: ['some-check', '!=', '@another-check']. if ( is_string( $check_value ) && 0 === strpos( $check_value, '@' ) ) { $check_value = $this->new_variable( substr( $check_value, 1 ) ); } $vars = $this->new_variable( $parent_name ); // The "is_" operator can not have check value. if ( 0 === strpos( $operator, 'is_' ) ) { return $vars->{$operator}(); } return $vars->{$operator}( $check_value ); }
Create a rule proposition. @param string $parent_name @param string $operator @param mixed $check_value @return mixed
entailment
protected function normalize_proposition( $operator = null, $check_value = null ) { // Here we will make some assumptions about the operator. If only $operator are // passed to the method, we will assume that the operator is an equals sign // and keep going. Otherwise, we'll require the operator to be passed in. if ( is_null( $check_value ) && 0 !== strpos( $operator, 'is_' ) ) { list( $check_value, $operator ) = [ $operator, '=' ]; } // Some operator like "=", "<=", etc. need to normalize to valid name. $operator = $this->normalize_operator( $operator ); if ( ! in_array( $operator, static::$operators ) ) { throw new \InvalidArgumentException( "The [{$operator}] operator is not supported." ); } // Wrap the value as array in case "in" or "not_in". if ( is_string( $check_value ) && in_array( $operator, [ 'in', 'not_in' ] ) ) { $check_value = false !== strpos( $check_value, ',' ) ? str_getcsv( $check_value ) : [ $check_value ]; } return [ $operator, $check_value ]; }
Normalize the proposition. @param string $operator @param mixed $check_value @return array @throws \InvalidArgumentException
entailment
public function add($line) { $array = preg_split('/\s+/', $line, 2); $parts = array_map('trim', explode('/', $array[0])); if (count($parts) != 2) { return false; } $unit = strtolower(substr(preg_replace('/[^A-Za-z]/', '', filter_var($parts[1], FILTER_SANITIZE_STRING)), 0, 1)); $multiplier = isset($this->units[$unit]) ? $this->units[$unit] : 1; $rate = (int)abs(filter_var($parts[0], FILTER_SANITIZE_NUMBER_INT)); $time = $multiplier * (int)abs(filter_var($parts[1], FILTER_SANITIZE_NUMBER_INT)); $result = [ 'rate' => $time / $rate, 'ratio' => $this->getRatio($rate, $time), 'from' => null, 'to' => null, ]; if (!empty($array[1]) && ($times = $this->draftParseTime($array[1])) !== false ) { $result = array_merge($result, $times); } $this->requestRates[] = $result; return true; }
Add @param string $line @return bool
entailment
private function getRatio($rate, $time) { $gcd = $this->getGCD($rate, $time); $requests = $rate / $gcd; $time = $time / $gcd; $suffix = 's'; foreach ($this->units as $unit => $sec) { if ($time % $sec === 0) { $suffix = $unit; $time /= $sec; break; } } return $requests . '/' . $time . $suffix; }
Get ratio string @param int $rate @param int $time @return string
entailment
private function getGCD($a, $b) { if (extension_loaded('gmp')) { return gmp_intval(gmp_gcd((string)$a, (string)$b)); } $large = $a > $b ? $a : $b; $small = $a > $b ? $b : $a; $remainder = $large % $small; return 0 === $remainder ? $small : $this->getGCD($small, $remainder); }
Returns the greatest common divisor of two integers using the Euclidean algorithm. @param int $a @param int $b @return int
entailment
public function client($userAgent = self::USER_AGENT, $fallbackValue = 0) { $this->sort(); return new RequestRateClient($this->base, $userAgent, $this->requestRates, $fallbackValue); }
Client @param string $userAgent @param float|int $fallbackValue @return RequestRateClient
entailment
private function sort() { if (!$this->sorted) { $this->sorted = true; return usort($this->requestRates, function (array $requestRateA, array $requestRateB) { // PHP 7: Switch to the <=> "Spaceship" operator return $requestRateB['rate'] > $requestRateA['rate']; }); } return $this->sorted; }
Sort @return bool
entailment
public function render(RenderHandler $handler) { $this->sort(); foreach ($this->requestRates as $array) { $time = ''; if (isset($array['from']) && isset($array['to']) ) { $time .= ' ' . $array['from'] . '-' . $array['to']; } $handler->add(self::DIRECTIVE_REQUEST_RATE, $array['ratio'] . $time); } return true; }
Render @param RenderHandler $handler @return bool
entailment
public function save(\Magento\Framework\Model\AbstractModel $object) { $object->setHasDataChanges(true); return parent::save($object); }
{@inheritdoc}
entailment
public function setStartDay($startDay) { $startDay = (int) $startDay; if ($startDay < 1 || $startDay > 7) { throw new OutOfRangeException( "'$startDay' is an invalid value for \$startDay in '" . __METHOD__ ); } $this->startDay = $startDay; return $this; }
Set which day to display as the starting day of the week. @param int $startDay @return self
entailment
public function showMonth($year, $month) { if (null !== $this->partial) { $partial = $this->view->plugin('partial'); $params = array( 'calendar' => $this->calendar, 'startDay' => $this->startDay, 'year' => $year, 'month' => $month, ); return $partial($this->partial, $params); } $renderer = $this->getRenderer(); $renderer->setCalendar($this->calendar); $renderer->setStartDay($this->startDay); return $renderer->renderMonth($year, $month); }
Returns the HTML to display a month. @param int $year @param int $month @return void
entailment
public function run() { $hostInfo = Yii::$app->getRequest()->getHostInfo(); $controller = $this->controller; if (($serviceUrl = $this->serviceUrl) === null) { $serviceUrl = $hostInfo . Url::toRoute([$this->getUniqueId(), $this->serviceVar => 1]); } if (($wsdlUrl = $this->wsdlUrl) === null) { $wsdlUrl = $hostInfo . Url::toRoute([$this->getUniqueId()]); } if (($provider = $this->provider) === null) { $provider = $controller; } $this->_service = $this->createWebService($provider, $wsdlUrl, $serviceUrl); if (is_array($this->classMap)) { $this->_service->classMap = $this->classMap; } foreach ($this->serviceOptions as $name => $value) { $this->_service->$name = $value; } if (isset($_GET[$this->serviceVar])) { $this->_service->run(); } else { return $this->_service->renderWsdl(); } }
Runs the action. If the GET parameter {@link serviceVar} exists, the action handle the remote method invocation. If not, the action will serve WSDL content; @throws \ReflectionException @throws \yii\base\InvalidConfigException
entailment
public function isLeap() { if (0 !== $this->year % 4) { return false; } if (0 !== $this->year % 100) { return true; } if (0 !== $this->year % 400) { return false; } return true; }
Checks if this year is a leap year. @return bool
entailment
public function getDocumentation($version = null) { return $this->routesMethodService->getDocumentation( $this->context->getRouteId(), $version, $this->context->getPath() ); }
Select all methods from the routes method table and build a resource based on the data. If the route is in production mode read the schema from the cache else resolve it @param integer $version @return \PSX\Api\Resource|null
entailment
private function getHostname() { $host = parse_url($this->config->get('psx_url'), PHP_URL_HOST); if (empty($host)) { $host = $_SERVER['SERVER_NAME']; } return $host; }
Tries to determine the current hostname @return string
entailment
private function handlerAdd($group) { if (!in_array($group, array_keys($this->handler))) { $this->handler[$group] = new SubDirectiveHandler($this->base, $group); return true; } return false; }
Add sub-directive handler @param string $group @return bool
entailment
public function add($line) { if ($line == '' || ($pair = $this->generateRulePair($line, [-1 => self::DIRECTIVE_USER_AGENT] + array_keys(self::SUB_DIRECTIVES))) === false) { return $this->append = false; } if ($pair[0] === self::DIRECTIVE_USER_AGENT) { return $this->set($pair[1]); } $this->append = false; $result = []; foreach ($this->current as $group) { $result[] = $this->handler[$group]->{self::SUB_DIRECTIVES[$pair[0]]}->add($pair[1]); $this->handler[$group]->count++; }
Add line @param string $line @return bool
entailment
public function setConfig($item, $value = null) { // unify the parameters is_array($item) or $item = array($item => $value); // update the configuration foreach ($item as $name => $value) { array_key_exists($name, $this->config) and $this->config[$name] = $value; } }
Sets the configuration for this file @param string|array $item @param mixed $value
entailment
public function validate() { // reset the error container and status $this->errors = array(); $this->isValid = true; // validation starts, call the pre-validation callback $this->runCallbacks('before_validation'); // was the upload of the file a success? if ($this->container['error'] == 0) { // add some filename details (pathinfo can't be trusted with utf-8 filenames!) $this->container['extension'] = ltrim(strrchr(ltrim($this->container['name'], '.'), '.'),'.'); if (empty($this->container['extension'])) { $this->container['basename'] = $this->container['name']; } else { $this->container['basename'] = substr($this->container['name'], 0, strlen($this->container['name'])-(strlen($this->container['extension'])+1)); } // does this upload exceed the maximum size? if ( ! empty($this->config['max_size']) and is_numeric($this->config['max_size']) and $this->container['size'] > $this->config['max_size']) { $this->addError(static::UPLOAD_ERR_MAX_SIZE); } // add mimetype information try { $handle = finfo_open(FILEINFO_MIME_TYPE); $this->container['mimetype'] = finfo_file($handle, $this->container['tmp_name']); finfo_close($handle); } // this will only work if PHP errors are converted into ErrorException (like when you use FuelPHP) catch (\ErrorException $e) { $this->container['mimetype'] = false; $this->addError(UPLOAD_ERR_NO_FILE); } // make sure it contains something valid if (empty($this->container['mimetype']) or strpos($this->container['mimetype'], '/') === false) { $this->container['mimetype'] = 'application/octet-stream'; } // split the mimetype info so we can run some tests preg_match('|^(.*)/(.*)|', $this->container['mimetype'], $mimeinfo); // check the file extension black- and whitelists if (in_array(strtolower($this->container['extension']), (array) $this->config['ext_blacklist'])) { $this->addError(static::UPLOAD_ERR_EXT_BLACKLISTED); } elseif ( ! empty($this->config['ext_whitelist']) and ! in_array(strtolower($this->container['extension']), (array) $this->config['ext_whitelist'])) { $this->addError(static::UPLOAD_ERR_EXT_NOT_WHITELISTED); } // check the file type black- and whitelists if (in_array($mimeinfo[1], (array) $this->config['type_blacklist'])) { $this->addError(static::UPLOAD_ERR_TYPE_BLACKLISTED); } if ( ! empty($this->config['type_whitelist']) and ! in_array($mimeinfo[1], (array) $this->config['type_whitelist'])) { $this->addError(static::UPLOAD_ERR_TYPE_NOT_WHITELISTED); } // check the file mimetype black- and whitelists if (in_array($this->container['mimetype'], (array) $this->config['mime_blacklist'])) { $this->addError(static::UPLOAD_ERR_MIME_BLACKLISTED); } elseif ( ! empty($this->config['mime_whitelist']) and ! in_array($this->container['mimetype'], (array) $this->config['mime_whitelist'])) { $this->addError(static::UPLOAD_ERR_MIME_NOT_WHITELISTED); } // validation finished, call the post-validation callback $this->runCallbacks('after_validation'); } else { // upload was already a failure, store the corresponding error $this->addError($this->container['error']); } // set the flag to indicate we ran the validation $this->isValidated = true; // return the validation state return $this->isValid; }
Runs validation on the uploaded file, based on the config being loaded @return boolean
entailment
public function save() { $tempfileCreated = false; // we can only save files marked as valid if ($this->isValid) { // make sure we have a valid path if (empty($this->container['path'])) { $this->container['path'] = rtrim($this->config['path'], DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; } // if the path does not exist if ( ! is_dir($this->container['path'])) { // do we need to create it? if ((bool) $this->config['create_path']) { @mkdir($this->container['path'], $this->config['path_chmod'], true); if ( ! is_dir($this->container['path'])) { $this->addError(static::UPLOAD_ERR_MKDIR_FAILED); } } else { $this->addError(static::UPLOAD_ERR_NO_PATH); } } // start processing the uploaded file if ($this->isValid) { $this->container['path'] = realpath($this->container['path']).DIRECTORY_SEPARATOR; // was a new name for the file given? if ( ! is_string($this->container['filename']) or $this->container['filename'] === '') { // do we need to generate a random filename? if ( (bool) $this->config['randomize']) { $this->container['filename'] = md5(serialize($this->container)); } // do we need to normalize the filename? else { $this->container['filename'] = $this->container['basename']; (bool) $this->config['normalize'] and $this->normalize(); } } // was a hardcoded new name specified in the config? if (array_key_exists('new_name', $this->config) and $this->config['new_name'] !== false) { $new_name = pathinfo($this->config['new_name']); empty($new_name['filename']) or $this->container['filename'] = $new_name['filename']; empty($new_name['extension']) or $this->container['extension'] = $new_name['extension']; } // array with all filename components $filename = array( $this->config['prefix'], $this->container['filename'], $this->config['suffix'], '', '.', empty($this->config['extension']) ? $this->container['extension'] : $this->config['extension'] ); // remove the dot if no extension is present empty($filename[5]) and $filename[4] = ''; // need to modify case? switch($this->config['change_case']) { case 'upper': $filename = array_map(function($var) { return strtoupper($var); }, $filename); break; case 'lower': $filename = array_map(function($var) { return strtolower($var); }, $filename); break; default: break; } // if we're saving the file locally if ( ! $this->config['moveCallback']) { // check if the file already exists if (file_exists($this->container['path'].implode('', $filename))) { // generate a unique filename if needed if ( (bool) $this->config['auto_rename']) { $counter = 0; do { $filename[3] = '_'.++$counter; } while (file_exists($this->container['path'].implode('', $filename))); // claim this generated filename before someone else does touch($this->container['path'].implode('', $filename)); $tempfileCreated = true; } else { // if we can't overwrite, we've got to bail out now if ( ! (bool) $this->config['overwrite']) { $this->addError(static::UPLOAD_ERR_DUPLICATE_FILE); } } } } // no need to store it as an array anymore $this->container['filename'] = implode('', $filename); // does the filename exceed the maximum length? if ( ! empty($this->config['max_length']) and strlen($this->container['filename']) > $this->config['max_length']) { $this->addError(static::UPLOAD_ERR_MAX_FILENAME_LENGTH); } // if the file is still valid, run the before save callbacks if ($this->isValid) { // validation starts, call the pre-save callbacks $this->runCallbacks('before_save'); // recheck the path, it might have been altered by a callback if ($this->isValid and ! is_dir($this->container['path']) and (bool) $this->config['create_path']) { @mkdir($this->container['path'], $this->config['path_chmod'], true); if ( ! is_dir($this->container['path'])) { $this->addError(static::UPLOAD_ERR_MKDIR_FAILED); } } // if the file is still valid, move it if ($this->isValid) { // check if file should be moved to an ftp server if ($this->config['moveCallback']) { $moved = call_user_func($this->config['moveCallback'], $this->container['tmp_name'], $this->container['path'].$this->container['filename']); if ( ! $moved) { $this->addError(static::UPLOAD_ERR_EXTERNAL_MOVE_FAILED); } } else { if( ! @move_uploaded_file($this->container['tmp_name'], $this->container['path'].$this->container['filename'])) { $this->addError(static::UPLOAD_ERR_MOVE_FAILED); } else { @chmod($this->container['path'].$this->container['filename'], $this->config['file_chmod']); } } } } } // call the post-save callbacks if the file was succefully saved if ($this->isValid) { $this->runCallbacks('after_save'); } // if there was an error and we've created a temp file, make sure to remove it elseif ($tempfileCreated) { unlink($this->container['path'].$this->container['filename']); } } // return the status of this operation return $this->isValid; }
Saves the uploaded file @return boolean @throws \DomainException if destination path specified does not exist
entailment
protected function runCallbacks($type) { // make sure we have callbacks of this type if (array_key_exists($type, $this->callbacks)) { // run the defined callbacks foreach ($this->callbacks[$type] as $callback) { // check if the callback is valid if (is_callable($callback)) { // call the defined callback $result = call_user_func_array($callback, array(&$this)); // and process the results. we need FileError instances only foreach ((array) $result as $entry) { if (is_object($entry) and $entry instanceOf FileError) { $this->errors[] = $entry; } } // update the status of this validation $this->isValid = empty($this->errors); } } } }
Runs callbacks of he defined type @param callable $type
entailment
protected function normalize() { // Decode all entities to their simpler forms $this->container['filename'] = html_entity_decode($this->container['filename'], ENT_QUOTES, 'UTF-8'); // Remove all quotes $this->container['filename'] = preg_replace("#[\"\']#", '', $this->container['filename']); // Strip unwanted characters $this->container['filename'] = preg_replace("#[^a-z0-9]#i", $this->config['normalize_separator'], $this->container['filename']); $this->container['filename'] = preg_replace("#[/_|+ -]+#u", $this->config['normalize_separator'], $this->container['filename']); $this->container['filename'] = trim($this->container['filename'], $this->config['normalize_separator']); }
Converts a filename into a normalized name. only outputs 7 bit ASCII characters.
entailment
protected function addError($error) { $this->errors[] = new FileError($error, $this->config['langCallback']); $this->isValid = false; }
Adds a new error object to the list @param integer $error
entailment
public static function initialize() { foreach ( static::$core_types as $name => $class ) { static::register( $name, new $class ); } foreach ( static::$bindings as $name => $binding ) { if ( ! static::resolved( $name ) ) { static::fire( $name, $binding['callback'], $binding['sanitizer'] ); static::$resolved[ $name ] = true; } } // Print the field type JS templates. if ( count( static::$instances ) > 0 ) { add_action( 'admin_footer', [ __CLASS__, 'print_js_templates' ], 20 ); } }
Initialize the custom fields. @return void
entailment
public static function register( $name, $callback = null, $sanitizer = null ) { unset( static::$resolved[ $name ] ); if ( $callback instanceof Field_Type ) { $instance = $callback; list( $callback, $sanitizer ) = [ [ $instance, 'display' ], [ $instance, 'sanitization' ], ]; static::$instances[ $name ] = $instance; } static::$bindings[ $name ] = compact( 'callback', 'sanitizer' ); }
Register a custom field type. @param string $name @param callable|Field_Type $callback @param callable $sanitizer @return void
entailment
public static function fire( $name, callable $callback, $sanitizer = null ) { add_action( "cmb2_render_{$name}", static::get_render_callback( $callback ), 10, 5 ); if ( ! is_null( $sanitizer ) && is_callable( $sanitizer ) ) { add_filter( "cmb2_sanitize_{$name}", static::get_sanitize_callback( $sanitizer ), 10, 5 ); } }
Fire the hooks to add field type in to the CMB2. @param string $name @param callable $callback @param callable $sanitizer
entailment
public static function print_js_templates() { foreach ( static::$instances as $type => $control ) { if ( ! method_exists( $control, 'template' ) ) { continue; } ?> <script type="text/html" id="tmpl-wplibs-field-<?php echo esc_attr( $type ); ?>-content"> <?php $control->template(); ?> </script> <?php // @codingStandardsIgnoreLine } }
Print the field JS templates. @return void
entailment
protected static function get_render_callback( $callback ) { /** * Rendering the field. * * @param Field $field The passed in `CMB2_Field` object. * @param mixed $escaped_value The value of this field escaped. * @param int $object_id The ID of the current object. * @param string $object_type The type of object you are working with. * @param \CMB2_Types $field_types The `CMB2_Types` object. */ return function ( $field, $escaped_value, $object_id, $object_type, $field_types ) use ( $callback ) { if ( $field instanceof Contracts\Field ) { $callback( $field, $escaped_value, $field_types ); } }; }
Get the render field callback. @param callable $callback @return \Closure
entailment
protected static function get_sanitize_callback( $sanitize_cb ) { /** * Filter the value before it is saved.a * * @param bool|mixed $check The check variable. * @param mixed $value The value to be saved to this field. * @param int $object_id The ID of the object where the value will be saved. * @param array $field_args The current field's arguments. * @param \CMB2_Sanitize $sanitizer The `CMB2_Sanitize` object. * * @return mixed */ return function( $check, $value, $object_id, $field_args, $sanitizer ) use ( $sanitize_cb ) { if ( $field_args['repeatable'] ) { return Utils::filter_blank( is_array( $value ) ? array_map( $sanitize_cb, $value ) : [] ); } return $sanitize_cb( $value ); }; }
Get the sanitize callback. @param callable $sanitize_cb The sanitize callback. @return \Closure
entailment
public static function syncConfig(Connection $connection, array $configs, \Closure $callback) { foreach ($configs as $row) { $config = $connection->fetchAssoc('SELECT id, name FROM fusio_config WHERE name = :name', [ 'name' => $row['name'] ]); if (empty($config)) { self::insertRow('fusio_config', $row, $callback); } } }
Helper method to sync all config values of an existing system @param \Doctrine\DBAL\Connection $connection @param array $configs @param \Closure $callback
entailment
public static function syncRoutes(Connection $connection, array $routes, \Closure $callback) { $scopes = []; $maxId = (int) $connection->fetchColumn('SELECT MAX(id) AS max_id FROM fusio_routes'); foreach ($routes as $row) { $route = $connection->fetchAssoc('SELECT id, status, priority, methods, controller FROM fusio_routes WHERE path = :path', [ 'path' => $row['path'] ]); if (empty($route)) { // the route does not exist so create it self::insertRow('fusio_routes', $row, $callback); $maxId++; $scopeId = NewInstallation::getScopeIdFromPath($row['path']); if ($scopeId !== null) { $scopes[] = [ 'scope_id' => $scopeId, 'route_id' => $maxId, 'allow' => 1, 'methods' => 'GET|POST|PUT|PATCH|DELETE', ]; } } else { // the route exists check whether something has changed $columns = ['status', 'priority', 'controller']; self::updateRow('fusio_routes', $row, $route, $columns, $callback); } } if (!empty($scopes)) { // add new routes to scopes foreach ($scopes as $row) { self::insertRow('fusio_scope_routes', $row, $callback); } } }
Helper method to sync all routes of an existing system @param \Doctrine\DBAL\Connection $connection @param array $routes @param \Closure $callback
entailment
public function getViewHelperConfig() { return array( 'factories' => array( 'calendar' => function ($vhm) { $helper = new \BmCalendar\View\Helper\Calendar(); $helper->setRenderer(new \BmCalendar\Renderer\HtmlCalendar()); return $helper; } ), ); }
{@inheritDoc} @return array
entailment
public function toOptionArray() { $selection = array(); foreach ($this->config->getStorageTypes() as $storageType) { $selection[] = [ 'label' => __($storageType['label']), 'value' => $storageType['value'] ]; } return $selection; }
{@inheritdoc}
entailment
public function monthTitle(Month $month) { $weekendClass = 'bm-calendar-weekend'; $monthName = self::$monthNames[$month->value()]; $output = '<thead>'; $output .= '<tr>'; $output .= '<th colspan="7" class="bm-calendar-month-title">' . $monthName . '</th>'; $output .= '</tr><tr>'; // Display the headings for the days of the week. for ($column = 0; $column < 7; $column++) { $day = ($column + $this->startDay - 1) % 7 + 1; if (DayInterface::SATURDAY === $day || DayInterface::SUNDAY === $day) { $output .= '<th class="' . $weekendClass . '">'; } else { $output .= '<th>'; } $output .= self::$dayNames[$day]; $output .= '</th>'; } $output .= '</tr>'; $output .= '</thead>'; return $output; }
Returns the markup for the header of a month table. @param Month $month @return string
entailment
public function renderDay(DayInterface $day) { $classes = array(); $dayOfWeek = $day->dayOfWeek(); if (DayInterface::SATURDAY === $dayOfWeek || DayInterface::SUNDAY === $dayOfWeek) { $classes[] = 'bm-calendar-weekend'; } foreach ($day->getStates() as $state) { $classes[] = 'bm-calendar-state-' . $state->type(); } $output = '<td>'; if (sizeof($classes)) { $output = '<td class="' . implode(' ', $classes) . '">'; } if ($day->getAction()) { $output .= '<a href="' . htmlentities($day->getAction()) . '">' . $day . '</a>'; } else { $output .= $day; } $output .= '</td>'; return $output; }
Returns the markup for a single table cell. @param DayInterface $day @return string
entailment
public function renderMonth($year, $month) { $monthClass = sprintf('bm-calendar-month-%02d', $month); $yearClass = sprintf('bm-calendar-year-%04d', $year); $month = $this->calendar->getMonth($year, $month); $days = $this->calendar->getDays($month); $column = 0; $output = '<table class="bm-calendar ' . $monthClass . ' ' . $yearClass .'">'; $output .= $this->monthTitle($month); $output .= '<tbody>'; $output .= '<tr>'; $blankCells = ($month->startDay() - $this->startDay + 7) % 7; while ($column < $blankCells) { $output .= '<td class="bm-calendar-empty"></td>'; $column++; } foreach ($days as $day) { if (1 !== $day->value() && 0 === $column) { $output .= '</tr><tr>'; } $output .= $this->renderDay($day, $column); $column = ($column + 1) % 7; } while ($column < 7) { $output .= '<td class="bm-calendar-empty"></td>'; $column++; } $output .= '</tr>'; $output .= '</tbody>'; $output .= '</table>'; return $output; }
Render a month table internally. @param int $yearNo @param int $monthNo @return string
entailment
protected function getCommandConfig($commandKey) { if (isset($this->configsPerCommandKey[$commandKey])) { return $this->configsPerCommandKey[$commandKey]; } $config = new Config($this->config->get('default')->toArray(), true); if ($this->config->__isset($commandKey)) { $commandConfig = $this->config->get($commandKey); $config->merge($commandConfig); } $this->configsPerCommandKey[$commandKey] = $config; return $config; }
Gets the config for given command key @param string $commandKey @return Config
entailment
protected function getCommandsRunning() { $commandKeys = array(); foreach (new \APCIterator('user', '/^' . ApcStateStorage::CACHE_PREFIX . '/') as $counter) { // APC entries do not expire within one request context so we have to check manually: if ($counter['creation_time'] + $counter['ttl'] < time()) { continue; } $expressionToExtractCommandKey = '/^' . ApcStateStorage::CACHE_PREFIX . '(.*)_(?:.*)_(?:[0-9]+)$/'; preg_match($expressionToExtractCommandKey, $counter['key'], $match); if (!isset($match[1])) { throw new \RuntimeException('Invalid counter key: ' . $counter['key']); } $commandKey = $match[1]; if (!in_array($commandKey, $commandKeys)) { // as we store APC entries longer than statistical window, we need to check manually if it's in it $statisticalWindowInSeconds = $this->getCommandConfig($commandKey)->get('metrics') ->get('rollingStatisticalWindowInMilliseconds') / 1000; if ($statisticalWindowInSeconds + $counter['creation_time'] >= time()) { $commandKeys[] = $commandKey; } } } return $commandKeys; }
Finds all commands currently running (having any metrics recorded within the statistical rolling window). @return array @throws \RuntimeException When entry with invalid name found in cache
entailment
public function getStatsForCommandsRunning() { $stats = array(); $commandKeys = $this->getCommandsRunning(); foreach ($commandKeys as $commandKey) { $commandConfig = $this->getCommandConfig($commandKey); $commandMetrics = $this->commandMetricsFactory->get($commandKey, $commandConfig); $circuitBreaker = $this->circuitBreakerFactory->get($commandKey, $commandConfig, $commandMetrics); $healtCounts = $commandMetrics->getHealthCounts(); $commandStats = array( // We have to use "HystrixCommand" exactly, otherwise it won't work 'type' => 'HystrixCommand', 'name' => $commandKey, 'group' => $commandKey, // unused in Phystrix 'currentTime' => $this->getTimeInMilliseconds(), 'isCircuitBreakerOpen' => $circuitBreaker->isOpen(), 'errorPercentage' => $healtCounts->getErrorPercentage(), 'errorCount' => $healtCounts->getFailure(), 'requestCount' => $healtCounts->getTotal(), 'rollingCountCollapsedRequests' => 0, // unused in Phystrix 'rollingCountExceptionsThrown' => $commandMetrics->getRollingCount(MetricsCounter::EXCEPTION_THROWN), 'rollingCountFailure' => $commandMetrics->getRollingCount(MetricsCounter::FAILURE), 'rollingCountFallbackFailure' => $commandMetrics->getRollingCount(MetricsCounter::FALLBACK_FAILURE), 'rollingCountFallbackRejection' => 0, // unused in Phystrix (concurrency thing) 'rollingCountFallbackSuccess' => $commandMetrics->getRollingCount(MetricsCounter::FALLBACK_SUCCESS), 'rollingCountResponsesFromCache' => $commandMetrics->getRollingCount(MetricsCounter::RESPONSE_FROM_CACHE), 'rollingCountSemaphoreRejected' => 0, // unused in Phystrix 'rollingCountShortCircuited' => $commandMetrics->getRollingCount(MetricsCounter::SHORT_CIRCUITED), 'rollingCountSuccess' => $commandMetrics->getRollingCount(MetricsCounter::SUCCESS), 'rollingCountThreadPoolRejected' => 0, // unused in Phystrix 'rollingCountTimeout' => 0, // unused in Phystrix. 'currentConcurrentExecutionCount' => 0, // Latency is not tracked in phystrix 'latencyExecute_mean' => 0, 'latencyExecute' => array('0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, '99.5' => 0, '100' => 0), 'latencyTotal_mean' => 15, 'latencyTotal' => array('0' => 0, '25' => 0, '50' => 0, '75' => 0, '90' => 0, '95' => 0, '99' => 0, '99.5' => 0, '100' => 0), 'propertyValue_circuitBreakerRequestVolumeThreshold' => $commandConfig->get('circuitBreaker')->get('requestVolumeThreshold'), 'propertyValue_circuitBreakerSleepWindowInMilliseconds' => $commandConfig->get('circuitBreaker')->get('sleepWindowInMilliseconds'), 'propertyValue_circuitBreakerErrorThresholdPercentage' => $commandConfig->get('circuitBreaker')->get('errorThresholdPercentage'), 'propertyValue_circuitBreakerForceOpen' => $commandConfig->get('circuitBreaker')->get('forceOpen'), 'propertyValue_circuitBreakerForceClosed' => $commandConfig->get('circuitBreaker')->get('forceClosed'), 'propertyValue_circuitBreakerEnabled' => $commandConfig->get('circuitBreaker')->get('enabled'), 'propertyValue_executionIsolationStrategy' => 'THREAD', // unused in Phystrix 'propertyValue_executionIsolationThreadTimeoutInMilliseconds' => 0, // unused in Phystrix 'propertyValue_executionIsolationThreadInterruptOnTimeout' => false, // unused in Phystrix 'propertyValue_executionIsolationThreadPoolKeyOverride' => 'null', // unused in Phystrix 'propertyValue_executionIsolationSemaphoreMaxConcurrentRequests' => 0, // unused in Phystrix 'propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests' => 0, // unused in Phystrix 'propertyValue_metricsRollingStatisticalWindowInMilliseconds' => $commandConfig->get('metrics')->get('rollingStatisticalWindowInMilliseconds'), 'propertyValue_requestCacheEnabled' => $commandConfig->get('requestCache')->get('enabled'), 'propertyValue_requestLogEnabled' => $commandConfig->get('requestLog')->get('enabled'), 'reportingHosts' => 1, ); $stats[] = $commandStats; } return $stats; }
Finds all commands currently running (having any metrics recorded within the statistical rolling window). For each command key prepares a set of statistic. Returns all sets. @return array
entailment
public function saveMessage($mail) { // convert message to html $messageHtml = quoted_printable_decode( $mail->getMessage()->getBodyHtml(true) ); $this->createFolder( $this->getMailFolderPathById($mail->getId()) ); // try to store message to filesystem $this->storeFile( $messageHtml, $this->getMailFolderPathById($mail->getId()) . DIRECTORY_SEPARATOR . self::MESSAGE_HTML_FILE_NAME ); // convert message to json $messageJson = json_encode($mail->getMessage()); // try to store message to filesystem $this->storeFile( $messageJson, $this->getMailFolderPathById($mail->getId()) . DIRECTORY_SEPARATOR . self::MESSAGE_FILE_NAME ); return $this; }
Save file to spool path @param \Shockwavemk\Mail\Base\Model\Mail $mail @return $this @throws \Magento\Framework\Exception\MailException @throws \Magento\Framework\Exception\FileSystemException @throws \Exception
entailment
protected function createFolder($folderPath) { if(!@mkdir($folderPath,0777,true) && !is_dir($folderPath)) { throw new FileSystemException( new Phrase('Folder can not be created, but does not exist.') ); } return $this; }
Create a folder path, if folder does not exist @param $folderPath @return $this @throws \Magento\Framework\Exception\FileSystemException
entailment
protected function storeFile($data, $filePath) { // create a folder for message if needed if (!is_dir(dirname($filePath))) { $this->createFolder(dirname($filePath)); } /** @noinspection LoopWhichDoesNotLoopInspection */ for ($i = 0; $i < $this->_config->getHostRetryLimit(); $i++) { /* We try an exclusive creation of the file. * This is an atomic operation, it avoid locking mechanism */ $fp = @fopen($filePath, 'x'); if($fp !== false) { if (false === fwrite($fp, $data)) { return false; } fclose($fp); return $filePath; } } throw new FileSystemException( new Phrase('Unable to create a file for enqueuing Message') ); }
Stores string data at a given path @param $data @param $filePath @return bool @throws \Magento\Framework\Exception\FileSystemException @throws \Exception
entailment
public function loadMessage($mail) { $localFilePath = $this->getMailFolderPathById($mail->getId()) . DIRECTORY_SEPARATOR . self::MESSAGE_FILE_NAME; $messageJson = $this->restoreFile($localFilePath); if (empty($messageJson)) { $messageJson = '{}'; } $messageData = json_decode($messageJson); /** @var \Shockwavemk\Mail\Base\Model\Mail\Message $message */ $message = $this->_objectManager->create('Shockwavemk\Mail\Base\Model\Mail\Message'); if (!empty($messageData->type)) { $message->setType($messageData->type); } if (!empty($messageData->txt)) { $message->setBodyText($messageData->txt); } if (!empty($messageData->html)) { $message->setBodyHtml($messageData->html); } if (!empty($messageData->from)) { $message->setFrom($messageData->from); } if (!empty($messageData->subject)) { $message->setSubject($messageData->subject); } if (!empty($messageData->recipients)) { foreach ($messageData->recipients as $recipient) { $message->addTo($recipient); } } return $message; }
Restore a message from filesystem @param \Shockwavemk\Mail\Base\Model\Mail $mail @return \Shockwavemk\Mail\Base\Model\Mail\Message $message @throws \Exception @throws \Zend_Mail_Exception
entailment
private function restoreFile($filePath) { try { for ($i = 0; $i < $this->_config->getHostRetryLimit(); ++$i) { /* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */ @fopen($filePath, 'x'); if (false === $fileData = file_get_contents($filePath)) { return null; } return $fileData; } } catch (\Exception $e) { return null; } return null; }
Load binary file data from a given file path @param $filePath @return null|string
entailment
public function saveMail($mail) { // first save file to spool path // to avoid exceptions on external storage provider connection // convert message to json $mailJson = json_encode($mail); $this->createFolder( $this->getMailFolderPathById($mail->getId()) ); // try to store message to filesystem return $this->storeFile( $mailJson, $this->getMailFolderPathById($mail->getId()) . DIRECTORY_SEPARATOR . self::MAIL_FILE_NAME ); }
Convert a mail object to json and store it at mail folder path @param \Shockwavemk\Mail\Base\Model\Mail $mail @return bool @throws \Magento\Framework\Exception\FileSystemException @throws \Exception
entailment
public function loadMail($id) { /** @var \Shockwavemk\Mail\Base\Model\Mail $mail */ $mail = $this->_objectManager->create('Shockwavemk\Mail\Base\Model\Mail'); $mail->setId($id); $localFilePath = $this->getMailFolderPathById( $mail->getId()) . DIRECTORY_SEPARATOR . self::MAIL_FILE_NAME; $mailJson = $this->restoreFile($localFilePath); /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($mailJson)) { $mailJson = '{}'; } /** @noinspection IsEmptyFunctionUsageInspection */ if (!empty($mailData = json_decode($mailJson, true))) { foreach ($mailData as $key => $value) { $mail->setData($key, $value); } } return $mail; }
Loads json file from storage and converts/parses it to a new mail object @param int $id folder name / id eg. pub/media/emails/66 @return \Shockwavemk\Mail\Base\Model\Mail @throws \Exception
entailment
public function loadAttachment($mail, $path) { $attachmentFolder = DIRECTORY_SEPARATOR . self::ATTACHMENT_PATH; $localFilePath = $this->getMailFolderPathById($mail->getId()) . $attachmentFolder . $path; return $this->restoreFile($localFilePath); }
Load binary data from storage provider @param \Shockwavemk\Mail\Base\Model\Mail $mail @param string $path @return string
entailment
public function getAttachments($mail) { /** @noinspection IsEmptyFunctionUsageInspection */ if(empty($mail->getId())) { return []; } $folderFileList = $this->getMailLocalFolderFileList($mail); $attachments = []; foreach ($folderFileList as $filePath => $fileMetaData) { $filePath = $fileMetaData['path']; /** @var \Shockwavemk\Mail\Base\Model\Mail\Attachment $attachment */ $attachment = $this->_objectManager ->create('\Shockwavemk\Mail\Base\Model\Mail\Attachment'); $attachment->setFilePath($filePath); $attachment->setMail($mail); // transfer all meta data into attachment object foreach ($fileMetaData as $attributeKey => $attributeValue) { $attachment->setData($attributeKey, $attributeValue); } $attachments[$filePath] = $attachment; } return $attachments; }
Returns attachments for a given mail \Shockwavemk\Mail\Base\Model\Mail $mail @return \Shockwavemk\Mail\Base\Model\Mail\Attachment[]
entailment
protected function getMailLocalFolderFileList($mail) { $spoolFolder = $this->_config->getHostSpoolerFolderPath() . DIRECTORY_SEPARATOR . $mail->getId() . DIRECTORY_SEPARATOR . self::ATTACHMENT_PATH; // create a folder for attachments if needed if (!is_dir($spoolFolder)) { $this->createFolder($spoolFolder); } /** @var RecursiveIteratorIterator $objects */ $objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($spoolFolder), RecursiveIteratorIterator::LEAVES_ONLY, FilesystemIterator::SKIP_DOTS ); /** @var array $files */ $files = []; /** * @var string $name * @var SplFileObject $object */ foreach ($objects as $path => $object) { /** @noinspection TypeUnsafeComparisonInspection */ /** @noinspection NotOptimalIfConditionsInspection */ if ($object->getFilename() != '.' && $object->getFilename() != '..') { $filePath = str_replace($spoolFolder, '', $path); $file = [ 'name' => $object->getFilename(), 'path' => $path ]; $files[$filePath] = $file; } } return $files; }
Get file list for a given mail @param \Shockwavemk\Mail\Base\Model\Mail $mail @return array
entailment
public function saveAttachments($mail) { /** @var \Shockwavemk\Mail\Base\Model\Mail\Attachment[] $attachments */ $attachments = $mail->getAttachments(); foreach ($attachments as $attachment) { $this->saveAttachment($attachment); } return $this; }
Save all attachments of a given mail @param \Shockwavemk\Mail\Base\Model\Mail $mail @return $this @throws \Magento\Framework\Exception\FileSystemException @throws \Magento\Framework\Exception\MailException @throws \Exception
entailment
public function saveAttachment($attachment) { $binaryData = $attachment->getBinary(); /** @var \Shockwavemk\Mail\Base\Model\Mail $mail */ $mail = $attachment->getMail(); $folderPath = $this->getMailFolderPathById($mail->getId()) . DIRECTORY_SEPARATOR . self::ATTACHMENT_PATH; // create a folder for message if needed $this->createFolder($folderPath); // try to store message to filesystem $filePath = $this->storeFile( $binaryData, $this->getMailFolderPathById($mail->getId()) . DIRECTORY_SEPARATOR . self::ATTACHMENT_PATH . DIRECTORY_SEPARATOR . basename($attachment->getFilePath()) ); $attachment->setFilePath($filePath); }
Save an attachment binary to a file in host temp folder @param \Shockwavemk\Mail\Base\Model\Mail\Attachment $attachment @return int $id @throws \Magento\Framework\Exception\FileSystemException @throws \Magento\Framework\Exception\MailException @throws \Exception
entailment
public function getRootLocalFolderFileList() { $spoolFolder = $this->_config->getHostSpoolerFolderPath(); /** @var IteratorIterator $objects */ $objects = new IteratorIterator( new DirectoryIterator($spoolFolder) ); /** @var array $files */ $files = []; /** * @var string $name * @var SplFileObject $object */ foreach ($objects as $path => $object) { /** @noinspection TypeUnsafeComparisonInspection */ /** @noinspection NotOptimalIfConditionsInspection */ if ($object->getFilename() != '.' && $object->getFilename() != '..') { /** @noinspection PhpMethodOrClassCallIsNotCaseSensitiveInspection */ $shortFilePath = str_replace($spoolFolder, '', $object->getPathName()); /** @noinspection PhpMethodOrClassCallIsNotCaseSensitiveInspection */ $files[] = [ 'name' => $object->getFilename(), 'localPath' => $object->getPathName(), 'remotePath' => $shortFilePath, 'modified' => $object->getMTime() ]; } } return $files; }
Get Folder list for host spooler folder path @return string[]
entailment
public function getLocalFileListForPath($localPath) { $files = []; $objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($localPath), RecursiveIteratorIterator::LEAVES_ONLY, FilesystemIterator::SKIP_DOTS ); /** * @var string $path * @var SplFileObject $object */ foreach ($objects as $path => $object) { /** @noinspection TypeUnsafeComparisonInspection */ /** @noinspection NotOptimalIfConditionsInspection */ if ($object->getFilename() != '.' && $object->getFilename() != '..') { $hostTempFolderPath = $this->_config->getHostSpoolerFolderPath(); /** @noinspection PhpMethodOrClassCallIsNotCaseSensitiveInspection */ $remoteFilePath = str_replace($hostTempFolderPath, '/', $object->getPathName()); /** @noinspection PhpMethodOrClassCallIsNotCaseSensitiveInspection */ $file = [ 'name' => $object->getFilename(), 'localPath' => $object->getPathName(), 'remotePath' => $remoteFilePath, 'modified' => $object->getMTime() ]; $files[$object->getFilename()] = $file; } } return $files; }
Get list of files in a local file path @param $localPath @return string[]
entailment
public function deleteLocalFiles($localPath) { $it = new RecursiveDirectoryIterator( $localPath, RecursiveDirectoryIterator::SKIP_DOTS ); $files = new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { if ($file->isDir()) { rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($localPath); }
Deletes all local stored files @param $localPath @return \Shockwavemk\Mail\Base\Model\Storages\DefaultStorage
entailment
public function setAttribute($userId, $name, $value) { $row = $this->connection->fetchAssoc('SELECT id FROM fusio_user_attribute WHERE name = :name', ['name' => $name]); if (empty($row)) { $this->connection->insert('fusio_user_attribute', [ 'user_id' => $userId, 'name' => $name, 'value' => $value, ]); } else { $this->connection->update('fusio_user_attribute', [ 'user_id' => $userId, 'name' => $name, 'value' => $value, ], [ 'id' => $row['id'] ]); } }
Sets a specific user attribute @param integer $userId @param string $name @param string $value
entailment
private function getSubmittedVersionNumber(RequestInterface $request) { $accept = $request->getHeader('Accept'); $matches = array(); preg_match('/^application\/vnd\.([a-z.-_]+)\.v([\d]+)\+([a-z]+)$/', $accept, $matches); return isset($matches[2]) ? $matches[2] : null; }
Returns the version number which was submitted by the client in the accept header field @return integer
entailment
private function generateRulePair($line, array $whiteList) { // Split by directive and rule $pair = array_map('trim', explode(':', $line, 2)); // Check if the line contains a rule if (empty($pair[1]) || empty($pair[0]) || !in_array(($pair[0] = str_ireplace(array_keys(self::ALIAS_DIRECTIVES), array_values(self::ALIAS_DIRECTIVES), strtolower($pair[0]))), $whiteList) ) { // Line does not contain any supported directive return false; } return $pair; }
Generate directive/rule pair @param string $line @param string[] $whiteList @return string[]|false
entailment
private function draftParseTime($string) { $array = explode('-', str_replace('+', '', filter_var($string, FILTER_SANITIZE_NUMBER_INT)), 3); if (count($array) !== 2 || ($fromTime = date_create_from_format('Hi', $array[0], $dtz = new DateTimeZone('UTC'))) === false || ($toTime = date_create_from_format('Hi', $array[1], $dtz)) === false ) { return false; } return [ 'from' => date_format($fromTime, 'Hi'), 'to' => date_format($toTime, 'Hi'), ]; }
Client timestamp range as specified in the `Robot exclusion standard` version 2.0 draft @link http://www.conman.org/people/spc/robots2.html#format.directives.visit-time @param $string @return string[]|false
entailment
public function hasPermission(RoleInterface $role, $permissionCode) { if ($this->cache->contains($this->getCacheKey($role))) { return in_array($permissionCode, $this->cache->fetch($this->getCacheKey($role))); } $permissions = $this->map->getPermissions($role); $permissionsCache = []; foreach ($permissions as $permission) { $permissionsCache[] = $permission->getCode(); } $this->cache->save($this->getCacheKey($role), $permissionsCache, $this->ttl); return in_array($permissionCode, $permissionsCache); }
{@inheritdoc}
entailment
private function parseTxt($txt) { $result = []; $lines = array_map('trim', mb_split('\r\n|\n|\r', $txt)); // Parse each line individually foreach ($lines as $key => $line) { // Limit rule length $line = mb_substr($line, 0, self::MAX_LENGTH_RULE); // Remove comments $line = explode('#', $line, 2)[0]; // Parse line $result[] = $this->parseLine($line); unset($lines[$key]); } return in_array(true, $result, true); }
Client robots.txt @param string $txt @return bool
entailment
private function parseLine($line) { if (($pair = $this->generateRulePair($line, array_keys(self::TOP_LEVEL_DIRECTIVES))) !== false) { return $this->handler->{self::TOP_LEVEL_DIRECTIVES[$pair[0]]}->add($pair[1]); }
Add line @param string $line @return bool
entailment
public function get( $key, $default = null ) { $metadata = get_metadata( $this->meta_type, $this->object_id, $key, true ); return false !== $metadata ? $metadata : $default; }
{@inheritdoc}
entailment
public function set( $key, $value ) { return (bool) update_metadata( $this->meta_type, $this->object_id, $key, $value ); }
{@inheritdoc}
entailment
public function accessOverride() { if (strpos($this->scheme, 'http') === 0) { switch (floor($this->code / 100) * 100) { case 300: case 400: return self::DIRECTIVE_ALLOW; case 500: return self::DIRECTIVE_DISALLOW; } } return false; }
Check if the code overrides the robots.txt file @link https://developers.google.com/webmasters/control-crawl-index/docs/robots_txt#handling-http-result-codes @link https://yandex.com/support/webmaster/controlling-robot/robots-txt.xml#additional-info @return string|false
entailment
public function initialize() { static::initialize_registry(); $this->prepare_form_data(); $this->make_fields_validation(); Dependency::check( $this->fields->all(), $this->data ); if ( $error_name = $this->config->get_option( 'resolve_errors' ) ) { $this->resolve_flash_errors( $error_name ); } if ( $this->config->get_option( 'old_values' ) ) { $this->fill_old_values(); } $this->initialized = true; }
{@inheritdoc}
entailment