sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function requestComparisonStrategy(): ComparisonStrategy { if ($this->comparisonStrategy !== null) { return $this->comparisonStrategy; } $selectedQueryPoints = array_merge($this->queryModel->getNamedSelectQueryPoints(), $this->queryModel->getUnnamedSelectQueryPoints()); if (1 != count($selectedQueryPoints)) { throw new CriteriaConflictException('Subselect not comparable.'); } $comparisonStrategy = current($selectedQueryPoints)->requestComparisonStrategy(); CastUtils::assertTrue($comparisonStrategy instanceof ComparisonStrategy); if ($comparisonStrategy->getType() != ComparisonStrategy::TYPE_COLUMN) { throw new CriteriaConflictException(); } $columnComparable = $comparisonStrategy->getColumnComparable(); $this->queryModel->getQueryItemSelect()->selectQueryItem($columnComparable ->buildQueryItem(CriteriaComparator::OPERATOR_EQUAL)); $selectBuilder = $this->queryState->getPdo()->getMetaData()->createSelectStatementBuilder(); $this->queryModel->apply($selectBuilder); return $this->comparisonStrategy = new ComparisonStrategy(new CriteriaColumnComparable( $selectBuilder->toQueryResult(), $columnComparable)); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\QueryPoint::requestComparisonStrategy()
entailment
public function requestRepresentableQueryItem(): QueryItem { $selectBuilder = $this->queryState->getPdo()->getMetaData()->createSelectStatementBuilder(); $this->queryModel->apply($selectBuilder); return $selectBuilder->toQueryResult(); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\QueryPoint::requestRepresentableQueryItem()
entailment
public function determineEntityModel() { // if ($this->value === null) return null; if (isset($this->discriminatedEntityModels[$this->value])) { return $this->discriminatedEntityModels[$this->value]; } throw new CorruptedDataException('Unknown discriminator value \'' . TypeUtils::buildScalar($this->value) . '\'. Following allowed: ' . implode(', ', array_keys($this->discriminatedEntityModels))); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\from\meta\DiscriminatorSelection::determineEntityModel()
entailment
public function createValueBuilder() { if (null !== ($entityModel = $this->determineEntityModel())) { return new EagerValueBuilder($entityModel->getClass()); } return new EagerValueBuilder(null); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::createValueBuilder()
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $dryRun = $input->getOption('dry-run'); $force = $input->getOption('force'); $dumper = new Dumper(); $file = sprintf('%s/../Resources/config/mime.yml', __DIR__); $result = array(); if (false !== $content = file_get_contents(self::MIME_FILE)) { foreach (explode("\n", $content) as $line) { if (false == preg_match('/^#/', $line) && strlen(trim($line)) > 0) { $data = preg_split('/\s+/', $line); for ($i = 1; $i <= count($data) - 1; $i++) { $result[$data[$i]] = $data[0]; } } } } else { throw new \RuntimeException(sprintf('could not open file: %s', self::MIME_FILE)); } $ymlDump = $dumper->dump($result, 2); if ((false === file_exists($file) || $force) && !$dryRun) { if (false === file_put_contents($file, $ymlDump)) { throw new \RuntimeException(sprintf('could not write to file: %s', $file)); } else { $output->writeln(sprintf('Successful writing file: <info>%s</info>', realpath($file))); } } elseif (file_exists($file) && !$dryRun) { $output->writeln('Mime file exists, use force options to overwrite'); } elseif ($dryRun) { echo $ymlDump; } }
Execute @param InputInterface $input @param OutputInterface $output
entailment
public function clearThumbnailAction(Request $request) { $path = $request->get('path'); $filter = $request->get('filter'); $response = [ 'error' => false, 'success' => false ]; if ($path && $filter) { /** @var CacheManager $cacheManager */ $cacheManager = $this->get('liip_imagine.cache.manager'); // Filter is purposely left out on the remove call, it should remove all the caches for the current given file. $cacheManager->remove($path); $cacheManager->getBrowserPath($path, $filter); $response['success'] = true; $response['url'] = $cacheManager->generateUrl($path, $filter); } else { $response['error'] = 'No "path" or "filter" provided'; } return new JsonResponse($response); }
Remove thumbnail for given path @param Request $request @return JsonResponse @Route("/clear-thumbnail")
entailment
public function setOptions($options) { parent::setOptions($options); if (isset($options['fetch_url'])) { $this->setFetchUrl($options['fetch_url']); } if (isset($options['preview_url'])) { $this->setPreviewUrl($options['preview_url']); } return $this; }
Set options. Accepted options are: @param array|\Traversable $options @return $this
entailment
public function arg( $index ) { return isset($this->arguments[$index]) ? $this->arguments[$index] : null; }
Returns the n'th command-line argument. `arg(0)` is the first remaining argument after flags have been processed. @param int $index @return string
entailment
public function shorts() { $out = array(); foreach( $this->definedShortFlags as $key => $data ) { $out[$key] = $data[self::DEF_VALUE]; } return $out; }
Returns an array of short-flag call-counts indexed by character `-v` would set the 'v' index to 1, whereas `-vvv` will set the 'v' index to 3 @return array
entailment
public function longs() { $out = array(); foreach( $this->definedFlags as $key => $data ) { $out[$key] = $data[self::DEF_VALUE]; } return $out; }
Returns an array of long-flag values indexed by flag name @return array
entailment
public function &short( $letter, $usage = '' ) { $this->definedShortFlags[$letter[0]] = array( self::DEF_VALUE => 0, self::DEF_USAGE => $usage, ); return $this->definedShortFlags[$letter[0]]['value']; }
Defines a short-flag of specified name, and usage string. The return value is a reference to an integer variable that stores the number of times the short-flag was called. This means the value of the reference for v would be the following. -v => 1 -vvv => 3 @param string $letter The character of the short-flag to define @param string $usage The usage description @return int
entailment
public function &bool( $name, $value = null, $usage = '' ) { return $this->_storeFlag(self::TYPE_BOOL, $name, $value, $usage); }
Defines a bool long-flag of specified name, default value, and usage string. The return value is a reference to a variable that stores the value of the flag. Examples: Truth-y: --mybool=[true|t|1] --mybool [true|t|1] --mybool False-y: --mybool=[false|f|0] --mybool [false|f|0] [not calling --mybool and having the default false] @param string $name The name of the long-flag to define @param mixed $value The default value - usually false for bool - which if null marks the flag required @param string $usage The usage description @return mixed A reference to the flags value
entailment
public function &float( $name, $value = null, $usage = '' ) { return $this->_storeFlag(self::TYPE_FLOAT, $name, $value, $usage); }
Defines a float long-flag of specified name, default value, and usage string. The return value is a reference to a variable that stores the value of the flag. Examples: --myfloat=1.1 --myfloat 1.1 @param string $name The name of the long-flag to define @param mixed $value The default value which if null marks the flag required @param string $usage The usage description @return mixed A reference to the flags value
entailment
public function &int( $name, $value = null, $usage = '' ) { return $this->_storeFlag(self::TYPE_INT, $name, $value, $usage); }
Defines an integer long-flag of specified name, default value, and usage string. The return value is a reference to a variable that stores the value of the flag. Note: Float values trigger an error, rather than casting. Examples: --myinteger=1 --myinteger 1 @param string $name The name of the long-flag to define @param mixed $value The default value which if null marks the flag required @param string $usage The usage description @return mixed A reference to the flags value
entailment
public function &uint( $name, $value = null, $usage = '' ) { return $this->_storeFlag(self::TYPE_UINT, $name, $value, $usage); }
Defines a unsigned integer long-flag of specified name, default value, and usage string. The return value is a reference to a variable that stores the value of the flag. Note: Negative values trigger an error, rather than casting. Examples: --myinteger=1 --myinteger 1 @param string $name The name of the long-flag to define @param mixed $value The default value which if null marks the flag required @param string $usage The usage description @return mixed A reference to the flags value
entailment
public function &string( $name, $value = null, $usage = '' ) { return $this->_storeFlag(self::TYPE_STRING, $name, $value, $usage); }
Defines a string long-flag of specified name, default value, and usage string. The return value is a reference to a variable that stores the value of the flag. Examples --mystring=vermouth --mystring="blind jazz singers" --mystring vermouth --mystring "blind jazz singers" @param string $name The name of the long-flag to define @param mixed $value The default value which if null marks the flag required @param string $usage The usage description @return mixed A reference to the flags value
entailment
public function getDefaults() { $output = ''; $final = array(); $max = 0; foreach( $this->definedShortFlags as $char => $data ) { $final["-{$char}"] = $data[self::DEF_USAGE]; } foreach( $this->definedFlags as $flag => $data ) { $key = "--{$flag}"; $final[$key] = ($data[self::DEF_REQUIRED] ? "<{$data[self::DEF_TYPE]}> " : ($data[self::DEF_TYPE] == self::TYPE_BOOL ? '' : "[{$data[self::DEF_TYPE]}] " )) . $data[self::DEF_USAGE]; $max = max($max, strlen($key)); } foreach( $final as $flag => $usage ) { $output .= sprintf('%' . ($max + 5) . 's', $flag) . " {$usage}" . PHP_EOL; } return $output; }
Returns the default values of all defined command-line flags as a formatted string. Example: -v Output in verbose mode --testsuite [string] Which test suite to run. --bootstrap [string] A "bootstrap" PHP file that is run before the specs. --help Display this help message. --version Display this applications version. @return string
entailment
public function parse( array $args = null, $ignoreExceptions = false, $skipFirstArgument = true ) { if( $args === null ) { $args = $GLOBALS['argv']; } if( $skipFirstArgument ) { array_shift($args); } list($longParams, $shortParams, $this->arguments) = $this->splitArguments($args, $this->definedFlags); foreach( $longParams as $name => $value ) { if( !isset($this->definedFlags[$name]) ) { if( !$ignoreExceptions ) { throw new InvalidFlagParamException('Unknown option: --' . $name); } } else { $defined_flag =& $this->definedFlags[$name]; if( $this->validateType($defined_flag[self::DEF_TYPE], $value) ) { $defined_flag[self::DEF_VALUE] = $value; $defined_flag[self::DEF_PARSED] = true; } else { if( !$ignoreExceptions ) { throw new InvalidFlagTypeException('Option --' . $name . ' expected type: "' . $defined_flag[self::DEF_TYPE] . '"'); } } } } foreach( $shortParams as $char => $value ) { if( !isset($this->definedShortFlags[$char]) ) { if( !$ignoreExceptions ) { throw new InvalidFlagParamException('Unknown option: -' . $char); } } else { $this->definedShortFlags[$char][self::DEF_VALUE] = $value; } } foreach( $this->definedFlags as $name => $data ) { if( $data[self::DEF_VALUE] === null ) { if( !$ignoreExceptions ) { throw new MissingFlagParamException('Expected option --' . $name . ' missing.'); } } } $this->parsed = true; }
Parses flag definitions from the argument list, which should include the command name. Must be called after all flags are defined and before flags are accessed by the program. Will throw exceptions on Missing Require Flags, Unknown Flags or Incorrect Flag Types @param array $args The arguments to parse, defaults to $GLOBALS['argv'] @param bool $ignoreExceptions Setting to true causes parsing to continue even after an exception has been thrown. @param bool $skipFirstArgument Setting to false causes the first argument to be parsed as an parameter rather than the command. @throws Exceptions\MissingFlagParamException @throws Exceptions\InvalidFlagParamException @throws Exceptions\InvalidFlagTypeException
entailment
protected function configureForm($form, AbstractOptions $options) { /* @var $options \Applications\Options\ModuleOptions */ $form->get($this->fileName)->setViewHelper('formImageUpload') ->setMaxSize($options->getContactImageMaxSize()) ->setAllowedTypes($options->getContactImageMimeType()) ->setForm($form); }
Configure the file upload formular with Applications/Options @param Form $form @param AbstractOptions $options
entailment
public function getOrCreatePersistAction($entity) { $this->removeActionPool->removeAction($entity); return $this->persistActionPool->getOrCreateAction($entity); }
/* (non-PHPdoc) @see \n2n\persistence\orm\store\action\ActionQueue::getOrCreatePersistAction()
entailment
public function getOrCreateRemoveAction($entity) { $this->persistActionPool->removeAction($entity); return $this->removeActionPool->getOrCreateAction($entity); }
/* (non-PHPdoc) @see \n2n\persistence\orm\store\action\ActionQueue::getOrCreateRemoveAction()
entailment
public function isValid($value) { if ($value == $this->allowName) { return true; } foreach ($this->getUser()->getGroups() as $group) { if ($group->getName() == $value) { $this->error(self::MSG_NOT_UNIQUE, $value); return false; } } return true; }
Returns true, if the given value is unique among the groups of the user. Also returns true, if the given value equals the {@link $allowName}. @param string $value @return bool @see \Zend\Validator\ValidatorInterface::isValid()
entailment
public function prepare(File $file, $entity, $field, $noclobber = true, $forceFilename = '') { $dir = $this->getDir($entity, $field); if ($forceFilename) { $pathname = $dir . '/' . $forceFilename; } else { if ($file instanceof UploadedFile) { $fileName = $file->getClientOriginalName(); } else { $fileName = $file->getBasename(); } $i = 0; do { $f = $this->namingStrategy->normalize($fileName, $i++); $pathname = $dir . '/' . $f; } while ($noclobber && $this->fs->exists($pathname)); $this->fs->mkdir(dirname($pathname), 0777 & ~umask(), true); $this->fs->touch($pathname); } $this->preparedPaths[]= $pathname; return $pathname; }
Prepares a file for upload, which means that a stub file is created at the point where the file otherwise would be uploaded. @param File $file @param mixed $entity @param string $field @param bool $noclobber @param string $forceFilename @return string
entailment
public function save(File $file, $preparedPath) { if (false === ($i = array_search($preparedPath, $this->preparedPaths))) { throw new \RuntimeException("{$preparedPath} is not prepared by the filemanager"); } unset($this->preparedPaths[$i]); $existed = $this->fs->exists($preparedPath); @$this->fs->remove($preparedPath); try { $this->dispatchEvent($existed ? ResourceEvent::REPLACED : ResourceEvent::CREATED, $preparedPath); $file->move(dirname($preparedPath), basename($preparedPath)); } catch (FileException $fileException) { throw new FileException( $fileException->getMessage() . "\n(hint: check the 'upload_max_filesize' in php.ini)", 0, $fileException ); } }
Save a file to a previously prepared path. @param \Symfony\Component\HttpFoundation\File\File $file @param string $preparedPath @return void @throws \RuntimeException
entailment
public function delete($filePath) { $relativePath = $this->fs->makePathRelative($filePath, $this->root); if (preg_match('!(^|/)\.\.!', $relativePath)) { throw new \RuntimeException("{$relativePath} does not seem to be managed by the filemanager"); } if ($this->fs->exists($filePath)) { $this->fs->remove($filePath); $this->dispatchEvent(ResourceEvent::DELETED, $filePath); return true; } return false; }
Delete a file path @param string $filePath @return bool
entailment
public function proposeFilename(File $file, $suffix) { if ($file instanceof UploadedFile) { $fileName = $file->getClientOriginalName(); } else { $fileName = $file->getBasename(); } $ret = preg_replace('/[^\w.]+/', '-', strtolower($fileName)); $ret = preg_replace('/-+/', '-', $ret); if ($suffix) { $ext = (string)pathinfo($ret, PATHINFO_EXTENSION); $fn = (string)pathinfo($ret, PATHINFO_FILENAME); $ret = sprintf('%s-%d.%s', trim($fn, '.'), $suffix, $ext); } return $ret; }
Propose a file name based on the uploaded file name. @param File $file @param string $suffix @return mixed|string
entailment
public function getRelativePath($entity, $field) { if (is_object($entity)) { $entity = get_class($entity); } $entity = strtolower(Str::classname($entity)); return $entity . '/' . $field; }
Returns the relative path for the specified entity / field combination. By default, the entity's local class name is lowercased and the field is used as-is. @param mixed $entity @param string $field @return string
entailment
public function getFileUrl($entity, $field, $fileName = null) { if (func_num_args() < 3) { if ($entity) { $fileName = PropertyHelper::getValue($entity, $field); } } if ($fileName instanceof File) { $fileName = $fileName->getBasename(); } if ($fileName) { return ltrim($this->httpRoot . '/' . $this->getRelativePath($entity, $field) . '/' . $fileName, '/'); } return null; }
Return the url to the file. @param mixed $entity @param string $field @param mixed $fileName @return null|string
entailment
public function getFilePath($entity, $field, $fileName = null) { if (func_num_args() < 3) { if (is_object($entity)) { $fileName = PropertyHelper::getValue($entity, $field); } } if ($fileName instanceof File) { $fileName = $fileName->getBasename(); } if ($fileName) { return $this->getDir($entity, $field) . '/' . $fileName; } return null; }
Returns the file path for the given entity / property combination @param mixed $entity @param string $field @param null $fileName @return null|string
entailment
private function dispatchEvent($eventType, $filePath) { if (null !== $this->eventDispatcher) { $relativePath = $this->fs->makePathRelative(dirname($filePath), $this->root) . basename($filePath); $this->eventDispatcher->dispatch( $eventType, new ResourceEvent($relativePath, $this->httpRoot, $this->root) ); if (null !== $this->imagineConfig) { if (false !== strpos($relativePath, '/../') || 0 === strpos($relativePath, '../')) { // outside web root, stop. return; } // Create events for the imagine cache as well. /** @var CacheManager $cacheManager */ /** @var FilterConfiguration $filterConfig */ list ($cacheManager, $filterConfig) = $this->imagineConfig; $webPath = $this->httpRoot . '/' . $relativePath; $cacheManager->remove($webPath); foreach ($filterConfig->all() as $name => $filter) { $url = $cacheManager->resolve($webPath, $name); // this weird construct is here because the imagine cache manager generates absolute urls // even though they're local for some unapparent reason. $relativeUrl = parse_url($url, PHP_URL_PATH); $url = $this->fs->makePathRelative(dirname($relativeUrl), $this->httpRoot) . basename($relativeUrl); if (false === strpos($url, '../')) { $this->eventDispatcher->dispatch( $eventType, new ResourceEvent($url, $this->httpRoot, $this->root) ); } } } } }
Dispatch an event for changed resources @param string $eventType @param string $filePath
entailment
public function isListed($institution) { /** @var RaListing $raListing */ foreach ($this->getElements() as $raListing) { if ($raListing->institution === $institution) { return true; } } return false; }
Checks if a certain institution is listed in the RA listing @param $institution @return bool
entailment
public static function setValue($entity, $field, $value) { $entity->{'set' . ucfirst(Str::camel($field))}($value); }
Calls a setter in the entity with the specified value @param object $entity @param string $field @param mixed $value @return void
entailment
public function getManagedFields($entity) { $class = get_class($entity); if (!isset($this->managedFields[$class])) { $entityClass = get_class($entity); $this->managedFields[$class] = array(); do { $metadata = $this->metadataFactory->getMetadataForClass($entityClass); foreach ($metadata->propertyMetadata as $field => $metadata) { if (isset($metadata->fileManager)) { $this->managedFields[$class][] =$field; } } } while ($entityClass = get_parent_class($entityClass)); $this->managedFields[$class] = array_unique($this->managedFields[$class]); } return $this->managedFields[$class]; }
Returns all field names that are managed @param mixed $entity @return array
entailment
public function determineEntityModel() { $identifiedEntityModel = null; foreach ($this->entityModels as $key => $entityModel) { if (!isset($this->values[$key])) continue; $identifiedEntityModel = $entityModel; } return $identifiedEntityModel; }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\from\meta\DiscriminatorSelection::determineEntityModel()
entailment
public function bindColumns(PdoStatement $stmt, array $columnAliases) { foreach ($columnAliases as $key => $columnAlias) { $this->values[$key] = null; $stmt->shareBindColumn($columnAlias, $this->values[$key]); } }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::bindColumns()
entailment
public function preUpdate($eventArgs) { $entity = $eventArgs->getEntity(); $changeset = $eventArgs->getEntityChangeSet(); foreach ($this->metadata->getManagedFields($entity) as $field) { if (isset($changeset[$field])) { list($old, $new) = $changeset[$field]; if ($old) { $tempFilePath = $this->fileManager->getFilePath($entity, $field, $old); if ($new && ((string)$new) && (string)$new == $tempFilePath) { /** @var File $new */ // in this case the file was wrapped in a file object, but not actually changed. // We "unwrap" the value here. $new = $new->getBasename(); } else { $filepath = $this->fileManager->getFilePath($entity, $field, $old); $this->unitOfWork[spl_object_hash($entity)][$field]['delete'] = function (FileManager $fm) use ($filepath) { $fm->delete($filepath); }; } } if (is_string($new)) { $eventArgs->setNewValue($field, $new); } else { if (null !== $new) { $eventArgs->setNewValue($field, $this->scheduleForUpload($new, $entity, $field)); } } } } }
Replaces a file value and removes the old file. @param PreUpdateEventArgs $eventArgs @return void
entailment
public function preRemove($eventArgs) { $entity = $eventArgs->getEntity(); foreach ($this->metadata->getManagedFields($entity) as $field) { $file = PropertyHelper::getValue($entity, $field); if ($file) { $filepath = $this->fileManager->getFilePath($entity, $field, $file); $this->unitOfWork[spl_object_hash($entity)][$field]['delete'] = function (FileManager $fm) use ($filepath) { $fm->delete($filepath); }; } } }
Removes the files attached to the entity @param LifeCycleEventArgs $eventArgs @return void
entailment
public function prePersist($eventArgs) { $entity = $eventArgs->getEntity(); foreach ($this->metadata->getManagedFields($entity) as $field) { $value = PropertyHelper::getValue($entity, $field); if (null !== $value) { $this->scheduleForUpload($value, $entity, $field); } } }
Saves the file(s) to disk @param LifecycleEventArgs $eventArgs @return void
entailment
public function scheduleForUpload($value, $entity, $field) { if (is_string($value)) { // try to locate the file on disk $value = new FixtureFile($this->fileManager->getFilePath($entity, $field, $value)); } if ($value instanceof File) { $replaceFile = isset($value->metaData['keep_previous_filename']) and $value->metaData['keep_previous_filename']; $path = $this->fileManager->prepare($value, $entity, $field, !$replaceFile); $fileName = basename($path); PropertyHelper::setValue($entity, $field, $fileName); $this->unitOfWork[spl_object_hash($entity)][$field]['save'] = function ($fm) use ($value, $path) { $fm->save($value, $path); }; return $fileName; } else { throw new \InvalidArgumentException("Invalid argument to scheduleForUpload(): " . gettype($value)); } }
Puts the upload in the unit of work to be executed when the flush is done. @param mixed $value @param mixed $entity @param string $field @return string @throws \InvalidArgumentException
entailment
public function doFlush() { while ($unit = array_shift($this->unitOfWork)) { while ($operations = array_shift($unit)) { while ($callback = array_shift($operations)) { call_user_func($callback, $this->fileManager); } } } }
Executes all scheduled callbacks in the unit of work. @return void
entailment
public function init() { $this->setName('users'); $this->setLabel('Users'); $this->setAttribute('id', 'users'); $this->setTargetElement( array( 'type' => 'hidden', 'name' => 'user', ) ); $this->setCount(0) ->setAllowRemove(true) ->setAllowAdd(true) ->setShouldCreateTemplate(true); }
Initialises the collection. @see \Zend\Form\Element::init()
entailment
public function getInputFilterSpecification() { $spec = array(); foreach ($this->getElements() as $element) { $name = (string) $element->getName(); $spec[$name] = array( 'name' => $name, ); } return $spec; }
{@inheritDoc} @see \Zend\InputFilter\InputFilterProviderInterface::getInputFilterSpecification()
entailment
public function getFileUrls($entities, $field) { $urls = array(); foreach ($entities as $entity) { $urls [] = $this->fm->getFileUrl($entity, $field); } return $urls; }
Returns a list of file urls for the specified entity/field combination. @param mixed[] $entities @param string $field @return string|null
entailment
public function normalize($fileName, $suffix = 0) { if ($this->casePreservation === self::LOWER_CASE) { $fileName = strtolower($fileName); } if ($suffix !== 0) { $ext = (string)pathinfo($fileName, PATHINFO_EXTENSION); $fn = (string)pathinfo($fileName, PATHINFO_FILENAME); $fileName = sprintf('%s-%d.%s', trim($fn, '.'), $suffix, $ext); } return $fileName; }
Propose a file name based on the uploaded file name. @param string $fileName @param string|int $suffix @return string
entailment
public function removeSessionData($key = null) { $authSessionRefresh = array(); foreach ($this->authSessions as $authSession) { /* @var $authSession AuthSession */ if (isset($key) && $key != $authSession->getName()) { $authSessionRefresh[] = $authSession; } } $this->authSessions = $authSessionRefresh; return $this; }
removes a stored Session @param string|null $key providerName, if null, remove all sessions @return $this
entailment
public function setPassword($password) { $filter = new Filter\CredentialFilter(); $credential = $filter->filter($password); return $this->setCredential($credential); }
{@inheritdoc}
entailment
public function getProfile($provider = null) { if (!isset($provider)) { return $this->profiles; } return isset($this->profiles[$provider]) ? $this->profiles[$provider] : []; }
{@inheritdoc}
entailment
public function getSettings($module) { if (!isset($module)) { throw new \InvalidArgumentException('$module must not be null.'); } if (!$this->settings) { $this->settings = new ArrayCollection(); } foreach ($this->settings as $settings) { if ($settings->moduleName == $module) { return $settings; } } $settings = $this->settingsEntityResolver->getNewSettingsEntity($module); $this->settings->add($settings); return $settings; }
{@inheritdoc}
entailment
public function getGroup($name, $create = false) { $groups = $this->getGroups(); foreach ($groups as $group) { /* @var $group GroupInterface */ if ($group->getName() == $name) { return $group; } } if ($create) { $group = new Group($name, $this); $groups->add($group); return $group; } return null; }
{@inheritdoc}
entailment
public function addProfileButton($name, $options = null) { if (null === $options) { $options['label'] = ucfirst($name); } elseif (is_string($options)) { $options = array('label' => $options); } if (!isset($options['fetch_url'])) { $options['fetch_url'] = sprintf($this->fetchUrl, $name); } if (!isset($options['preview_url']) && $this->previewUrl) { $options['preview_url'] = sprintf($this->previewUrl, $options['label']); } if (!isset($options['icon'])) { $options['icon'] = $name; } $options['disable_capable']['description'] = sprintf( /*@translate*/ 'Allow users to attach their %s profile.', $options['label'] ); $this->add( array( 'type' => 'Auth/SocialProfilesButton', 'name' => $name, 'options' => $options, ) ); return $this; }
Adds a profile button. if <b>$options</b> is null, the <b>$name</b> will be used as label. if <b>$options</b> is a string, this string will be used as label. if <b>$options</b> is an array, it must provide a key 'label'. @param string $name @param null|string|array $options @return self
entailment
public function createValueBuilder() { try { return new EagerValueBuilder(FileFactory::createFromInputStream( new ResourceStream($this->resource))); } catch (\InvalidArgumentException $e) { throw new CorruptedDataException(null, 0, $e); } }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::createValueBuilder()
entailment
public function clear() { $session = $this->getSessionContainer(); if (!$session->isSwitchedUser) { return false; } $oldSession = unserialize($session->session); $ref = $session->ref; $_SESSION = $oldSession; return $ref ? $ref : true; }
Restores the original user. @return bool
entailment
public function switchUser($id, array $params = []) { if ($id instanceOf UserInterface) { $id = $id->getId(); } $oldSession = serialize($_SESSION); $session = $this->getSessionContainer(); if ($session->isSwitchedUser) { return false; } $session->session = $oldSession; $session->isSwitchedUser = true; $session->originalUser = $this->exchangeAuthUser($id); $session->params = $params; $session->ref = isset($params['ref']) ? $params['ref'] : $this->getController()->getRequest()->getRequestUri(); return true; }
Switch to another user. @param string|UserInterface $id user id of the user to switch to. @param array $params Additional parameters to store in the session container. @return bool
entailment
public function setSessionParams(array $params, $merge = false) { $session = $this->getSessionContainer(); if (isset($session->params) && $merge) { $params = ArrayUtils::merge($session->params, $params); } $session->params = $params; return $this; }
Set additional params. @param array $params @param bool $merge Merges with existing params. @return self
entailment
public function getSessionParam($key, $default = null) { $params = $this->getSessionParams(); return array_key_exists($key, $params) ? $params[$key] : $default; }
Get a param. @param string $key @param mixed $default Value to return if param $key is not set. @return null
entailment
private function getSessionContainer() { if (!$this->sessionContainer) { $this->sessionContainer = new Container(self::SESSION_NAMESPACE); } return $this->sessionContainer; }
Gets the session container. @return Container
entailment
private function exchangeAuthUser($id) { $storage = $this->auth->getStorage(); $originalUserId = $storage->read(); $this->auth->clearIdentity(); $storage->write($id); if ($acl = $this->getAclPlugin()) { $acl->setUser($this->auth->getUser()); } return $originalUserId; }
Exchanges the authenticated user in AuthenticationService. @param string $id @return string The id of the previously authenticated user.
entailment
public function createValueBuilder() { try { return new EagerValueBuilder(N2nLocale::build($this->value)); } catch (IllegalN2nLocaleFormatException $e) { throw new CorruptedDataException(null, 0, $e); } }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::createValueBuilder()
entailment
public function editAction() { /* @var $user \Auth\Entity\User */ $user = $this->userRepository->find($this->params('id'), \Doctrine\ODM\MongoDB\LockMode::NONE, null, ['allowDeactivated' => true]); // check if user is not found if (!$user) { return $this->notFoundAction(); } $params = $this->params(); $forms = $this->formManager; /* @var $infoContainer \Auth\Form\UserProfileContainer */ $infoContainer = $forms->get('Auth/UserProfileContainer'); $infoContainer->setEntity($user); $statusContainer = $forms->get('Auth/UserStatusContainer'); $statusContainer->setEntity($user); // set selected user to image strategy $imageStrategy = $infoContainer->getForm('info.image') ->getHydrator() ->getStrategy('image'); $fileEntity = $imageStrategy->getFileEntity(); $fileEntity->setUser($user); $imageStrategy->setFileEntity($fileEntity); if ($this->request->isPost()) { $formName = $params->fromQuery('form'); $container = $formName === 'status' ? $statusContainer : $infoContainer; $form = $container->getForm($formName); if ($form) { $postData = $form->getOption('use_post_array') ? $params->fromPost() : []; $filesData = $form->getOption('use_files_array') ? $params->fromFiles() : []; $form->setData(array_merge($postData, $filesData)); if (!$form->isValid()) { return new JsonModel( array( 'valid' => false, 'errors' => $form->getMessages(), ) ); } $this->userRepository->store($user); if ('file-uri' === $params->fromPost('return')) { $content = $form->getHydrator()->getLastUploadedFile()->getUri(); } else { if ($form instanceof SummaryFormInterface) { $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY); $viewHelper = 'summaryForm'; } else { $viewHelper = 'form'; } $content = $this->viewHelper->get($viewHelper)->__invoke($form); } return new JsonModel( array( 'valid' => $form->isValid(), 'content' => $content, ) ); } } return [ 'infoContainer' => $infoContainer, 'statusContainer' => $statusContainer ]; }
Edit user @return \Zend\Http\Response|ViewModel|array
entailment
public function processChar($char) { if (!StringUtils::isEmpty($char)) { $this->currentToken .= $char; return; } if (null !== $this->joinComparator) { $this->joinNql .= ' ' . $this->currentToken; $this->currentToken = ''; return; } if ($this->expectingKeywordJoin) { if (mb_strtoupper($this->currentToken) != Nql::KEYWORD_JOIN) { throw $this->createNqlParseException(Nql::KEYWORD_JOIN . ' expected. ' . $this->currentToken . ' given.'); } $this->currentToken = ''; $this->expectingKeywordJoin = false; return; } if (strtoupper($this->currentToken) == Nql::KEYWORD_FETCH) { if (null !== $this->joinCriteria || null !== $this->joinEntityClass && null !== $this->joinProperty) { throw $this->createNqlParseException('Invalid position for: ' . Nql::KEYWORD_FETCH); } $this->fetch = true; $this->currentToken = ''; return; } $this->processCurrentToken(); }
}
entailment
public function filter($value) { if (!$value instanceof User) { return array(); } $info = $value->getInfo(); return array( 'id' => $value->getId(), 'name' => $info->displayName, 'image' => $info->image ? $info->image->uri : '', 'email' => $info->email, ); }
Filters an user to a search result array. @return array @see \Zend\Filter\FilterInterface::filter()
entailment
public function setRawValue(EntityModel $entityModel, string $columnName, $rawValue, int $pdoDataType = null) { if ($columnName != $this->idColumnName) { $this->assignRawValue($entityModel, $columnName, $rawValue, false, $pdoDataType); return; } if ($this->idRawValue !== null && $this->idRawValue !== $rawValue) { throw new EntityDataException('Entity id changed for ' . $this->entityModel->getClass()->getName() . ' (id: ' . $this->idRawValue . ' new id: ' . $rawValue . ')'); } $this->setIdRawValue($rawValue, true); }
}
entailment
public function getTransactional() { if ($this->transactionalEm !== null && $this->transactionalEm->isOpen()) { return $this->transactionalEm; } $pdo = $this->pdoPool->getPdo($this->persistenceUnitName); if (!$pdo->inTransaction()) { throw new IllegalStateException('No tranaction open.'); } $this->transactionalEm = new LazyEntityManager($this->persistenceUnitName, $this->pdoPool, true); $this->transactionalEm->bindPdo($pdo); return $this->transactionalEm; }
{@inheritDoc} @see \n2n\persistence\orm\EntityManagerFactory::getTransactional()
entailment
public function getExtended() { if (!isset($this->shared)) { $this->shared = $this->create(); } return $this->shared; }
{@inheritDoc} @see \n2n\persistence\orm\EntityManagerFactory::getExtended()
entailment
public function normalize($fileName, $suffix = 0) { if ($this->casePreservation === self::LOWER_CASE) { $fileName = strtolower($fileName); } $ret = preg_replace('/[^\w.]+/', '-', $fileName); $ret = preg_replace('/-+/', '-', $ret); if ($suffix !== 0) { $ext = (string)pathinfo($ret, PATHINFO_EXTENSION); $fn = (string)pathinfo($ret, PATHINFO_FILENAME); $ret = sprintf('%s-%d.%s', trim($fn, '.'), $suffix, $ext); } return $ret; }
Propose a file name based on the uploaded file name. @param string $fileName @param string|int $suffix @return string
entailment
public function requestColumn(string $propertyName, string $columnName = null, array $relatedComponents = array()) { $determineColumnName = $this->determineColumnName($propertyName, $columnName === null, $relatedComponents); if ($columnName === null) { $columnName = $determineColumnName; } $columnName = $this->namingStrategy->buildColumnName($propertyName, $columnName); $this->setupProcess->registerColumnName($columnName, $this->buildPropertyString($propertyName), $relatedComponents); return $columnName; }
Request a column to write your data. @param string $propertyName @param string $columnName @param string $overrideAllowed @param array $relatedComponents @return string
entailment
public function preUpdate($isNew = false) { if (null === $this->educations) { $this->getEducations(); } if (null === $this->employments) { $this->getEmployments(); } if (null === $this->link) { $this->getLink(); } }
{@inheritDoc} @see \Core\Entity\PreUpdateAwareInterface::preUpdate() @ODM\PreUpdate @ODM\PrePersist
entailment
public function getData($key = null) { if (null === $key) { return $this->data; } $return = $this->data; foreach (explode('.', $key) as $subKey) { if (isset($return[$subKey])) { $return = $return[$subKey]; } else { return null; } } return $return; }
{@inheritDoc} @see \Auth\Entity\SocialProfiles\ProfileInterface::getData()
entailment
public function setData(array $data) { $this->data = $data; // Force recreation of collections and properties. $this->educations = null; $this->employments = null; $this->link = null; return $this; }
{@inheritDoc} @see \Auth\Entity\SocialProfiles\ProfileInterface::setData()
entailment
public function getLink() { if (!$this->link) { $this->link = $this->getData($this->config['properties_map']['link']); } return $this->link; }
{@inheritDoc} @see \Auth\Entity\SocialProfiles\ProfileInterface::getLink()
entailment
protected function getCollection($type) { $collection = new ArrayCollection(); $key = $this->config[$type]['key']; $hydrator = $this->getHydrator($type); $filter = 'filter' . rtrim($type, 's'); $entity = $this->getEntity($type); $dataArray = $this->getData($key); if ($dataArray) { foreach ($dataArray as $data) { $data = $this->$filter($data); if (!count($data)) { continue; } $current = $hydrator->hydrate($data, clone $entity); $collection->add($current); } } return $collection; }
Creates a collection of normalized embedded documents. @param string $type @uses getHydrator(), getEntity(), getData() @return \Core\Entity\Collection\ArrayCollection
entailment
protected function getHydrator($type) { $hydrator = isset($this->config[$type]['hydrator']) ? $this->config[$type]['hydrator'] : new EntityHydrator(); if (is_string($hydrator)) { $this->config[$type]['hydrator'] = $hydrator = new $hydrator(); } return $hydrator; }
Gets a hydrator @param string $type @return \Core\Entity\Hydrator\EntityHydrator
entailment
protected function getEntity($type) { $entity = isset($this->config[$type]['entity']) ? $this->config[$type]['entity'] : '\Cv\Entity\\'. ucfirst(rtrim($type, 's')); if (is_string($entity)) { $this->config[$type]['entity'] = $entity = new $entity(); } return $entity; }
Gets an entity for education or employment. @param string $type @return \Core\Entity\EntityInterface
entailment
public function get($property) { $auth = $this->authenticationService; if ($auth->hasIdentity()) { if (false !== strpos($property, '.')) { $value = $auth->getUser(); foreach (explode('.', $property) as $prop) { $value = $value->$prop; } return $value; } return 'id' == $property ? $auth->getIdentity() : $auth->getUser()->{'get' . $property}(); } return null; }
@param $property @return null
entailment
public function createQuery($params, $queryBuilder) { if (!empty($params['text'])) { $queryBuilder->text($params['text']); } $queryBuilder->field('isDraft')->equals(false); if (isset($params['sort'])) { foreach (explode(",", $params['sort']) as $sort) { $queryBuilder->sort($this->filterSort($sort)); } } return $queryBuilder; }
@param $params @param \Doctrine\ODM\MongoDB\Query\Builder $queryBuilder @return mixed
entailment
public function createValueBuilder() { if ($this->value === null) { return new EagerValueBuilder(null); } return new EagerValueBuilder($this->entityModel->getClass()); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::createValueBuilder()
entailment
public function toHttpQuery() { return '?' . http_build_query( array_filter( [ 'actorInstitution' => $this->actorInstitution, 'actorId' => $this->actorId, 'name' => $this->name, 'type' => $this->type, 'secondFactorId' => $this->secondFactorId, 'email' => $this->email, 'institution' => $this->institution, 'status' => $this->status, 'orderBy' => $this->orderBy, 'orderDirection' => $this->orderDirection ], function ($value) { return !is_null($value); } ) ); }
Return the Http Query string as should be used, MUST include the '?' prefix. @return string
entailment
public function loadMetadataForClass(\ReflectionClass $class) { $classMetadata = new MergeableClassMetadata($class->getName()); foreach ($class->getProperties() as $reflectionProperty) { $propertyMetadata = new PropertyMetadata($class->getName(), $reflectionProperty->getName()); /** @var $annotation \Zicht\Bundle\FileManagerBundle\Annotation\File */ $annotation = $this->reader->getPropertyAnnotation( $reflectionProperty, 'Zicht\Bundle\FileManagerBundle\Annotation\File' ); if (null !== $annotation) { // a "@DefaultValue" annotation was found $propertyMetadata->fileManager = $annotation->settings; } $classMetadata->addPropertyMetadata($propertyMetadata); } return $classMetadata; }
Loads the metadata for the class. @param \ReflectionClass $class @return \Metadata\MergeableClassMetadata
entailment
public function setAttr(\n2n\persistence\orm\property\EntityProperty $entityProperty, $name, $value) { throw new UnsupportedOperationException(); }
/* (non-PHPdoc) @see \n2n\persistence\orm\store\action\EntityAction::setAttr()
entailment
public function requestPropertyComparisonStrategy(TreePath $treePath) { $queryPoint = $this->findSelectQueryPoint($treePath); $comparisonStrategy = null; if ($treePath->hasNext()) { $comparisonStrategy = $queryPoint->requestPropertyComparisonStrategy($treePath); } else { $comparisonStrategy = $queryPoint->requestComparisonStrategy(); } if ($comparisonStrategy->getType() != ComparisonStrategy::TYPE_COLUMN) { throw new QueryConflictException('Property can not be compared in having clause: ' . TreePath::prettyPropertyStr($treePath->getDones())); } return new ComparisonStrategy(new SelectColumnComparable( $comparisonStrategy->getColumnComparable(), $this->queryModel->getQueryItemSelect())); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\QueryPointResolver::requestPropertyComparisonStrategy()
entailment
public function requestPropertyRepresentableQueryItem(TreePath $treePath) { $queryPoint = $this->findSelectQueryPoint($treePath); $queryItem = null; if ($treePath->hasNext()) { $queryItem = $queryPoint->requestPropertyRepresentableQueryItem($treePath); } else { $queryItem = $queryPoint->requestRepresentableQueryItem(); } $columnAlias = $this->queryModel->getQueryItemSelect()->selectQueryItem($queryItem); return new QueryColumn($columnAlias); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\QueryPointResolver::requestPropertyRepresentableQueryItem()
entailment
public function prepareExceptionViewModel(MvcEvent $e) { // Do nothing if no error in the event $error = $e->getError(); if (empty($error)) { return; } // Do nothing if the result is a response object $result = $e->getResult(); if ($result instanceof Response) { return; } // Do nothing if there is no exception or the exception is not // an UnauthorizedAccessException $exception = $e->getParam('exception'); if (!$exception instanceof UnauthorizedAccessException) { return; } $response = $e->getResponse(); if (!$response) { $response = new Response(); $e->setResponse($response); } /* * Return an image, if an image was requested. */ if ($exception instanceof UnauthorizedImageAccessException) { $image = __DIR__ . '/../../../../../public/images/unauthorized-access.png'; $response->setStatusCode(Response::STATUS_CODE_403) ->setContent(file_get_contents($image)) ->getHeaders() ->addHeaderLine('Content-Type', 'image/png'); $e->stopPropagation(); $response->sendHeaders(); //echo file_get_contents($image); //$response->stopped = true; return $response; } $application = $e->getApplication(); $auth = $application->getServiceManager()->get('AuthenticationService'); if (!$auth->hasIdentity()) { $routeMatch = $e->getRouteMatch(); $routeMatch->setParam('controller', 'Auth\Controller\Index'); $routeMatch->setParam('action', 'index'); $query = $e->getRequest()->getQuery(); $ref = $e->getRequest()->getRequestUri(); $ref = preg_replace('~^' . preg_quote($e->getRouter()->getBaseUrl()) . '~', '', $ref); $query->set('ref', $ref); $query->set('req', 1); $response->setStatusCode(Response::STATUS_CODE_401); $response->getHeaders() ->addHeaderLine('X-YAWIK-Login-Url', $e->getRouter()->assemble([], ['name' => 'lang/auth', 'query' => ['ref' => $ref]])); $result = $application->getEventManager()->trigger('dispatch', $e); $e->stopPropagation(); return $result; } $message = $exception->getMessage(); $model = new ViewModel( array( 'message' => empty($message) ? /*@translate*/ 'You are not permitted to access this resource.' : $message, 'exception' => $e->getParam('exception'), 'display_exceptions' => $this->displayExceptions(), ) ); $model->setTemplate($this->getExceptionTemplate()); $e->setResult($model); // $statusCode = $response->getStatusCode(); // if ($statusCode === 200) { $response->setStatusCode(Response::STATUS_CODE_403); // } }
Create an exception view model, and set the HTTP status code @todo dispatch.error does not halt dispatch unless a response is returned. As such, we likely need to trigger rendering as a low priority dispatch.error event (or goto a render event) to ensure rendering occurs, and that munging of view models occurs when expected. @param MvcEvent $e @return void
entailment
protected function preAssert( Acl $acl, RoleInterface $role = null, ResourceInterface $resource = null, $privilege = null ) { return null; }
Overwrite this to check some conditions before the event is triggered. If this method returns a boolean value, this value will be returned as the assertions' result and no event will be triggered. @param Acl $acl @param RoleInterface $role @param ResourceInterface $resource @param null|string $privilege @return null|bool
entailment
public function serialize() { return serialize( [ $this->id, $this->nameId, $this->institution, $this->email, $this->commonName, $this->preferredLocale ] ); }
Used so that we can serialize the Identity within the SAMLToken, so we can store the token in a session. This to support persistent login @return string
entailment
public function unserialize($serialized) { list ( $this->id, $this->nameId, $this->institution, $this->email, $this->commonName, $this->preferredLocale ) = unserialize($serialized); }
Used so that we can unserialize the Identity within the SAMLToken, so that it can be loaded from the session for persistent login. @param string $serialized
entailment
public function getConsent($description) { static $codes = array(); if (! isset($codes[$description])) { $codes[$description] = $this->_loadClass('consentCode', true, array($description)); } return $codes[$description]; }
Returns a single consent code object. @param string $description @return \Gems\Util\ConsentCode
entailment
public function getConsentRejected() { if ($this->project->offsetExists('consentRejected')) { return $this->project->consentRejected; } // Remove in 1.7.3 if ($this->project->offsetExists('concentRejected')) { throw new \Gems_Exception_Coding('project.ini setting was changed from "concentRejected" to "consentRejected", please update your project.ini'); } return 'do not use'; }
Retrieve the consentCODE to use for rejected responses by the survey system The mapping of actual consents to consentCODEs is done in the gems__consents table @return string Default value is 'do not use' @throws \Gems_Exception_Coding
entailment
public function getConsentTypes() { if (isset($this->project->consentTypes)) { $consentTypes = explode('|', $this->project->consentTypes); } else { $consentTypes = array('do not use', 'consent given'); } return array_combine($consentTypes, $consentTypes); }
Retrieve the array of possible consentCODEs to use for responses by the survey system The mapping of actual consents to consentCODEs is done in the gems__consents table @return array Default consent codes are 'do not use' and 'consent given'
entailment
public function getCurrentURI($subpath = '') { static $uri; if (! $uri) { $uri = (\MUtil_Https::on() || $this->project->isHttpsRequired()) ? 'https' : 'http'; $uri .= '://'; $uri .= isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $this->project->getConsoleUrl(); $uri .= $this->basepath->getBasePath(); } if ($subpath && ($subpath[0] != '/')) { $subpath = '/' . $subpath; } return $uri . $subpath; }
Returns the current 'base site' url, optionally with a subpath. @staticvar string $uri @param string $subpath Optional string @return string The Url + basePath plus the optional subpath
entailment
public function getReceptionCode($code) { static $codes = array(); if (! isset($codes[$code])) { $codes[$code] = $this->_loadClass('receptionCode', true, array($code)); } return $codes[$code]; }
Returns a single reception code object. @param string $code @return \Gems_Util_ReceptionCode
entailment
public function isAllowedIP($ip, $ipRanges = "") { $address = IpFactory::addressFromString($ip); if (! (($address instanceof AddressInterface) && strlen($ipRanges))) { return true; } $aType = $address->getAddressType(); $ranges = explode('|', $ipRanges); foreach ($ranges as $range) { if (($sep = strpos($range, '-')) !== false) { $rangeIF = IpFactory::rangeFromBoundaries(substr($range, 0, $sep), substr($range, $sep + 1)); } else { $rangeIF = IpFactory::rangeFromString($range); } if (($rangeIF instanceof RangeInterface) && $rangeIF->getAddressType() == $aType && $rangeIF->contains($address)) { return true; } } return false; }
Checks if a given IP is allowed according to a set of IP addresses / ranges. Multiple addresses/ranges are separated by a colon, an individual range takes the form of Separate with | examples: 10.0.0.0-10.0.0.255, 10.10.*.*, 10.10.151.1 or 10.10.151.1/25 @param string $ip @param string $ipRanges @return bool
entailment
public function addConfigFields(\MUtil_Model_ModelAbstract $orgModel) { $configModel = $this->getConfigModel(true); $order = $orgModel->getOrder('gor_user_class') + 1; foreach ($configModel->getItemNames() as $name) { $orgModel->set($name, 'order', $order++); $orgModel->set($name, $configModel->get($name)); } }
Appends the needed fields for this config to the $bridge @param \MUtil_Model_ModelAbstract $orgModel
entailment
public function getAuthAdapter(\Gems_User_User $user, $password) { //Ok hardcoded for now this needs to be read from the userdefinition $configData = $this->loadConfig(array('gor_id_organization' => $user->getBaseOrganizationId())); $config = array('ip' => $configData['grcfg_ip'], 'authenticationport' => $configData['grcfg_port'], 'sharedsecret' => $configData['grcfg_secret']); //Unset empty foreach($config as $key=>$value) { if (empty($value)) { unset($config[$key]); } } $adapter = new \Gems_User_Adapter_Radius($config); $adapter->setIdentity($user->getLoginName()) ->setCredential($password); return $adapter; }
Returns an initialized Zend\Authentication\Adapter\AdapterInterface @param \Gems_User_User $user @param string $password @return Zend\Authentication\Adapter\AdapterInterface
entailment
protected function getConfigModel($valueMask = true) { if (!$this->_configModel) { $model = new \MUtil_Model_TableModel('gems__radius_config', 'config'); // $model = new \Gems_Model_JoinModel('config', 'gems__radius_config', 'grcfg'); $model->setIfExists('grcfg_ip', 'label', $this->translate->_('IP address'), 'required', true); $model->setIfExists('grcfg_port', 'label', $this->translate->_('Port'), 'required', true); $model->setIfExists('grcfg_secret', 'label', $this->translate->_('Shared secret'), 'description', $this->translate->_('Enter only when changing'), 'elementClass', 'password', 'required', false, 'repeatLabel', $this->translate->_('Repeat password') ); $type = new \Gems_Model_Type_EncryptedField($this->project, $valueMask); $type->apply($model, 'grcfg_secret'); $this->_configModel = $model; } return $this->_configModel; }
Get a model to store the config @param boolean $valueMask MAsk the password or if false decrypt it @return \Gems_Model_JoinModel
entailment
protected function getUserSelect($login_name, $organization) { /** * Read the needed parameters from the different tables, lots of renames * for compatibility accross implementations. */ $select = new \Zend_Db_Select($this->db); $select->from('gems__user_logins', array( 'user_login_id' => 'gul_id_user', 'user_two_factor_key' => 'gul_two_factor_key', 'user_enable_2factor' => 'gul_enable_2factor' )) ->join('gems__staff', 'gul_login = gsf_login AND gul_id_organization = gsf_id_organization', array( 'user_id' => 'gsf_id_user', 'user_login' => 'gsf_login', 'user_email' => 'gsf_email', 'user_first_name' => 'gsf_first_name', 'user_surname_prefix' => 'gsf_surname_prefix', 'user_last_name' => 'gsf_last_name', 'user_gender' => 'gsf_gender', 'user_group' => 'gsf_id_primary_group', 'user_locale' => 'gsf_iso_lang', 'user_logout' => 'gsf_logout_on_survey', 'user_base_org_id' => 'gsf_id_organization', )) ->join('gems__groups', 'gsf_id_primary_group = ggp_id_group', array( 'user_role'=>'ggp_role', 'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges', )) //->joinLeft('gems__user_passwords', 'gul_id_user = gup_id_user', array( // 'user_password_reset' => 'gup_reset_required', // )) ->where('ggp_group_active = 1') ->where('gsf_active = 1') ->where('gul_can_login = 1') ->where('gul_login = ?') ->where('gul_id_organization = ?') ->limit(1); return $select; }
Copied from \Gems_User_StaffUserDefinition but left out the password link @param type $login_name @param type $organization @return \Zend_Db_Select
entailment
public function loadConfig($data) { $model = $this->getConfigModel(false); $newData = $model->loadFirst(array('grcfg_id_organization' => $data['gor_id_organization'])); if (empty($newData)) { $newData = $model->loadNew(); } $newData['grcfg_id_organization'] = $data['gor_id_organization']; return $newData; }
Handles loading the config for the given data @param array $data @return array
entailment
public function saveConfig($data, $values) { $model = $this->getConfigModel(true); $values['grcfg_id_organization'] = $data['gor_id_organization']; return $model->save($values) + $data; }
Handles saving the configvalues in $values using the $data @param array $data @param array $values @return array
entailment
public function getMenuParameter($name, $altname = null) { if (array_key_exists($name, $this->values) && ! empty($this->values[$name])) { return $this->values[$name]; } $this->values[$name] = null; foreach ($this->sources as $source) { if ($source instanceof \MUtil_Model_Bridge_TableBridgeAbstract) { if ($source->has($name)) { $this->values[$name] = $source->getLazy($name); } } elseif ($source instanceof \Gems_Menu_ParameterSourceInterface) { $this->values[$name] = $source->getMenuParameter($name, $this->values[$name]); } elseif ($source instanceof \Zend_Controller_Request_Abstract) { $value = $source->getParam($name, null); if (null === $value || empty($value)) { $value = $source->getParam($altname, $this->values[$name]); } $this->values[$name] = $value; } elseif (is_array($source)) { // \MUtil_Echo::track($name, $source); if (isset($source[$name])) { $this->values[$name] = $source[$name]; } } elseif ($source instanceof \MUtil_Lazy_RepeatableInterface) { $this->values[$name] = $source->__get($name); } if (null !== $this->values[$name] && ! empty($this->values[$name])) { break; } } return $this->values[$name]; }
Returns a value to use as parameter for $name or $default if this object does not contain the value. @param string $name @param mixed $default @return mixed
entailment
public function hasHtmlOutput() { $user = $this->loginStatusTracker->getUser(); if ($user) { $user->setAsCurrentUser(); /** * Tell the user */ $this->addMessage(sprintf($this->_('Login successful, welcome %s.'), $user->getFullName())); /** * Log the login */ $this->accesslog->logChange($this->request); } return false; }
The place to check if the data set in the snippet is valid to generate the snippet. When invalid data should result in an error, you can throw it here but you can also perform the check in the checkRegistryRequestsAnswers() function from the {@see \MUtil_Registry_TargetInterface}. @return boolean
entailment
public function getHtmlOutput(\Zend_View_Abstract $view) { if ($script = $this->getAjaxEventScript()) { $baseUrl = \GemsEscort::getInstance()->basepath->getBasePath(); \MUtil_JQuery::enableView($view); $view->headScript()->appendFile($baseUrl . '/gems/js/jquery.getSelectOptions.js'); $view->inlineScript()->appendScript($script); } return parent::getHtmlOutput($view); }
Create the snippets content This is a stub function either override getHtmlOutput() or override render() @param \Zend_View_Abstract $view Just in case it is needed here @return \MUtil_Html_HtmlInterface Something that can be rendered
entailment