sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function normalizeHeaders(array $headers) { $ignoreHeaders = $this->ignoreHeaders; foreach ($ignoreHeaders as $ignoreHeader) { $headers = array_filter($headers, function($header) use ($ignoreHeader) { return stripos($header, $ignoreHeader.':') !== 0; }); } return $headers; }
Get only those headers that should not be ignored @param array $headers @return array
entailment
public function get($pages = 0) { $endpoint = $this->getEndpoint(); $params = $this->getParams(); $list = $this->getClient()->request($endpoint, 'GET', $params); $i = 1; while ($list['metadata']['continue']) { if ($pages > 0 && $pages >= $i) { return $list; } $params['continue'] = $list['metadata']['continue']; $i_list = $this->getClient()->request($endpoint, 'GET', $params); $i_list['items'] = array_merge($list['items'], $i_list['items']); $list = $i_list; unset($i_list); $i++; } return $list; }
Get all values from a list endpoint. Full list is returned as if made in a single call. @param int $pages @return bool|mixed|string @throws \Exception
entailment
public function stream() { $endpoint = $this->getEndpoint(); $params = $this->getParams(); $list = $this->getClient()->request($endpoint, 'GET', $params); foreach ($list['items'] as $item) { yield $item; } while ($list['metadata']['continue']) { $params['continue'] = $list['metadata']['continue']; $list = $this->getClient()->request($endpoint, 'GET', $params); foreach ($list['items'] as $item) { yield $item; } } }
Get all values from a list endpoint. Used for iterators like foreach(). @return \Generator @throws \Exception
entailment
public function sortIds($idList, $strDirection) { if (!$this->isProperlyConfigured()) { return $idList; } $strTableName = $this->getSelectSource(); $strColNameId = $this->getIdColumn(); $strSortColumn = $this->getSortingColumn(); $idList = $this->connection->createQueryBuilder() ->select('m.id') ->from($this->getMetaModel()->getTableName(), 'm') ->leftJoin('m', $strTableName, 's', sprintf('s.%s = m.%s', $strColNameId, $this->getColName())) ->where('m.id IN (:ids)') ->orderBy('s.' . $strSortColumn, $strDirection) ->setParameter('ids', $idList, Connection::PARAM_STR_ARRAY) ->execute() ->fetchAll(\PDO::FETCH_COLUMN); return $idList; }
{@inheritdoc}
entailment
public function valueToWidget($varValue) { if (!is_array($varValue) || !array_key_exists($idColumn = $this->getIdColumn(), $varValue)) { return null; } return ($varValue[$idColumn] ?? null); }
{@inheritdoc}
entailment
public function widgetToValue($varValue, $itemId) { if (null === $varValue) { return null; } // Lookup the value. $value = $this->connection->createQueryBuilder() ->select('*') ->from($this->getSelectSource()) ->where($this->getIdColumn() . '=:id') ->setParameter('id', $varValue) ->setMaxResults(1) ->execute() ->fetch(\PDO::FETCH_ASSOC); return $value; }
{@inheritdoc}
entailment
public function getFilterOptionsForDcGeneral() { if (!$this->isFilterOptionRetrievingPossible(null)) { return array(); } $values = $this->getFilterOptionsForUsedOnly(false); return $this->convertOptionsList($values, $this->getIdColumn(), $this->getValueColumn()); }
{@inheritDoc} @SuppressWarnings(PHPMD.Superglobals) @SuppressWarnings(PHPMD.CamelCaseVariableName)
entailment
protected function convertOptionsList($statement, $aliasColumn, $valueColumn, &$count = null) { $arrReturn = array(); while ($values = $statement->fetch(\PDO::FETCH_OBJ)) { if (is_array($count)) { /** @noinspection PhpUndefinedFieldInspection */ $count[$values->$aliasColumn] = $values->mm_count; } $arrReturn[$values->$aliasColumn] = $values->$valueColumn; } return $arrReturn; }
Convert the database result into a proper result array. @param Statement $statement The database result statement. @param string $aliasColumn The name of the alias column to be used. @param string $valueColumn The name of the value column. @param array $count The optional count array. @return array
entailment
public function getFilterOptionsForUsedOnly($usedOnly) { $sortColumn = $this->getSortingColumn(); if ($usedOnly) { $builder = $this->connection->createQueryBuilder() ->select('COUNT(sourceTable.' . $this->getIdColumn() . ') as mm_count') ->addSelect('sourceTable.*') ->from($this->getSelectSource(), 'sourceTable') ->rightJoin( 'sourceTable', $this->getMetaModel()->getTableName(), 'modelTable', 'modelTable.' . $this->getColName() . '=sourceTable.' . $this->getIdColumn() ) ->addGroupBy('sourceTable.' . $this->getIdColumn()) ->addOrderBy('sourceTable.' . $sortColumn); if ($additionalWhere = $this->getAdditionalWhere()) { $builder->andWhere($additionalWhere); } return $builder->execute(); } $builder = $this->connection->createQueryBuilder() ->select('COUNT(modelTable.' . $this->getColName() . ') as mm_count') ->addSelect('sourceTable.*') ->from($this->getSelectSource(), 'sourceTable') ->leftJoin( 'sourceTable', $this->getMetaModel()->getTableName(), 'modelTable', 'modelTable.' . $this->getColName() . '=sourceTable.' . $this->getIdColumn() ) ->addGroupBy('sourceTable.' . $this->getIdColumn()) ->addOrderBy('sourceTable.' . $sortColumn); if ($additionalWhere = $this->getAdditionalWhere()) { $builder->andWhere($additionalWhere); } return $builder->execute(); }
Fetch filter options from foreign table taking the given flag into account. @param bool $usedOnly The flag if only used values shall be returned. @return Statement
entailment
public function getFilterOptions($idList, $usedOnly, &$arrCount = null) { if (!$this->isFilterOptionRetrievingPossible($idList)) { return array(); } $tableName = $this->getSelectSource(); $idColumn = $this->getIdColumn(); $strSortColumn = $this->getSortingColumn(); if ($idList) { $builder = $this->connection->createQueryBuilder() ->select('COUNT(sourceTable.' . $idColumn . ') as mm_count') ->addSelect('sourceTable.*') ->from($tableName, 'sourceTable') ->rightJoin( 'sourceTable', $this->getMetaModel()->getTableName(), 'modelTable', 'modelTable.' . $this->getColName() . '=sourceTable.' . $idColumn ) ->where('modelTable.id IN (:ids)') ->setParameter('ids', $idList, Connection::PARAM_STR_ARRAY) ->addGroupBy('sourceTable.' . $idColumn) ->addOrderBy('sourceTable.' . $strSortColumn); if ($additionalWhere = $this->getAdditionalWhere()) { $builder->andWhere($additionalWhere); } $statement = $builder->execute(); } else { $statement = $this->getFilterOptionsForUsedOnly($usedOnly); } return $this->convertOptionsList($statement, $this->getAliasColumn(), $this->getValueColumn(), $arrCount); }
{@inheritdoc} Fetch filter options from foreign table.
entailment
public function getDataFor($arrIds) { if (!$this->isProperlyConfigured()) { return array(); } $strTableNameId = $this->getSelectSource(); $strColNameId = $this->getIdColumn(); $arrReturn = []; $strMetaModelTableName = $this->getMetaModel()->getTableName(); $strMetaModelTableNameId = $strMetaModelTableName.'_id'; $builder = $this->connection->createQueryBuilder() ->select('sourceTable.*') ->addSelect('modelTable.id AS ' . $strMetaModelTableNameId) ->from($strTableNameId, 'sourceTable') ->leftJoin( 'sourceTable', $strMetaModelTableName, 'modelTable', 'sourceTable.' . $strColNameId . '=modelTable.' . $this->getColName() ) ->where('modelTable.id IN (:ids)') ->setParameter('ids', $arrIds, Connection::PARAM_STR_ARRAY) ->execute(); foreach ($builder->fetchAll(\PDO::FETCH_ASSOC) as $row) { $arrReturn[$row[$strMetaModelTableNameId]] = $row; } return $arrReturn; }
{@inheritdoc}
entailment
public function setDataFor($arrValues) { if (!$this->isProperlyConfigured()) { return; } $strTableName = $this->getSelectSource(); $strColNameId = $this->getIdColumn(); if ($strTableName && $strColNameId) { foreach ($arrValues as $intItemId => $arrValue) { $this->connection->update( $this->getMetaModel()->getTableName(), [$this->getColName() => $arrValue[$strColNameId]], ['id' => $intItemId] ); } } }
{@inheritdoc}
entailment
protected function isProperlyConfigured() { if (isset($this->isProperlyConfigured)) { return $this->isProperlyConfigured; } return $this->isProperlyConfigured = $this->checkConfiguration(); }
Ensure the attribute has been configured correctly. @return bool
entailment
protected function checkConfiguration() { return $this->getSelectSource() && $this->getValueColumn() && $this->getAliasColumn() && $this->getIdColumn() && $this->getSortingColumn(); }
Check the configuration of the attribute. @return bool
entailment
public function getFieldDefinition($arrOverrides = []) { $arrFieldDef = parent::getFieldDefinition($arrOverrides); $this->widgetMode = $arrOverrides['select_as_radio']; if ($this->isTreePicker()) { $arrFieldDef['inputType'] = $this->getPickerType(); $arrFieldDef['eval']['sourceName'] = $this->getSelectSource(); $arrFieldDef['eval']['fieldType'] = 'radio'; $arrFieldDef['eval']['idProperty'] = $this->getIdColumn(); $arrFieldDef['eval']['orderField'] = $this->getSortingColumn(); $arrFieldDef['eval']['minLevel'] = $arrOverrides['select_minLevel']; $arrFieldDef['eval']['maxLevel'] = $arrOverrides['select_maxLevel']; } elseif ($this->widgetMode == 1) { // If select as radio is true, change the input type. $arrFieldDef['inputType'] = 'radio'; } else { $arrFieldDef['inputType'] = 'select'; } return $arrFieldDef; }
{@inheritdoc}
entailment
public function searchFor($strPattern) { $objFilterRule = new FilterRuleSelect($this, $strPattern, $this->connection); return $objFilterRule->getMatchingIds(); }
{@inheritdoc} Search value in table.
entailment
public function unsetDataFor($arrIds) { $this->connection->createQueryBuilder() ->update($this->getMetaModel()->getTableName()) ->set($this->getColName(), 0) ->where('id IN (:ids)') ->setParameter('ids', $arrIds, Connection::PARAM_STR_ARRAY) ->execute(); }
{@inheritdoc}
entailment
public function convertValuesToValueIds($values) { $tableName = $this->getSelectSource(); $idColumn = $this->getIdColumn(); $aliasColumn = $this->getAliasColumn(); if ($idColumn === $aliasColumn) { return $values; } $values = \array_unique(\array_filter($values)); if (empty($values)) { return []; } return $this->connection->createQueryBuilder() ->select($idColumn) ->from($tableName) ->where($aliasColumn . ' IN (:values)') ->setParameter('values', $values, Connection::PARAM_STR_ARRAY) ->execute() ->fetch(\PDO::FETCH_ASSOC); }
Convert the passed values to a list of value ids. @param string[] $values The values to convert. @return string[]
entailment
public static function make($value, $defaultOrder = self::ORDER_ASCENDING) { $value = static::prepareValue($value); list($field, $order) = static::parseFieldAndOrder($value, $defaultOrder); static::validateFieldName($field); return new static($field, $order); }
Creates criterion object for given value. @param string $value query value @param string $defaultOrder default sort order if order is not given explicitly in query @return Criterion
entailment
public function apply(Builder $builder) { $sortMethod = 'sort' . studly_case($this->getField()); if(method_exists($builder->getModel(), $sortMethod)) { call_user_func_array([$builder->getModel(), $sortMethod], [$builder, $this->getOrder()]); } else { $builder->orderBy($this->getField(), $this->getOrder()); } }
Applies criterion to query. @param Builder $builder query builder
entailment
protected static function parseFieldAndOrder($value, $defaultOrder) { if (preg_match('/^([^,]+)(,(asc|desc))?$/', $value, $match)) { return [$match[1], isset($match[3]) ? $match[3] : $defaultOrder]; } throw new InvalidArgumentException(sprintf('Unable to parse field name or order from "%s"', $value)); }
Parse query parameter and get field name and order. @param string $value @param string $defaultOrder default sort order if order is not given explicitly in query @return string[] @throws InvalidArgumentException when unable to parse field name or order
entailment
private function getHandle() { // make sure to clean up old handles if ($this->handle !== null && feof($this->handle)) { $this->resetHandle(); } // provision new handle if ($this->handle == null) { $params = $this->params; if (!empty($this->getResourceVersion())) { $params['resourceVersion'] = $this->getResourceVersion(); } $query = http_build_query($params); $base = $this->getClient()->getConfig()->getServer().$this->endpoint; $url = $base; if (!empty($query)) { $parsed = parse_url($base); if (key_exists('query', $parsed) || substr($base, -1) == "?") { $url .= '&'.$query; } else { $url .= '?'.$query; } } $handle = @fopen($url, 'r', false, $this->getClient()->getStreamContext()); if ($handle === false) { $e = error_get_last(); throw new \Exception($e['message'], $e['type']); } stream_set_timeout($handle, 0, $this->getStreamTimeout()); $this->handle = $handle; } return $this->handle; }
Retrieve (open if necessary) the HTTP connection @throws \Exception @return bool|resource
entailment
public function setStreamTimeout($value) { if ($value < 1) { $value = self::DEFAULT_STREAM_TIMEOUT; } $this->streamTimeout = (int) $value; if ($this->handle !== null) { stream_set_timeout($this->handle, 0, $this->getStreamTimeout()); } }
Set streamTimeout (microseconds) @param $value
entailment
public function setStreamReadLength($value) { if ($value < 1) { $value = self::DEFAULT_STREAM_READ_LENGTH; } $this->streamReadLength = (int) $value; }
Set streamReadLength (bytes) @param $value
entailment
private function setResourceVersion($value) { if ($value > $this->resourceVersion || $value === null) { $this->resourceVersion = $value; } }
Set resourceVersion @param $value
entailment
private function internal_iterator($cycles = 0) { $handle = $this->getHandle(); $i_cycles = 0; while (true) { if ($this->getStop()) { $this->internal_stop(); return; } //$meta = stream_get_meta_data($handle); if (feof($handle)) { if ($this->params['timeoutSeconds'] > 0) { //assume we've reached a successful end of watch return; } else { $this->resetHandle(); $handle = $this->getHandle(); } } $data = fread($handle, $this->getStreamReadLength()); if ($data === false) { throw new \Exception('Failed to read bytes from stream: ' . $this->getClient()->getConfig()->getServer()); } $this->buffer .= $data; //break immediately if nothing is on the buffer if (empty($this->buffer) && $cycles > 0) { return; } if ((bool) strstr($this->buffer, "\n")) { $parts = explode("\n", $this->buffer); $parts_count = count($parts); for ($x = 0; $x < ($parts_count - 1); $x++) { if (!empty($parts[$x])) { try { $response = json_decode($parts[$x], true); $code = $this->preProcessResponse($response); if ($code != 0) { $this->resetHandle(); $this->resourceVersion = null; $handle = $this->getHandle(); goto end; } if ($response['object']['metadata']['resourceVersion'] > $this->getResourceVersionLastSuccess()) { ($this->callback)($response, $this); } $this->setResourceVersion($response['object']['metadata']['resourceVersion']); $this->setResourceVersionLastSuccess($response['object']['metadata']['resourceVersion']); if ($this->getStop()) { $this->internal_stop(); return; } } catch (\Exception $e) { //TODO: log failure } } } $this->buffer = $parts[($parts_count - 1)]; } end: $i_cycles++; if ($cycles > 0 && $cycles >= $i_cycles) { return; } } }
Read and process event messages (closure/callback) @param int $cycles @throws \Exception
entailment
public function fork() { if (!function_exists('pcntl_fork')) { return false; } $pid = pcntl_fork(); if ($pid == -1) { //failure return false; } elseif ($pid) { return true; } else { $this->start(); exit(0); } }
Fork a watch into a new process @return bool @throws \Exception
entailment
public static function getPropertyOptions(GetPropertyOptionsEvent $event) { if ($event->getOptions() !== null) { return; } $model = $event->getModel(); if (!($model instanceof Model)) { return; } $attribute = $model->getItem()->getAttribute($event->getPropertyName()); if (!($attribute instanceof AbstractSelect)) { return; } try { $options = $attribute->getFilterOptionsForDcGeneral(); } catch (\Exception $exception) { $options = ['Error: ' . $exception->getMessage()]; } $event->setOptions($options); }
Retrieve the property options. @param GetPropertyOptionsEvent $event The event. @return void
entailment
public function stop() { $this->setStop(true); foreach ($this->getWatches() as $watch) { $watch->stop(); } }
Stop all watches in the collection and break the loop
entailment
public function stream($cycles = 0) { $i_cycles = 0; while (true) { if ($this->getStop()) { $this->internal_stop(); return; } foreach ($this->getWatches() as $watch) { if ($this->getStop()) { $this->internal_stop(); return; } foreach ($watch->stream(1) as $message) { if ($this->getStop()) { $this->internal_stop(); return; } yield $message; } } $i_cycles++; if ($cycles > 0 && $cycles >= $i_cycles) { return; } } }
Generator interface for looping @param int $cycles @return \Generator|void
entailment
public function getTableAndMetaModelsList() { $sqlTable = $this->translator->trans( 'tl_metamodel_attribute.select_table_type.sql-table', [], 'contao_tl_metamodel_attribute' ); $translated = $this->translator->trans( 'tl_metamodel_attribute.select_table_type.translated', [], 'contao_tl_metamodel_attribute' ); $untranslated = $this->translator->trans( 'tl_metamodel_attribute.select_table_type.untranslated', [], 'contao_tl_metamodel_attribute' ); $result = $this->getMetaModelTableNames($translated, $untranslated); foreach ($this->connection->getSchemaManager()->listTableNames() as $table) { if (0 !== strpos($table, 'mm_')) { $result[$sqlTable][$table] = $table; } } if (\is_array($result[$translated])) { \asort($result[$translated]); } if (\is_array($result[$untranslated])) { \asort($result[$untranslated]); } if (\is_array($result[$sqlTable])) { \asort($result[$sqlTable]); } return $result; }
Retrieve all database table names. @return array @SuppressWarnings(PHPMD.Superglobals) @SuppressWarnings(PHPMD.CamelCaseVariableName)
entailment
public function getTableNames(GetPropertyOptionsEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_attribute') || ($event->getPropertyName() !== 'select_table')) { return; } $event->setOptions($this->getTableAndMetaModelsList()); }
Retrieve all database table names. @param GetPropertyOptionsEvent $event The event. @return void
entailment
protected function getAttributeNamesFrom($metaModelName) { $metaModel = $this->factory->getMetaModel($metaModelName); $result = []; if (empty($metaModel)) { return $result; } foreach ($metaModel->getAttributes() as $attribute) { $name = $attribute->getName(); $column = $attribute->getColName(); $type = $attribute->get('type'); $result[$column] = \sprintf('%s (%s - %s)', $name, $column, $type); } return $result; }
Retrieve all attribute names from a given MetaModel name. @param string $metaModelName The name of the MetaModel. @return string[]
entailment
public function getFilters(GetPropertyOptionsEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_attribute') || ($event->getPropertyName() !== 'select_filter') ) { return; } $model = $event->getModel(); $metaModel = $this->factory->getMetaModel($model->getProperty('select_table')); if ($metaModel) { $statement = $this->connection ->prepare('SELECT id,name FROM tl_metamodel_filter WHERE pid=:pid ORDER BY name'); $statement->execute(['pid' => $metaModel->get('id')]); $result = []; while ($row = $statement->fetch(\PDO::FETCH_OBJ)) { /** @noinspection PhpUndefinedFieldInspection */ $result[$row->id] = $row->name; } $event->setOptions($result); } }
Retrieve all filter names for the currently selected MetaModel. @param GetPropertyOptionsEvent $event The event. @return void
entailment
public function getFiltersParams(BuildWidgetEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_attribute') || ($event->getProperty()->getName() !== 'select_filterparams') ) { return; } $model = $event->getModel(); $properties = $event->getProperty(); $arrExtra = $properties->getExtra(); $filterId = $model->getProperty('select_filter'); // Check if we have a filter, if not return. if (empty($filterId)) { return; } // Get the filter with the given id and check if we got it. // If not return. $filterSettings = $this->filterSettingFactory->createCollection($filterId); if ($filterSettings == null) { return; } // Set the subfields. $arrExtra['subfields'] = $filterSettings->getParameterDCA(); $properties->setExtra($arrExtra); }
Set the sub fields for the sub-dca based in the mm_filter selection. @param BuildWidgetEvent $event The event. @return void
entailment
public function getIntColumnNames(GetPropertyOptionsEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_attribute') || ($event->getPropertyName() !== 'select_id') ) { return; } $result = $this->getColumnNamesFromMetaModel( $event->getModel()->getProperty('select_table'), [Type::INTEGER, Type::BIGINT, Type::SMALLINT] ); $event->setOptions($result); }
Retrieve all column names of type int for the current selected table. @param GetPropertyOptionsEvent $event The event. @return void
entailment
public function buildConditions($propertyNames, PalettesDefinitionInterface $palettes) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } foreach ($palettes->getPalettes() as $palette) { foreach ($propertyNames as $propertyName => $mask) { foreach ($palette->getProperties() as $property) { if ($property->getName() === $propertyName) { // Show the widget when we are editing a select attribute. $condition = new PropertyConditionChain( [ new PropertyConditionChain( [ new PropertyValueCondition('type', 'select'), new ConditionTableNameIsMetaModel('select_table', $mask) ] ) ], ConditionChainInterface::OR_CONJUNCTION ); // If we want to hide the widget for metamodel tables, do so only when editing a select // attribute. if (!$mask) { $condition->addCondition(new NotCondition(new PropertyValueCondition('type', 'select'))); } $this->addCondition($property, $condition); } } } } }
Build the data definition palettes. @param array<string,bool> $propertyNames The property names which shall be masked. @param PalettesDefinitionInterface $palettes The palette definition. @return void
entailment
private static function writeTempFile($data) { $file = tempnam(sys_get_temp_dir(), self::$temp_file_prefix); file_put_contents($file, $data); register_shutdown_function(function () use ($file) { if (file_exists($file)) { unlink($file); } }); return $file; }
Create a temporary file to be used and destroyed at shutdown @param $data @return bool|string
entailment
public static function InClusterConfig() { $config = new Config(); $config->setToken(file_get_contents('/var/run/secrets/kubernetes.io/serviceaccount/token')); $config->setCertificateAuthorityPath('/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'); $config->setServer('https://kubernetes.default.svc'); return $config; }
Create a config based off running inside a cluster @return Config
entailment
public static function BuildConfigFromFile($path = null) { if (empty($path)) { $path = getenv('KUBECONFIG'); } if (empty($path)) { $path = getenv('HOME').'/.kube/config'; } if (!file_exists($path)) { throw new \Exception('Config file does not exist: ' . $path); } $yaml = yaml_parse_file($path); $currentContextName = $yaml['current-context']; $context = null; foreach ($yaml['contexts'] as $item) { if ($item['name'] == $currentContextName) { $context = $item['context']; break; } } $cluster = null; foreach ($yaml['clusters'] as $item) { if ($item['name'] == $context['cluster']) { $cluster = $item['cluster']; break; } } $user = null; foreach ($yaml['users'] as $item) { if ($item['name'] == $context['user']) { $user = $item['user']; break; } } $config = new Config(); $config->setServer($cluster['server']); if (!empty($cluster['certificate-authority-data'])) { $path = self::writeTempFile(base64_decode($cluster['certificate-authority-data'], true)); $config->setCertificateAuthorityPath($path); } if (!empty($user['client-certificate-data'])) { $path = self::writeTempFile(base64_decode($user['client-certificate-data'])); $config->setClientCertificatePath($path); } if (!empty($user['client-key-data'])) { $path = self::writeTempFile(base64_decode($user['client-key-data'])); $config->setClientKeyPath($path); } return $config; }
Create a config from file will auto fallback to KUBECONFIG env variable or ~/.kube/config if no path supplied @param null $path @return Config @throws \Exception
entailment
private function getContextOptions() { $opts = array( 'http'=>array( 'ignore_errors' => true, 'header' => "Accept: application/json, */*\r\nContent-Encoding: gzip\r\n" ), ); if (!empty($this->config->getCertificateAuthorityPath())) { $opts['ssl']['cafile'] = $this->config->getCertificateAuthorityPath(); } if (!empty($this->config->getClientCertificatePath())) { $opts['ssl']['local_cert'] = $this->config->getClientCertificatePath(); } if (!empty($this->config->getClientKeyPath())) { $opts['ssl']['local_pk'] = $this->config->getClientKeyPath(); } $token = $this->config->getToken(); if (!empty($token)) { $opts['http']['header'] .= "Authorization: Bearer ${token}\r\n"; } return $opts; }
Get common options to be used for the stream context @return array
entailment
public function getStreamContext($verb = 'GET', $opts = []) { $o = array_merge_recursive($this->getContextOptions(), $opts); $o['http']['method'] = $verb; if (substr($verb, 0, 5) == 'PATCH') { /** * https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#patch-operations * https://github.com/kubernetes/community/blob/master/contributors/devel/strategic-merge-patch.md * * Content-Type: application/json-patch+json * Content-Type: application/merge-patch+json * Content-Type: application/strategic-merge-patch+json */ switch ($verb) { case 'PATCH-JSON': $o['http']['header'] .= "Content-Type: application/json-patch+json\r\n"; break; case 'PATCH-STRATEGIC-MERGE': $o['http']['header'] .= "Content-Type: application/strategic-merge-patch+json\r\n"; break; case 'PATCH': case 'PATCH-MERGE': default: $o['http']['header'] .= "Content-Type: application/merge-patch+json\r\n"; break; } } else { $o['http']['header'] .= "Content-Type: application/json\r\n"; } return stream_context_create($o); }
Get the stream context @param string $verb @param array $opts @return resource
entailment
public function request($endpoint, $verb = 'GET', $params = [], $data = null) { $context = $this->getStreamContext($verb); if ($data) { stream_context_set_option($context, array('http' => array('content' => json_encode($data)))); } $query = http_build_query($params); $base = $this->getConfig()->getServer().$endpoint; $url = $base; if (!empty($query)) { $parsed = parse_url($base); if (key_exists('query', $parsed) || substr($base, -1) == "?") { $url .= '&'.$query; } else { $url .= '?'.$query; } } $handle = fopen($url, 'r', false, $context); if ($handle === false) { $e = error_get_last(); throw new \Exception($e['message'], $e['type']); } $response = stream_get_contents($handle); fclose($handle); $response = json_decode($response, true); return $response; }
Make a request to the API @param $endpoint @param string $verb @param array $params @param null $data @throws \Exception @return bool|mixed|string
entailment
public function createWatch($endpoint, $params = [], \Closure $callback) { $watch = new Watch($this, $endpoint, $params, $callback); return $watch; }
Create a Watch for api feed @param $endpoint @param array $params @param \Closure $callback @return Watch
entailment
public function toOptionArray() { $helper = Mage::helper('australia'); return array( array('value' => self::AUTHORITY_LEAVE, 'label' => $helper->__('Authority To Leave')), array('value' => self::AUTHORITY_LEAVE_REQUEST, 'label' => $helper->__('Authority To leave can be requested')), array('value' => self::REQUIRED, 'label' => $helper->__('Signature required')), ); }
Options getter @return array
entailment
public function toArray() { $helper = Mage::helper('australia'); return array( self::AUTHORITY_LEAVE => $helper->__('Authority To Leave'), self::AUTHORITY_LEAVE_REQUEST => $helper->__('Authority To leave can be requested'), self::REQUIRED => $helper->__('Signature required'), ); }
Get options in "key-value" format @return array
entailment
protected function _getCsvValues($string, $separator=",") { $elements = explode($separator, trim($string)); for ($i = 0; $i < count($elements); $i++) { $nquotes = substr_count($elements[$i], '"'); if ($nquotes %2 == 1) { for ($j = $i+1; $j < count($elements); $j++) { if (substr_count($elements[$j], '"') %2 == 1) { // Look for an odd-number of quotes // Put the quoted string's pieces back together again array_splice($elements, $i, $j-$i+1, implode($separator, array_slice($elements, $i, $j-$i+1))); break; } } } if ($nquotes > 0) { // Remove first and last quotes, then merge pairs of quotes $qstr =& $elements[$i]; $qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1); $qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1); $qstr = str_replace('""', '"', $qstr); } $elements[$i] = trim($elements[$i]); } return $elements; }
Due to bugs in fgetcsv(), this extension is using tips from php.net. We could potentially swap this out for Zend's CSV parsers after testing for bugs in that. Note: I've updated this code the latest version in the comments on php.net (Jonathan Melnick) @author Jonathan Melnick @author Chris Norton @author Dave Walter @author justin at cam dot org @author Theodule @author dan dot jones at lunarfish dot co dot uk @see http://www.php.net/manual/en/function.split.php#81490 @see https://bugs.php.net/bug.php?id=45356 @see http://stackoverflow.com/questions/12390851/fgetcsv-is-eating-the-first-letter-of-a-string-if-its-an-umlaut @param string $string @param string $separator @return array
entailment
public function decision($string) { // Do not call functions so that we'll compute only one time $dominantClass = $this->sentiment->categorise($string); switch ($dominantClass) { case 'neg': return self::NEGATIVE; case 'neu': return self::NEUTRAL; case 'pos': return self::POSITIVE; } }
Get the sentiment of a phrase. @param string $string The given sentence @return string Possible values: negative|neutral|positive
entailment
public function scores($string) { $scores = $this->sentiment->score($string); $array = []; // The original keys are 'neg' / 'neu' / 'pos' // We will remap to 'negative' / 'neutral' / 'positive' and round with 2 digits foreach ([self::NEGATIVE, self::NEUTRAL, self::POSITIVE] as $value) { $array[$value] = round($scores[substr($value, 0, 3)], 2); } return $array; }
Get scores for each decision. @param string $string The original string @return array An array containing keys 'negative', 'neutral' and 'positive' with a float. The closer to 1, the better @example ['negative' => 0.5, 'neutral' => 0.25, 'positive' => 0.25]
entailment
public function exportAction() { $request = $this->getRequest(); if (!$request->isPost()) { $this->_redirect(self::ADMINHTML_SALES_ORDER_INDEX); } $orderIds = $this->getRequest()->getPost('order_ids', array()); try { // Build the CSV and retrieve its path $filePath = Mage::getModel('australia/shipping_carrier_eparcel_export_csv')->exportOrders($orderIds); // Download the file $this->_prepareDownloadResponse(basename($filePath), file_get_contents($filePath)); } catch (Exception $e) { Mage::getSingleton('core/session')->addError($e->getMessage()); $this->_redirect(self::ADMINHTML_SALES_ORDER_INDEX); } }
Generate and export a CSV file for the given orders.
entailment
public function exportTableratesAction() { $rates = Mage::getResourceModel('australia/shipping_carrier_eparcel_collection'); $response = array( array( 'Country', 'Region/State', 'Postcodes', 'Weight from', 'Weight to', 'Parcel Cost', 'Cost Per Kg', 'Delivery Type', 'Charge Code Individual', 'Charge Code Business' ) ); foreach ($rates as $rate) { $countryId = $rate->getData('dest_country_id'); $countryCode = Mage::getModel('directory/country')->load($countryId)->getIso3Code(); $regionId = $rate->getData('dest_region_id'); $regionCode = Mage::getModel('directory/region')->load($regionId)->getCode(); $response[] = array( $countryCode, $regionCode, $rate->getData('dest_zip'), $rate->getData('condition_from_value'), $rate->getData('condition_to_value'), $rate->getData('price'), $rate->getData('price_per_kg'), $rate->getData('delivery_type'), $rate->getData('charge_code_individual'), $rate->getData('charge_code_business') ); } $csv = new Varien_File_Csv(); $temp = tmpfile(); foreach ($response as $responseRow) { $csv->fputcsv($temp, $responseRow); } rewind($temp); $contents = stream_get_contents($temp); $this->_prepareDownloadResponse('tablerates.csv', $contents); fclose($temp); }
Export the eParcel table rates as a CSV file.
entailment
public function validateAction() { // Check for a valid POST request if (!$this->getRequest()->isPost()) { // Return a "405 Method Not Allowed" response $this->getResponse()->setHttpResponseCode(405); return; } $data = $this->getRequest()->getPost(); // Check that all of the required fields are present if (empty($data) || !isset($data['country_id'], $data['region_id'], $data['street'], $data['city'], $data['postcode'])) { // Return a "400 Bad Request" response $this->getResponse()->setHttpResponseCode(400); return; } $country = Mage::getModel('directory/country')->load($data['country_id'])->getName(); $region = Mage::getModel('directory/region')->load($data['region_id'])->getCode(); $result = Mage::helper('australia/address')->validate( $data['street'], $region, $data['city'], $data['postcode'], $country ); $this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result)); }
Sends a request to the address validation backend to validate the address the customer provided on the checkout page.
entailment
public function collectRates(Mage_Shipping_Model_Rate_Request $request) { // Check if this method is active if (!$this->getConfigFlag('active')) { return false; } // Check if this method is even applicable (shipping from Australia) $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $request->getStore()); if ($origCountry != Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE) { return false; } if ($this->_client == null) { return false; } $fromPostcode = str_pad((int)Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()), 4, '0', STR_PAD_LEFT); $toPostcode = str_pad((int)$request->getDestPostcode(), 4, '0', STR_PAD_LEFT); $destCountry = $request->getDestCountryId(); if (!$destCountry) { $destCountry = Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE; } /** @var Fontis_Australia_Helper_Australiapost $helper */ $helper = Mage::helper('australia/australiapost'); $weight = (float) $request->getPackageWeight(); $length = (int)$helper->getAttribute($request, 'length'); $width = (int)$helper->getAttribute($request, 'width'); $height = (int)$helper->getAttribute($request, 'height'); $extraCover = max((int)$request->getPackageValue(), self::EXTRA_COVER_LIMIT); $config = array( 'from_postcode' => $fromPostcode, 'to_postcode' => $toPostcode, 'length' => $length, 'width' => $width, 'height' => $height, 'weight' => $weight, 'country_code' => $destCountry ); $this->_getQuotes($extraCover, $config); $_result = $this->_result->asArray(); if (empty($_result)) { return false; } return $this->_result; }
Collects the shipping rates for Australia Post from the REST API. @param Mage_Shipping_Model_Rate_Request $request @return Mage_Shipping_Model_Rate_Result|bool
entailment
protected function _isAvailableShippingMethod($name, $destCountry) { return $this->_isOptionVisibilityRequired($name, $destCountry) && !$this->_isOptionVisibilityNever($name, $destCountry); }
Determines whether a shipping method should be added to the result. @param string $name Name of the shipping method @param string $destCountry Country code @return bool
entailment
protected function _isOptionVisibilityNever($name, $destCountry) { $suboptions = $this->_getOptionVisibilities($destCountry, Fontis_Australia_Model_Shipping_Carrier_Australiapost_Source_Visibility::NEVER); foreach ($suboptions as $suboption) { if (stripos($name, $suboption) !== false) { return true; } } return false; }
Checks whether a shipping method option has the visibility "never" @param string $name Name of the shipping method @param string $destCountry Country code @return bool
entailment
protected function _isOptionVisibilityRequired($name, $destCountry) { $suboptions = $this->_getOptionVisibilities($destCountry, Fontis_Australia_Model_Shipping_Carrier_Australiapost_Source_Visibility::REQUIRED); foreach ($suboptions as $suboption) { if (stripos($name, $suboption) === false) { return false; } } return true; }
Checks whether a shipping method has the visibility "required" @param string $name Name of the shipping method @param string $destCountry Country code @return bool
entailment
protected function _getOptionVisibilities($destCountry, $visibility) { /** @var Fontis_Australia_Helper_Australiapost $helper */ $helper = Mage::helper('australia/australiapost'); $suboptions = array(); if ($helper->getPickUp() == $visibility && $destCountry != Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE) { $suboptions[] = 'pick up'; } if ($helper->getExtraCover() == $visibility) { $suboptions[] = 'extra cover'; } if ($helper->getSignatureOnDelivery() == $visibility && $destCountry == Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE) { $suboptions[] = 'signature on delivery'; } return $suboptions; }
Returns an array of shipping method options, e.g. "signature on delivery", that have a certain visibility, e.g. "never" @param string $destCountry Destination country code @param int $visibility Shipping method option visibility @return array
entailment
protected function createMethod($code, $title, $price) { /** @var Mage_Shipping_Model_Rate_Result_Method $method */ $method = Mage::getModel('shipping/rate_result_method'); $method->setCarrier($this->_code); $method->setCarrierTitle($this->getConfigData('title')); $method->setMethod($code); $method->setMethodTitle($title); $method->setPrice($this->getFinalPriceWithHandlingFee($price)); return $method; }
Simplifies creating a new shipping method. @param string $code @param string $title @param string $price @return Mage_Shipping_Model_Rate_Result_Method
entailment
public function getCode($type, $code='') { /** @var Fontis_Australia_Helper_Data $helper */ $helper = Mage::helper('australia'); $codes = array( 'services' => array( 'AUS_LETTER_EXPRESS_SMALL' => $helper->__('Express Post Small Envelope'), 'AUS_LETTER_REGULAR_LARGE' => $helper->__('Large Letter'), 'AUS_PARCEL_COURIER' => $helper->__('Courier Post'), 'AUS_PARCEL_COURIER_SATCHEL_MEDIUM' => $helper->__('Courier Post Assessed Medium Satchel'), 'AUS_PARCEL_EXPRESS' => $helper->__('Express Post'), 'AUS_PARCEL_REGULAR' => $helper->__('Parcel Post'), 'INT_PARCEL_COR_OWN_PACKAGING' => $helper->__('International Courier'), 'INT_PARCEL_EXP_OWN_PACKAGING' => $helper->__('International Express'), 'INT_PARCEL_STD_OWN_PACKAGING' => $helper->__('International Standard'), 'INT_PARCEL_AIR_OWN_PACKAGING' => $helper->__('International Economy Air'), 'INT_PARCEL_SEA_OWN_PACKAGING' => $helper->__('International Economy Sea'), ), 'extra_cover' => array( 'AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY' => $helper->__('Signature on Delivery'), 'AUS_SERVICE_OPTION_COURIER_EXTRA_COVER_SERVICE' => $helper->__('Standard cover') ) ); if (!isset($codes[$type])) { return false; } elseif (''===$code) { return $codes[$type]; } if (!isset($codes[$type][$code])) { return false; } else { return $codes[$type][$code]; } }
Returns an associative array of shipping method codes. @param string $type @param string $code @return array|bool
entailment
public function validationDefault(Validator $validator) { $validator ->integer('id') ->allowEmpty('id', 'create'); $validator ->requirePresence('ip', 'create') ->notEmpty('ip'); $validator ->requirePresence('session_id', 'create') ->notEmpty('session_id'); $validator ->allowEmpty('result'); $validator ->dateTime('used') ->allowEmpty('used'); return $validator; }
Default validation rules. @param \Cake\Validation\Validator $validator Validator instance. @return \Cake\Validation\Validator
entailment
public function touch($sessionId, $ip) { $probability = (int)Configure::read('Captcha.cleanupProbability'); $this->cleanup($probability); $captcha = $this->newEntity( [ 'session_id' => $sessionId, 'ip' => $ip, ] ); if (!$this->save($captcha)) { throw new BadMethodCallException('Sth went wrong: ' . print_r($captcha->getErrors(), true)); } return $captcha->id; }
@param string $sessionId @param string $ip @return int
entailment
public function addHistory($event) { /** @var $order Mage_Sales_Model_Order */ $order = $event->getOrder(); if ($order && $order->getPayment()) { if ($order->getPayment()->getMethod() == Fontis_Australia_Model_Payment_Directdeposit::CODE) { $order->addStatusHistoryComment('Order placed with Direct Deposit')->setIsCustomerNotified(false); } elseif ($order->getPayment()->getMethod() == Fontis_Australia_Model_Payment_Bpay::CODE) { $order->addStatusHistoryComment('Order placed with BPay')->setIsCustomerNotified(false); } } }
Adds a history entry to orders placed using AU direct deposit or BPay. @listen checkout_type_onepage_save_order @param Varien_Event_Observer $event
entailment
public function addMagentoCss($observer) { if (!Mage::helper('australia/address')->isAddressValidationEnabled()) { return; } /** @var Mage_Core_Model_Layout $layout */ $layout = Mage::getSingleton('core/layout'); /** @var Mage_Page_Block_Html_Head $head */ $head = $layout->getBlock('head'); $skinBaseDir = Mage::getDesign()->getSkinBaseDir(array('_package' => 'base', '_theme' => 'default')); $cssPath = 'prototype/windows/themes/magento.css'; if (file_exists($skinBaseDir . DS . 'lib' . DS . $cssPath)) { $head->addCss('lib' . DS . $cssPath); } else { $head->addItem('js_css', $cssPath); } }
The magento.css file is moved into the skin directory in Magento 1.7 so we need to look for it in both the new and old locations for backwards compatibility. @listen controller_action_layout_render_before_checkout_onepage_index @param Varien_Event_Observer $observer
entailment
public function validateCompletedOrderAddress(Varien_Event_Observer $observer) { /** @var Fontis_Australia_Helper_Address $helper */ $helper = Mage::helper('australia/address'); if (!$helper->isValidationOrderSaveEnabled()) { return; } try { /** @var Mage_Sales_Model_Order $order */ $order = $observer->getOrder(); if (!$order || !$order->getShippingAddress()) { return; } $helper->validateOrderAddress($order); $order->save(); } catch (Exception $err) { Mage::logException($err); } }
After order placement, validate the shipping address and store the result. @listen sales_model_service_quote_submit_success @param Varien_Event_Observer $observer
entailment
public function validateAdminOrderAddressSave(Varien_Event_Observer $observer) { /** @var Fontis_Australia_Helper_Address $helper */ $helper = Mage::helper('australia/address'); if (!$helper->isValidationOrderSaveEnabled()) { return; } /** @var Mage_Adminhtml_Model_Session $session */ $session = Mage::getSingleton('adminhtml/session'); $errors = $session->getMessages()->getErrors(); if (count($errors) > 0) { // We had an error when saving the address, so we'll skip validation $session->addWarning('Address validation has been skipped.'); return; } try { /** @var Mage_Adminhtml_Controller_Action $controller */ $controller = $observer->getControllerAction(); if (!$controller) { return; } $addressId = $controller->getRequest()->getParam('address_id'); /** @var Mage_Sales_Model_Order_Address $address */ $address = Mage::getModel('sales/order_address')->load($addressId); if ($address->getAddressType() !== Mage_Sales_Model_Order_Address::TYPE_SHIPPING) { return; } $order = $address->getOrder(); if (!$order) { return; } $ignoreValidation = $controller->getRequest()->getParam('override_validation'); if ($ignoreValidation) { $result = array( Fontis_Australia_Helper_Address::ADDRESS_OVERRIDE_FLAG => true ); $order->setAddressValidated(Fontis_Australia_Helper_Address::ADDRESS_OVERRIDE); } else { // Validate the address and store the result on the order. $result = $helper->validateOrderAddress($order); } $order->save(); // Use the result to add a message to the session telling the // admin about the validation status. $helper->addValidationMessageToSession($result, $session); } catch (Exception $err) { Mage::logException($err); } }
After a shipping address is edited, validate it and store the result. @listen controller_action_postdispatch_adminhtml_sales_order_addressSave @param Varien_Event_Observer $observer
entailment
public function exportAction() { $orders = $this->getRequest()->getPost('order_ids', array()); try { // Build the CSV and retrieve its path $filePath = Mage::getModel('australia/shipping_carrier_clickandsend_export_csv')->exportOrders($orders); // Download the file $this->_prepareDownloadResponse(basename($filePath), file_get_contents($filePath)); } catch (Exception $e) { Mage::getSingleton('core/session')->addError($e->getMessage()); $this->_redirect('adminhtml/sales_order/index'); } }
Export Orders to CSV This action exports orders to a CSV file and downloads the file. The orders to be exported depend on the HTTP POST param "order_ids".
entailment
public function addValidation(Validator $validator) { $fields = (array)$this->getConfig('dummyField'); foreach ($fields as $field) { $validator->requirePresence($field); $validator->allowEmpty($field); $validator->add($field, [ $field => [ 'rule' => function ($value, $context) { return $value === ''; }, 'last' => true ], ]); } }
@param \Cake\Validation\Validator $validator @return void
entailment
public function isValidChargeCode($chargeCode) { $isStandard = in_array($chargeCode, $this->standardChargeCodes); if ($isStandard || Mage::getStoreConfigFlag('doghouse_eparcelexport/charge_codes/allow_custom_charge_codes')) { // Charge code not found in the standard list of codes, but system config tells us this is OK // @see https://github.com/fontis/fontis_australia/issues/39 return true; } return false; }
Determines whether a given string is a valid eParcel charge code. @param string $chargeCode @return bool
entailment
public function setClient(DeliveryChoiceClient $client) { $client->getConfig()->setPath(HttpClient::CURL_OPTIONS . "/" . CURLOPT_TIMEOUT, self::HTTP_REQUEST_TIMEOUT); $this->client = $client; }
Set the Australia Post Delivery Choices client @param DeliveryChoiceClient $client
entailment
public function validateAddress(array $street, $state, $suburb, $postcode, $country) { $address = array( 'address_line_1' => strtoupper($street[0]), 'state' => strtoupper($state), 'suburb' => strtoupper($suburb), 'postcode' => strtoupper($postcode), 'country' => strtoupper($country), ); if (count($street) > 1) { $address['address_line_2'] = strtoupper($street[1]); } /** @var $helper Fontis_Australia_Helper_Data */ $helper = Mage::helper('australia'); $result = array(); try { $result = $this->client->validateAddress($address); $result = $result['ValidateAustralianAddressResponse']; $result['success'] = true; $result['original'] = $this->_getAddressString( trim($address['address_line_1'] . (isset($address['address_line_2']) ? ' ' . $address['address_line_2'] : '')), $address['suburb'], $address['state'], $address['postcode'] ); // If the address isn't valid if (!$result['ValidAustralianAddress']) { return $result; } // Unset the delivery point identifier as it isn't relevant in this context. unset($result['Address']['DeliveryPointIdentifier']); $resultAddress = $result['Address']; $result['suggestion'] = $this->_getAddressString( $resultAddress['AddressLine'], $resultAddress['SuburbOrPlaceOrLocality'], $resultAddress['StateOrTerritory'], $resultAddress['PostCode'] ); /** @var $regionModel Mage_Directory_Model_Region */ $regionModel = Mage::getModel('directory/region')->loadByCode($resultAddress['StateOrTerritory'], $resultAddress['Country']['CountryCode']); $regionId = $regionModel->getId(); $result['suggestedAddress'] = array( 'street1' => $resultAddress['AddressLine'], 'city' => $resultAddress['SuburbOrPlaceOrLocality'], 'regionId' => $regionId, 'postcode' => $resultAddress['PostCode'], ); // If we have a valid address append it to the response so the JavaScript can act accordingly. $result['validAddress'] = $this->_checkAddressValidity($result['original'], $result['suggestion']); } catch (BadResponseException $e) { $helper->logMessage("An error occurred while contacting the AusPost Delivery Choices API:\n" . $e->getMessage(), Zend_Log::ERR); $result['success'] = false; } catch (Exception $e) { Mage::logException($e); $result['success'] = false; } return $result; }
Converts the customer provided address data into an Australia Post-supported format. @param array $street Address lines @param string $state Address state @param string $suburb Address city / suburb @param string $postcode Address postcode @param string $country Address country @return array
entailment
protected function getStoreName($order) { $storeId = $order->getStoreId(); if (is_null($storeId)) { return $this->getOrder()->getStoreName(); } $store = Mage::app()->getStore($storeId); $name = array( $store->getWebsite()->getName(), $store->getGroup()->getName(), $store->getName() ); return implode(', ', $name); }
Returns the name of the website, store and store view the order was placed in. @param Mage_Sales_Model_Order $order The order to return info from @return String The name of the website, store and store view the order was placed in
entailment
protected function getTotalQtyItemsOrdered($order) { $qty = 0; $orderedItems = $order->getItemsCollection(); foreach ($orderedItems as $item) { if (!$item->isDummy()) { $qty += (int)$item->getQtyOrdered(); } } return $qty; }
Returns the total quantity of ordered items of the given order. @param Mage_Sales_Model_Order $order The order to return info from @return int The total quantity of ordered items
entailment
protected function getItemSku($item) { if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { return $item->getProductOptionByCode('simple_sku'); } return $item->getSku(); }
Returns the sku of the given item dependant on the product type. @param Mage_Sales_Model_Order_Item $item The item to return info from @return String The sku
entailment
protected function getItemOptions($item) { $options = ''; if ($orderOptions = $this->getItemOrderOptions($item)) { foreach ($orderOptions as $_option) { if (strlen($options) > 0) { $options .= ', '; } $options .= $_option['label'].': '.$_option['value']; } } return $options; }
Returns the options of the given item separated by comma(s) like this: option1: value1, option2: value2 @param Mage_Sales_Model_Order_Item $item The item to return info from @return String The item options
entailment
protected function getItemOrderOptions($item) { $result = array(); if ($options = $item->getProductOptions()) { if (isset($options['options'])) { $result = array_merge($result, $options['options']); } if (isset($options['additional_options'])) { $result = array_merge($result, $options['additional_options']); } if (!empty($options['attributes_info'])) { $result = array_merge($options['attributes_info'], $result); } } return $result; }
Returns all the product options of the given item including additional_options and attributes_info. @param Mage_Sales_Model_Order_Item $item The item to return info from @return Array The item options
entailment
protected function getItemTotal($item) { return $item->getRowTotal() - $item->getDiscountAmount() + $item->getTaxAmount() + $item->getWeeeTaxAppliedRowAmount(); }
Calculates and returns the grand total of an item including tax and excluding discount. @param Mage_Sales_Model_Order_Item $item The item to return info from @return Float The grand total
entailment
public function beforeFilter(Event $event) { $actions = $this->getConfig('actions'); if ($actions && !in_array($this->controller->request->param('action'), $actions)) { return; } $model = $this->controller->modelClass; if (!isset($this->controller->$model) || $this->controller->$model->hasBehavior('Captcha')) { return; } $this->controller->$model->addBehavior('Captcha.Captcha'); }
@param \Cake\Event\Event $event @return void
entailment
public function beforeRender(Event $event) { if (in_array('Captcha.Captcha', $this->controller->helpers) || isset($this->controller->helpers['Captcha.Captcha'])) { return; } $this->controller->helpers[] = 'Captcha.Captcha'; }
@param \Cake\Event\Event $event @return void
entailment
public function addValidation(Validator $validator) { /** @var \Captcha\Model\Table\CaptchasTable $Captchas */ $Captchas = TableRegistry::get('CaptchasValidator', ['class' => 'Captcha.Captchas']); $Captchas->setValidator(null, $validator); $Captchas->addBehavior('Captcha.Captcha'); /** @var \Captcha\Model\Behavior\CaptchaBehavior $Captchas */ $Captchas->addValidation($validator); }
@param \Cake\Validation\Validator $validator @return void
entailment
public function assignData($data) { $storeId = $this->getInfoInstance()->getQuote()->getStoreId(); $details = array(); if ($this->getAccountName()) { $details['account_name'] = $this->getAccountName($storeId); } if ($this->getAccountBSB()) { $details['account_bsb'] = $this->getAccountBSB($storeId); } if ($this->getAccountNumber()) { $details['account_number'] = $this->getAccountNumber($storeId); } if ($this->getMessage()) { $details['message'] = $this->getMessage($storeId); } if (!empty($details)) { $this->getInfoInstance()->setAdditionalData(serialize($details)); } return $this; }
Assign data to info model instance @param mixed $data @return Fontis_Australia_Model_Payment_Directdeposit
entailment
public function exportOrders($orders) { $eparcel = new Doghouse_Australia_Eparcel(); foreach ($orders as $order) { if (!($order instanceof Mage_Sales_Model_Order)) { $order = Mage::getModel('sales/order')->load($order); } if (!$order->getShippingCarrier() instanceof Fontis_Australia_Model_Shipping_Carrier_Eparcel) { throw new Fontis_Australia_Model_Shipping_Carrier_Eparcel_Export_Exception( "Order #" . $order->getIncrementId() . " doesn't use Australia Post eParcel as its carrier!" ); } $orderItems = $order->getItemsCollection(); $currentParcel = $this->getNewParcel($order); $consignmentRecord = $this->getConsignmentRecord($order,$currentParcel); foreach ($orderItems as $item) { /* Check item is valid */ if ($item->isDummy()) { continue; } /* Calculate item quantity */ $itemQuantity = $item->getData('qty_ordered') - $item->getData('qty_canceled') - $item->getData('qty_shipped'); /* Check item quantity */ if ($itemQuantity == 0) { continue; } /* * Populate Good Record * * UPDATE 2010.06.16 : Auspost support has said that we should only have ONE good record * per consignment (though their documentation says otherwise) * * @var Doghouse_Australia_Eparcel_Record_Good */ $goodRecord = new Doghouse_Australia_Eparcel_Record_Good(); $goodRecord->originCountryCode = ''; $goodRecord->hsTariffCode = ''; $goodRecord->description = substr(str_replace(',', '', $item['name']), 0, 50); // remove commas and cap at maximum length $goodRecord->productType = $this->getDefault('good/product_type'); $goodRecord->productClassification = null; $goodRecord->quantity = $itemQuantity; $goodRecord->weight = max($item['weight'], 0); $goodRecord->unitValue = max($item->getData('price') + $item->getData('tax_amount'), 0); $goodRecord->totalValue = max($goodRecord->unitValue * $goodRecord->quantity, 0); /* We have at least one Good, time to add the consignmentRecord if not done yet */ if (! $consignmentRecord->isAddedToEparcel()) { $eparcel->addRecord($consignmentRecord); } /* If current parcel can't fit extra item, close it, and open new parcel */ if (! $currentParcel->canAddGood($goodRecord)) { $this->closeParcel($eparcel, $currentParcel); $currentParcel = $this->getNewParcel($order); } /* Add item to Parcel */ $currentParcel->addGood($goodRecord); } $this->closeParcel($eparcel, $currentParcel); } if (self::DEBUG) { throw new Fontis_Australia_Model_Shipping_Carrier_Eparcel_Export_Exception( nl2br($this->log()) ); } /* Save file */ $fileName = 'order_export_'.date("Ymd_His").'_eparcel.csv'; $filePath = Mage::getBaseDir('export').'/'.$fileName; if ($eparcel->makeCsv($filePath)) { return $filePath; } throw new Fontis_Australia_Model_Shipping_Carrier_Eparcel_Export_Exception( "Unable to build .CSV file!" ); }
Implementation of abstract method to export given orders to csv file in var/export. @param int[]|Mage_Sales_Model_Order[] $orders List of orders of type Mage_Sales_Model_Order or order IDs to export. @return string The name of the written csv file in var/export @throws Fontis_Australia_Model_Shipping_Carrier_Eparcel_Export_Exception
entailment
public function initialize(array $config = []) { $config += (array)Configure::read('Captcha'); parent::initialize($config); $engine = $this->getConfig('engine'); $this->_engine = new $engine($this->getConfig()); $this->_captchasTable = TableRegistry::get('Captcha.Captchas'); }
Behavior configuration @param array $config @return void
entailment
public function addValidation(Validator $validator) { $validator->requirePresence('captcha_result'); $validator->add('captcha_result', [ 'required' => [ 'rule' => 'notBlank', 'last' => true ], ]); /** @deprecated Use PassiveCaptcha Behavior */ if ($this->getConfig('dummyField')) { $validator->requirePresence($this->getConfig('dummyField')); $validator->allowEmpty($this->getConfig('dummyField')); $validator->add($this->getConfig('dummyField'), [ 'dummyField' => [ 'rule' => function ($value, $context) { return $value === ''; }, 'last' => true ], ]); } $this->_engine->buildValidator($validator); if ($this->getConfig('minTime')) { $validator->add('captcha_result', [ 'minTime' => [ 'rule' => 'validateCaptchaMinTime', 'provider' => 'table', 'message' => __('You were too fast'), 'last' => true ], ]); } if ($this->getConfig('maxTime')) { $validator->add('captcha_result', [ 'maxTime' => [ 'rule' => 'validateCaptchaMaxTime', 'provider' => 'table', 'message' => __('You were too slow'), 'last' => true ], ]); } }
@param \Cake\Validation\Validator $validator @return void
entailment
public function validateCaptchaMinTime($value, $context) { $captcha = $this->_getCaptcha($context['data']); if (!$captcha) { return false; } if ($captcha->created >= new Time('- ' . $this->getConfig('minTime') . ' seconds')) { return false; } return true; }
@param string $value @param array $context @return bool
entailment
public function validateCaptchaResult($value, $context) { $captcha = $this->_getCaptcha($context['data']); if (!$captcha) { return false; } if ((string)$value !== $captcha->result) { return false; } $this->_captchasTable->markUsed($captcha); return true; }
@param string $value @param array $context @return bool
entailment
protected function _getCaptcha(array $data) { $id = !empty($data['captcha_id']) ? (int)$data['captcha_id'] : null; if (array_key_exists($id, $this->_captchas)) { return $this->_captchas[$id]; } $request = Router::getRequest(); if (!$request->getSession()->started()) { $request->getSession()->start(); } $sessionId = $request->getSession()->id(); if (!$sessionId && PHP_SAPI === 'cli') { $sessionId = 'test'; } $ip = $request->clientIp(); if (!$id) { $this->_captchas[$id] = null; return null; } $conditions = [ 'id' => $id, 'ip' => $ip, 'session_id' => $sessionId ]; $this->_captchas[$id] = $this->_captchasTable->find()->where($conditions)->first(); return $this->_captchas[$id]; }
@param array $data @return \Captcha\Model\Entity\Captcha|null
entailment
protected function _convertAdditionalData() { $details = @unserialize($this->getInfo()->getAdditionalData()); if (is_array($details)) { $this->_billerCode = isset($details['biller_code']) ? (string) $details['biller_code'] : ''; $this->_ref = isset($details['ref']) ? (string) $details['ref'] : ''; } else { $this->_billerCode = ''; $this->_ref = ''; } return $this; }
Gets any additional data saved by the BPAY payment module. @return Fontis_Australia_Block_Bpay_Info
entailment
public function toOptionArray() { $helper = Mage::helper('australia'); return array( array('value' => self::REQUIRED, 'label' => $helper->__('Required')), array('value' => self::OPTIONAL, 'label' => $helper->__('Optional')), array('value' => self::NEVER, 'label' => $helper->__('Never')), ); }
Options getter @return array
entailment
public function toArray() { $helper = Mage::helper('australia'); return array( self::NEVER => $helper->__('Never'), self::OPTIONAL => $helper->__('Optional'), self::REQUIRED => $helper->__('Required'), ); }
Get options in "key-value" format @return array
entailment
public function control(array $options = []) { $options += [ 'label' => ['escape' => false, 'text' => $this->image()], 'escapeLabel' => false, 'autocomplete' => 'off', ]; return $this->Form->control('captcha_result', $options); }
@param array $options @return string
entailment
public function render(array $options = []) { $id = $this->_getId(); $html = $this->control($options); $html .= $this->Form->control('captcha_id', ['type' => 'hidden', 'value' => $id]); $html .= $this->passive(); return $html; }
@param array $options @return string
entailment
public function passive($field = null) { if (!$field) { $field = $this->getConfig('dummyField') ?: 'email_homepage'; } $dummyFields = (array)$field; $html = []; foreach ($dummyFields as $dummyField) { $html[] = '<div style="display: none">' . $this->Form->control($dummyField, ['value' => '']) . '</div>'; } return implode(PHP_EOL, $html); }
Add a honey pot trap field. Requires corresponding validation to be activated. If you pass null, it will use the configured default field name. @param string|array|null $field @return string
entailment
protected function _convertAdditionalData() { $details = @unserialize($this->getInfo()->getAdditionalData()); if (is_array($details)) { $this->_accountName = isset($details['account_name']) ? (string) $details['account_name'] : ''; $this->_accountBSB = isset($details['account_bsb']) ? (string) $details['account_bsb'] : ''; $this->_accountNumber = isset($details['account_number']) ? (string) $details['account_number'] : ''; $this->_message = isset($details['message']) ? (string) $details['message'] : ''; } else { $this->_accountName = ''; $this->_accountBSB = ''; $this->_accountNumber = ''; $this->_message = ''; } return $this; }
Converts serialised additional data into a more usable form. @return Fontis_Australia_Block_Directdeposit_Info
entailment
public function display($id = null) { $captcha = $this->Captchas->get($id); $captcha = $this->Preparer->prepare($captcha); $this->set(compact('captcha')); $this->viewBuilder()->setClassName('Captcha.Captcha'); }
Displays a captcha image @param int|null $id @return \Cake\Http\Response|void
entailment
public function validate() { $order = $this->getInfoInstance()->getOrder(); if ($order) { // Force to generate REF from Order ID. $this->assignData(null); } return parent::validate(); }
Validate. This is just a little hack in order to generate REF from Order ID after Order is created.
entailment
public function assignData($data) { $billerCode = $this->getBillerCode(); $ref = $this->getRef(); $info = $this->getInfoInstance(); $info->setBillerCode($billerCode); $info->setRef($ref); $details = array(); if ($this->getBillerCode()) { $details['biller_code'] = $billerCode; if ($this->getRef()) { $details['ref'] = $ref; } } if (!empty($details)) { $this->getInfoInstance()->setAdditionalData(serialize($details)); } return $this; }
Assign data to info model instance @param mixed $data @return Fontis_Australia_Model_Payment_Bpay
entailment
protected function _calculateRefMod10v5($number) { $number = preg_replace("/\D/", "", $number); // The seed number needs to be numeric if (!is_numeric($number)) { return false; } // Must be a positive number if ($number <= 0) { return false; } // Get the length of the seed number $length = strlen($number); $total = 0; // For each character in seed number, sum the character multiplied by its one // based array position (instead of normal PHP zero based numbering) for ($i = 0; $i < $length; $i++) { $total += $number{$i} * ($i + 1); } // The check digit is the result of the sum total from above mod 10 $checkDigit = fmod($total, 10); // Return the original seed plus the check digit return $number . $checkDigit; }
Calculate Modulus 10 Version 5. http://stackoverflow.com/a/11605561/747834 @param integer $number @return integer
entailment
private function getArticleType(Mage_Sales_Model_Order $order) { if ($order->getShippingAddress()->getCountry() == Fontis_Australia_Helper_Data::AUSTRALIA_COUNTRY_CODE) { return 7; } else { $shippingMethod = $this->getShippingConfiguration($order); if (isset($shippingMethod[4]) && $shippingMethod[4] == 'D') { return 1; } return 2; } }
Article type can be documents (1), merchandise (2) or own packaging (7) @param Mage_Sales_Model_Order $order @return int
entailment
public function addExportToBulkAction($observer) { $block = $observer->getBlock(); if ( $block instanceof Mage_Adminhtml_Block_Sales_Order_Grid && Mage::helper('australia/clickandsend')->isClickAndSendEnabled() ) { $block->getMassactionBlock()->addItem('clickandsendexport', array( 'label' => $block->__('Export to CSV (Click & Send)'), 'url' => $block->getUrl('*/australia_clickandsend/export') )); } }
Event observer. Triggered before an adminhtml widget template is rendered. We use this to add our action to bulk actions in the sales order grid instead of overriding the class. @param $observer
entailment
public function getAllSimpleItems($order) { $items = array(); foreach ($order->getAllItems() as $item) { if ($item->getProductType() == 'simple') { $items[] = $item; } } return $items; }
Get all the simple items in an order. @param Mage_Shipping_Model_Rate_Request|Mage_Sales_Model_Order $order Order to retrieve items for @return array List of simple products from order
entailment