sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function generateIsotopeVisitHitTop($VisitorsID, $limit = 20, $parse = true) { $arrIsotopeStatCount = false; //Isotope Table exists? if (true === $this->getIsotopeTableExists()) { $objIsotopeStatCount = \Database::getInstance() ->prepare("SELECT visitors_page_id, visitors_page_pid, visitors_page_lang, SUM(visitors_page_visit) AS visitors_page_visits, SUM(visitors_page_hit) AS visitors_page_hits FROM tl_visitors_pages WHERE vid = ? AND visitors_page_type = ? GROUP BY visitors_page_id, visitors_page_pid, visitors_page_lang ORDER BY visitors_page_visits DESC, visitors_page_hits DESC, visitors_page_id, visitors_page_pid, visitors_page_lang ") ->limit($limit) ->execute($VisitorsID, self::PAGE_TYPE_ISOTOPE); while ($objIsotopeStatCount->next()) { $alias = false; $aliases = $this->getIsotopeAliases($objIsotopeStatCount->visitors_page_id, $objIsotopeStatCount->visitors_page_pid); if (false !== $aliases['PageAlias']) { $alias = $aliases['PageAlias'] .'/'. $aliases['ProductAlias']; $title = $aliases['ProductTeaser'] .': '. $aliases['ProductName']; } if (false !== $alias) { $arrIsotopeStatCount[] = array ( 'title' => $title, 'alias' => $alias, 'lang' => $objIsotopeStatCount->visitors_page_lang, 'visits' => $objIsotopeStatCount->visitors_page_visits, 'hits' => $objIsotopeStatCount->visitors_page_hits ); } } if ($parse === true) { /* @var $TemplatePartial Template */ $TemplatePartial = new \BackendTemplate('mod_visitors_be_stat_partial_isotopevisithittop'); $TemplatePartial->IsotopeVisitHitTop = $arrIsotopeStatCount; return $TemplatePartial->parse(); } return $arrIsotopeStatCount; } return false; }
////////////////////////////////////////////////////////////
entailment
protected function reset() { //NEVER TRUST USER INPUT if (function_exists('filter_var')) // Adjustment for hoster without the filter extension { $this->_http_referer = isset($_SERVER['HTTP_REFERER']) ? filter_var($_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL) : self::REFERER_UNKNOWN ; } else { $this->_http_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : self::REFERER_UNKNOWN ; } $this->_search_engine = self::SEARCH_ENGINE_UNKNOWN ; $this->_keywords = self::KEYWORDS_UNKNOWN ; }
Reset all properties
entailment
protected function checkEngineGeneric() { if ( preg_match('/\?q=/', $this->_http_referer ) || preg_match('/\&q=/', $this->_http_referer ) ) { $this->_search_engine = self::SEARCH_ENGINE_GENERIC ; if ( isset($this->_parse_result['q']) ) { $this->_keywords = $this->_parse_result['q']; } return true; } return false; }
Last Check for unknown Search Engines @return bool
entailment
public function process(InvokeSpec $specifier): ResultSpec { $resultUnits = []; $callUnits = $specifier->getUnits(); foreach ($callUnits as $unit) { $unit = $this->preProcess($unit); if ($unit instanceof Invoke\Invoke) { $resultUnits[] = $this->handleCallUnit($unit); } elseif ($unit instanceof Invoke\Notification) { $resultUnits[] = $this->handleNotificationUnit($unit); } else { $resultUnits[] = $this->handleErrorUnit($unit); } } return new ResultSpec($resultUnits, $specifier->isSingleCall()); }
@param InvokeSpec $specifier @return ResultSpec
entailment
private function preProcess(AbstractInvoke $invoke): AbstractInvoke { $result = $this->preProcess->handle(new ProcessorContainer($this, $invoke)); if ($result instanceof ProcessorContainer) { return $result->getInvoke(); } throw new \RuntimeException(); }
@param AbstractInvoke $invoke @return AbstractInvoke
entailment
private function handleCallUnit(Invoke\Invoke $unit): Result\AbstractResult { try { list($class, $method) = $this->getClassAndMethod($unit->getRawMethod()); $result = $this->invoker->invoke($this->handlers[$class], $method, $unit->getRawParams()); } catch (JsonRpcException $exception) { return new Result\Error($unit->getRawId(), $exception); } return new Result\Result($unit->getRawId(), $result); }
@param Invoke\Invoke $unit @return Result\AbstractResult
entailment
private function handleNotificationUnit(Invoke\Notification $unit): Result\AbstractResult { try { list($class, $method) = $this->getClassAndMethod($unit->getRawMethod()); $this->invoker->invoke($this->handlers[$class], $method, $unit->getRawParams()); } catch (JsonRpcException $exception) { return new Result\Error(null, $exception); } return new Result\Notification(); }
@param Invoke\Notification $unit @return Result\AbstractResult
entailment
private function handleErrorUnit(Invoke\Error $unit): Result\AbstractResult { return new Result\Error(null, $unit->getBaseException()); }
@param Invoke\Error $unit @return Result\AbstractResult
entailment
private function getClassAndMethod(string $requestedMethod) { list($class, $method) = $this->mapper->getClassAndMethod($requestedMethod); if ($class && array_key_exists($class, $this->handlers) && method_exists($this->handlers[$class], $method)) { return [$class, $method]; } throw new MethodNotFoundException(); }
@param string $requestedMethod @return array
entailment
public function build(ResultSpec $result): string { $response = []; $units = $result->getResults(); foreach ($units as $unit) { /** @var AbstractResult $unit */ if ($unit instanceof Result) { /** @var Result $unit */ $response[] = [ 'jsonrpc' => '2.0', 'result' => $this->preBuild($unit->getResult()), 'id' => $unit->getId() ]; } elseif ($unit instanceof Error) { /** @var Error $unit */ $baseException = $unit->getBaseException(); $response[] = [ 'jsonrpc' => '2.0', 'error' => [ 'code' => $baseException->getJsonRpcCode(), 'message' => $this->getErrorMessage($baseException->getJsonRpcCode()), 'data' => $baseException->getJsonRpcData() ], 'id' => $unit->getId() ]; } } if (empty($response)) { return ''; } if ($result->isSingleResult()) { return json_encode($response[0]); } return json_encode($response); }
@param ResultSpec $result @return string
entailment
private function preBuild($result) { $container = $this->preBuild->handle(new BuilderContainer($this, $result)); if ($container instanceof BuilderContainer) { return $container->getValue(); } throw new \RuntimeException(); }
@param mixed $result @return mixed
entailment
public function fetchJson($parameters = []) { if (!isset($parameters['url'])) { Craft::error('URL parameter not set', __METHOD__); return false; } $data = self::getUrl($parameters['url']); return json_decode($data, true); }
Returns JSON from URL. @param array $parameters Parameters, just URL for now. @return string
entailment
protected static function getUrl($url) { Craft::debug('Fetching JSON from: '.$url, __METHOD__); $ch = curl_init(); curl_setopt_array( $ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 5, ] ); $data = curl_exec($ch); $errorNumber = curl_errno($ch); $errorMessage = curl_error($ch); curl_close($ch); if ($errorNumber > 0) { Craft::warning('cURL got an error: '.$errorNumber.', '.$errorMessage, __METHOD__); return false; } return $data; }
Function for actually getting data with cURL Improvements: - Use Guzzle? - Check mimetype? @param string $url URL to fetch @return mixed
entailment
public function updateCMSFields(FieldList $fields) { $msg = _t('JonoM\ShareCare\ShareCareFields.CMSMessage', 'The preview is automatically generated from your content. You can override the default values using these fields:'); $tab = 'Root.' . _t('JonoM\ShareCare\ShareCare.TabName', 'Share'); if ($msg) { $fields->addFieldToTab($tab, new LiteralField('ShareCareFieldsMessage', '<div class="message notice"><p>' . $msg . '</p></div>')); } $fields->addFieldToTab($tab, TextField::create('OGTitleCustom', _t('JonoM\ShareCare\ShareCareFields.ShareTitle', 'Share title')) ->setAttribute('placeholder', $this->owner->getDefaultOGTitle()) ->setMaxLength(90)); $fields->addFieldToTab($tab, TextAreaField::create('OGDescriptionCustom', _t('JonoM\ShareCare\ShareCareFields.ShareDescription', 'Share description')) ->setAttribute('placeholder', $this->owner->getDefaultOGDescription()) ->setRows(2)); $fields->addFieldToTab($tab, UploadField::create('OGImageCustom', _t('JonoM\ShareCare\ShareCareFields.ShareImage', 'Share image')) ->setAllowedFileCategories('image') ->setAllowedMaxFileNumber(1) ->setDescription(_t('JonoM\ShareCare\ShareCareFields.ShareImageRatio', '{Link}Optimum image ratio</a> is 1.91:1. (1200px wide by 630px tall or better)', array('Link' => '<a href="https://developers.facebook.com/docs/sharing/best-practices#images" target="_blank">')))); if (ShareCare::config()->get('pinterest')) { $fields->addFieldToTab($tab, UploadField::create('PinterestImageCustom', _t('ShareCareFields.PinterestImage', 'Pinterest image')) ->setAllowedFileCategories('image') ->setAllowedMaxFileNumber(1) ->setDescription(_t('JonoM\ShareCare\ShareCareFields.PinterestImageDescription', 'Square/portrait or taller images look best on Pinterest. This image should be at least 750px wide.'))); } }
Add CMS fields to allow setting of custom open graph values.
entailment
public function getOGTitle() { return ($this->owner->OGTitleCustom) ? $this->owner->OGTitleCustom : $this->owner->getDefaultOGTitle(); }
The title that will be used in the 'og:title' open graph tag. Use a custom value if set, or fallback to a default value. @return string
entailment
public function getOGDescription() { // Use OG Description if set if ($this->owner->OGDescriptionCustom) { $description = trim($this->owner->OGDescriptionCustom); if (!empty($description)) { return $description; } } return $this->owner->getDefaultOGDescription(); }
The description that will be used in the 'og:description' open graph tag. Use a custom value if set, or fallback to a default value. @return string
entailment
public function getDefaultOGDescription() { // Use MetaDescription if set if ($this->owner->MetaDescription) { $description = trim($this->owner->MetaDescription); if (!empty($description)) { return $description; } } // Fall back to Content if ($this->owner->Content) { $description = trim($this->owner->obj('Content')->Summary(20, 5)); if (!empty($description)) { return $description; } } return false; }
The default/fallback value to be used in the 'og:description' open graph tag. @return string
entailment
public function getOGImage() { $ogImage = $this->owner->OGImageCustom(); if ($ogImage->exists()) { return ($ogImage->getWidth() > 1200) ? $ogImage->scaleWidth(1200) : $ogImage; } return $this->owner->getDefaultOGImage(); }
The Image object or absolute URL that will be used for the 'og:image' open graph tag. Use a custom selection if set, or fallback to a default value. Image size specs: https://developers.facebook.com/docs/sharing/best-practices#images. @return Image|string|false
entailment
public function getPinterestImage() { $pinImage = $this->owner->PinterestImageCustom(); if ($pinImage->exists()) { return ($pinImage->getWidth() > 1200) ? $pinImage->scaleWidth(1200) : $pinImage; } return $this->owner->getOGImage(); }
Get an Image object to be used in the 'Pin it' ($PinterestShareLink) link. Image size specs: https://developers.pinterest.com/pin_it/. @return Image|null
entailment
protected function getUploadedFile($data) { $file = null; if ($data !== null && is_array($data) && isset($data[FileType::RADIO_FIELDNAME])) { switch ($data[FileType::RADIO_FIELDNAME]) { case FileType::FILE_URL: if (!empty($data[FileType::URL_FIELDNAME])) { $fileurl = $data[FileType::URL_FIELDNAME]; $fileparts = explode('/', $fileurl); $filename = urldecode(array_pop($fileparts)); $parsedFileName = parse_url($filename); // We are only interested in the original file path, strip '?...' section $filePath = sprintf('%s/%s', sys_get_temp_dir(), $parsedFileName['path']); file_put_contents($filePath, file_get_contents($fileurl)); $file = new File($filePath); } break; case FileType::FILE_UPLOAD: if (isset($data[FileType::UPLOAD_FIELDNAME]) && $data[FileType::UPLOAD_FIELDNAME] instanceof UploadedFile) { /** @var UploadedFile $file */ $file = $data[FileType::UPLOAD_FIELDNAME]; } break; } } return $file; }
Get the File object from the form data. @param array $data @return null|File|UploadedFile
entailment
protected function validateFile($file, FormEvent $event) { if ($file instanceof File) { $isValidFile = true; //check if the file is allowed by the MIME-types constraint given if (!empty($this->allowedFileTypes) && null !== $mime = $file->getMimeType()) { if (!in_array($mime, $this->allowedFileTypes)) { $isValidFile = false; $message = $this->translator->trans( 'zicht_filemanager.wrong_type', array( '%this_type%' => $mime, '%allowed_types%' => implode(', ', $this->allowedFileTypes) ), $event->getForm()->getConfig()->getOption('translation_domain') ); $event->getForm()->addError(new FormError($message)); /** Set back data to old so we don`t see new file */ $event->setData(array(FileType::UPLOAD_FIELDNAME => $event->getForm()->getData())); } } if ($isValidFile) { $purgatoryFileManager = $this->getPurgatoryFileManager(); $entity = $event->getForm()->getParent()->getConfig()->getDataClass(); $data = $event->getData(); $replaceFile = isset($data[FileType::KEEP_PREVIOUS_FILENAME]) && $data[FileType::KEEP_PREVIOUS_FILENAME] === '1'; $forceFilename = $replaceFile ? $event->getForm()->getData() : ''; $path = $purgatoryFileManager->prepare($file, $entity, $this->field, true, $forceFilename); $purgatoryFileManager->save($file, $path); $this->prepareData($data, $path, $event->getForm()->getPropertyPath()); $event->setData($data); } } }
Validate file. @param File $file @param FormEvent $event
entailment
public function preSubmit(FormEvent $event) { $data = $event->getData(); $entity = $event->getForm()->getParent()->getConfig()->getDataClass(); //if the remove checkbox is checked, clear the data if (isset($data[FileType::REMOVE_FIELDNAME]) && $data[FileType::REMOVE_FIELDNAME] === '1') { $event->setData(null); $data = null; return; } if (null !== ($file = $this->getUploadedFile($data))) { $this->validateFile($file, $event); } else { // nothing uploaded $hash = $data[FileType::HASH_FIELDNAME]; $filename = $data[FileType::FILENAME_FIELDNAME]; // check if there was a purgatory file (and the file is not tampered with) if (!empty($hash) && !empty($filename) && PurgatoryHelper::makeHash($event->getForm()->getPropertyPath(), $filename) === $hash ) { $path = $this->getPurgatoryFileManager()->getFilePath( $entity, $this->field, $filename ); $this->prepareData($data, $path, $event->getForm()->getPropertyPath()); $event->setData($data); //use the original form data, so the field isn't empty } elseif ($event->getForm()->getData() !== null) { unset($data[FileType::HASH_FIELDNAME]); unset($data[FileType::FILENAME_FIELDNAME]); $originalFormData = $event->getForm()->getData(); $path = $this->fileManager->getFilePath($entity, $this->field, $originalFormData); try { $file = new File($path); $data[FileType::UPLOAD_FIELDNAME] = $file; $event->setData($data); } catch (FileNotFoundException $e) { //do nothing } } } }
Just before the form is submitted, check if there is no data entered and if so, set the 'old' data back. @param FormEvent $event @return void
entailment
private function prepareData(&$data, $path, $propertyPath) { $file = new File($path); $data[FileType::FILENAME_FIELDNAME] = $file->getBasename(); $data[FileType::HASH_FIELDNAME] = PurgatoryHelper::makeHash($propertyPath, $data[FileType::FILENAME_FIELDNAME]); $data[FileType::UPLOAD_FIELDNAME] = $file; $file->metaData = $data; }
Prepares the data before sending it to the form @param mixed &$data @param string $path @param string $propertyPath
entailment
public function injectEventManager($assertion, $serviceLocator) { //@TODO: [ZF3] check if ACL working properly /* @var $serviceLocator AssertionManager */ if (!$assertion instanceof EventManagerAwareInterface) { return; } /* @var EventManager $events */ $container = $this->container; $events = $assertion->getEventManager(); if (!$events instanceof EventManagerInterface) { $events = $container->get('EventManager'); /* @var $events \Zend\EventManager\EventManagerInterface */ $assertion->setEventManager($events); } else { //@TODO: [ZF3] setSharedManager method now is removed //$sharedEvents = $container->get('SharedEventManager'); /* @var $sharedEvents \Zend\EventManager\SharedEventManagerInterface */ //$events->setSharedManager($sharedEvents); } }
Injects a shared event manager aware event manager. @param AssertionInterface $assertion @param ServiceLocatorInterface $serviceLocator
entailment
public static function initializeProxy(EntityManager $em, $obj) { if ($obj instanceof EntityProxy) { $em->getPersistenceContext()->getEntityProxyManager() ->initializeProxy($obj); return; } if ($obj instanceof ArrayObjectProxy) { $obj->initialize(); } }
}
entailment
public static function determineValue(EntityPropertyCollection $entityPropertyCollection, $value, CriteriaProperty $criteriaProperty) { $propertyNames = $criteriaProperty->getPropertyNames(); $entityProperty = null; foreach ($criteriaProperty->getPropertyNames() as $propertyName) { $entityProperty = $entityPropertyCollection->getEntityPropertyByName($propertyName); if ($value === null) return null; if (!is_object($value)) { throw new \InvalidArgumentException(); } $value = $entityProperty->readValue($value); if ($entityProperty->hasEmbeddedEntityPropertyCollection()) { $entityPropertyCollection = $entityProperty->getEmbeddedEntityPropertyCollection(); } else if ($entityProperty->hasTargetEntityModel()) { $entityPropertyCollection = $entityProperty->getTargetEntityModel(); } } return $value; }
}
entailment
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'entity' => null, 'property' => null, 'show_current_file' => true, 'show_remove' => true, 'show_keep_previous_filename' => true, 'translation_domain' => 'admin', 'file_types' => [], 'allow_url' => false, ] ); }
{@inheritDoc}
entailment
public function transformCallback($value, $property) { list($property, $id) = $property; return $this->fileManager->getFilePath($this->entities[$id], $property, $value); }
Callback for the FileTransformer - since we can't pass the entity in buildForm, we needed a seperate handler, so the entity is defined :( @param string $value @param string $property @return null|string
entailment
protected function getAllowedTypes(array $options) { $types = null; if (isset($options['file_types'])) { $types = $options['file_types']; $self = $this; if (!is_array($types)) { $types = explode(',', $types); $types = array_map('trim', $types); } array_walk( $types, function (&$val) use ($self) { if (false == preg_match('#^([^/]+)/([\w|\.|\-]+)#', $val)) { $val = $self->getMimeType($val); } } ); } return $types; }
Update options field file_types so if only extension is given it will try to determine mime type @param array $options @return null | mixed;
entailment
public function getMimeType($extension) { /** * check and remove (*.)ext so we only got the extension * when wrong define for example *.jpg becomes jpg */ if (false != preg_match("#^.*\.(?P<EXTENSION>[a-z0-9]{2,4})$#i", $extension, $match)) { $extension = $match['EXTENSION']; } $extension = strtolower($extension); if (is_null($this->mimeTypes)) { $file = __DIR__.'/../Resources/config/mime.yml'; if (is_file($file)) { $this->mimeTypes = Yaml::parse(file_get_contents($file)); } else { throw new \InvalidArgumentException('Mime file not found, perhaps you need to create it first? (zicht:filemanager:create:mime)'); } } if (array_key_exists($extension, $this->mimeTypes)) { return $this->mimeTypes[$extension]; } else { throw new \InvalidArgumentException(sprintf('Could not determine mime type on: %s', $extension)); } }
mime type converter for lazy loading :) @param string $extension @return string @throws \InvalidArgumentException
entailment
public static function createBindColumnJob(QueryItemSelect $queryItemSelect, Selection $selection) { $columnAliases = array(); foreach ($selection->getSelectQueryItems() as $key => $queryItem) { $columnAliases[$key] = $queryItemSelect->selectQueryItem($queryItem); } return new BindColumnJob($selection, $columnAliases); }
}
entailment
public function isRole($role, $inherit = false, $onlyParents = false) { if ($role instanceof RoleInterface) { $role = $role->getRoleId(); } $userRole = $this->getUser()->getRole(); $isRole = $userRole == $role; /* * @todo remove this, if the admin module is implemented */ if ('recruiter' == $role) { $inherit = true; } if ($isRole || !$inherit) { return $isRole; } $acl = $this->getAcl(); /* @var $acl \Zend\Permissions\Acl\Acl */ return method_exists($acl, 'inheritsRole') && $acl->inheritsRole($userRole, $role, $onlyParents); }
Returns true, if the logged in user is of a specific role. If $inherit is TRUE, inheritance is also considered. In that case, the third parameter is used to determine, wether only the direct parent role should be checked or not. @param string|\Zend\Permissions\Acl\Role\RoleInterface $role Matching role. @param bool $inherit @param bool $onlyParents @return bool @uses \Zend\Permission\Acl\Acl::inheritsRole()
entailment
public function onRoute(MvcEvent $event) { if ($event->isError()) { return $event->getResult(); } $routeMatch = $event->getRouteMatch(); $routeName = $routeMatch->getMatchedRouteName(); $resourceId = "route/$routeName"; return $this->checkAcl($event, $resourceId); }
@param MvcEvent $event @return array|\ArrayAccess|mixed|object
entailment
public function reverseTransform($value) { if (null === $value) { return null; } if (is_array($value) && array_key_exists(FileType::UPLOAD_FIELDNAME, $value)) { return $value[FileType::UPLOAD_FIELDNAME]; } return null; }
Transforms File -> string (to database) @param mixed $value @return mixed|null
entailment
public function transform($value) { if (is_array($value)) { $value = $value[FileType::UPLOAD_FIELDNAME]; } try { return array( FileType::UPLOAD_FIELDNAME => new File(call_user_func($this->callback, $value, $this->property)) ); } catch (FileNotFoundException $e) { return null; } }
Transforms string (from database) -> File @param mixed $value @return array|mixed|null
entailment
private function assertAllNonEmptyString(array $values, $parameterName) { foreach ($values as $value) { $this->assertNonEmptyString( $value, $parameterName, 'Elements of "%s" must be non-empty strings, element of type "%s" given' ); } }
@param array $values @param string $parameterName @return void
entailment
public function apply(QueryComparator $queryComparator, QueryState $queryState, QueryPointResolver $queryPointResolver) { $comparatorBuilder = new QueryComparatorBuilder($queryState, $queryPointResolver, $queryComparator); foreach ($this->comparisonDefs as $comparisonDef) { if (isset($comparisonDef['groupCriteriaComparator'])) { $comparisonDef['groupCriteriaComparator']->apply( ($comparisonDef['useAnd'] ? $queryComparator->andGroup() : $queryComparator->orGroup()), $queryState, $queryPointResolver); continue; } if (isset($comparisonDef['testCriteria'])) { $comparatorBuilder->applyTest($comparisonDef['operator'], $comparisonDef['testCriteria'], $comparisonDef['useAnd']); continue; } $comparatorBuilder->applyMatch($comparisonDef['criteriaItem1'], $comparisonDef['operator'], $comparisonDef['criteriaItem2'], $comparisonDef['useAnd']); } }
}
entailment
public function getInputFilterSpecification() { return array( 'firstName' => array( 'required' => true, 'filters' => array( array('name' => '\Zend\Filter\StringTrim'), ), 'validators' => array( new NotEmpty(), new StringLength(array('max' => 50)) ), ), 'lastName' => array( 'required' => true, 'filters' => array( array('name' => 'Zend\Filter\StringTrim'), ), 'validators' => array( new NotEmpty(), new StringLength(array('max' => 50)) ), ), 'email' => array( 'required' => true, 'filters' => array( array('name' => 'Zend\Filter\StringTrim'), ), 'validators' => array( new NotEmpty(), new StringLength(array('max' => 100)), new EmailAddress() ) ), 'image' => array( 'required' => false, 'filters' => array(), 'validators' => array( new File\Exists(), new File\Extension(array('extension' => array('jpg', 'png', 'jpeg', 'gif'))), ), ), ); }
(non-PHPdoc) @see \Zend\InputFilter\InputFilterProviderInterface::getInputFilterSpecification()
entailment
public function beginTransaction() { if ($this->transactionManager === null) { $this->performBeginTransaction(); return; } if (!$this->transactionManager->hasOpenTransaction()) { $this->transactionManager->createTransaction(); } }
(non-PHPdoc) @see PDO::beginTransaction()
entailment
public function commit() { if ($this->transactionManager === null) { $this->prepareCommit(); $this->performCommit(); } if ($this->transactionManager->hasOpenTransaction()) { $this->transactionManager->getRootTransaction()->commit(); } }
(non-PHPdoc) @see PDO::commit()
entailment
public function rollBack() { if ($this->transactionManager === null) { $this->performRollBack(); return; } if ($this->transactionManager->hasOpenTransaction()) { $this->transactionManager->getRootTransaction()->rollBack(); } }
(non-PHPdoc) @see PDO::rollBack()
entailment
public function getDisplayName($emailIfEmpty = true) { if (!$this->lastName) { return $emailIfEmpty ? $this->email : ''; } return ($this->firstName ? $this->firstName . ' ' : '') . $this->lastName; }
@param bool $emailIfEmpty @return string
entailment
public function indexAction() { if ($this->auth->hasIdentity()) { return $this->redirect()->toRoute('lang'); } $viewModel = new ViewModel(); /* @var $loginForm Login */ $loginForm = $this->forms[self::LOGIN]; /* @var $registerForm Register */ $registerForm = $this->forms[self::REGISTER]; /* @var $request \Zend\Http\Request */ $request = $this->getRequest(); if ($request->isPost()) { $data = $this->params()->fromPost(); $adapter = $this->userLoginAdapter; // inject suffixes via shared Events $loginSuffix = ''; // @TODO: replace this by the Plugin LoginFilter $e = $this->getEvent(); $loginSuffixResponseCollection = $this->getEventManager()->trigger('login.getSuffix', $e); if (!$loginSuffixResponseCollection->isEmpty()) { $loginSuffix = $loginSuffixResponseCollection->last(); } $loginForm->setData($data); if (array_key_exists('credentials', $data) && array_key_exists('login', $data['credentials']) && array_key_exists('credential', $data['credentials'])) { $adapter->setIdentity($data['credentials']['login'] . $loginSuffix) ->setCredential($data['credentials']['credential']); } $auth = $this->auth; $result = $auth->authenticate($adapter); if ($result->isValid()) { $user = $auth->getUser(); $language = $this->locale->detectLanguage($request, $user); $this->logger->info('User ' . $user->getLogin() . ' logged in'); $ref = $this->params()->fromQuery('ref', false); if ($ref) { $ref = urldecode($ref); $url = preg_replace('~/[a-z]{2}(/|$)~', '/' . $language . '$1', $ref); $url = $request->getBasePath() . $url; } else { $urlHelper = $this->viewHelperManager->get('url'); $url = $urlHelper('lang', array('lang' => $language)); } $this->notification()->success(/*@translate*/ 'You are now logged in.'); return $this->redirect()->toUrl($url); } else { $loginName = $data['credentials']['login']; if (!empty($loginSuffix)) { $loginName = $loginName . ' (' . $loginName . $loginSuffix . ')'; } $this->logger->info('Failed to authenticate User ' . $loginName); $this->notification()->danger(/*@translate*/ 'Authentication failed.'); } } $ref = $this->params()->fromQuery('ref', false); if ($ref) { $req = $this->params()->fromQuery('req', false); if ($req) { $this->getResponse()->setStatusCode(Response::STATUS_CODE_401); $viewModel->setVariable('required', true); } $viewModel->setVariable('ref', $ref); } $allowRegister = $this->options->getEnableRegistration(); $allowResetPassword = $this->options->getEnableResetPassword(); if (isset($allowRegister)) { $viewModel->setVariables( [ 'allowRegister' => $allowRegister, 'allowResetPassword' => $allowResetPassword ] ); } $viewModel->setVariable('loginForm', $loginForm); $viewModel->setVariable('registerForm', $registerForm); /* @deprecated use loginForm instead of form in your view scripts */ $viewModel->setVariable('form', $loginForm); return $viewModel; }
Login with username and password @return \Zend\Http\Response|ViewModel
entailment
public function loginAction() { $ref = urldecode($this->getRequest()->getBasePath().$this->params()->fromQuery('ref')); $provider = $this->params('provider', '--keiner--'); $hauth = $this->hybridAuthAdapter; $hauth->setProvider($provider); $auth = $this->auth; $result = $auth->authenticate($hauth); $resultMessage = $result->getMessages(); if (array_key_exists('firstLogin', $resultMessage) && $resultMessage['firstLogin'] === true) { try { $user = $auth->getUser(); $password = substr(md5(uniqid()), 0, 6); $login = uniqid() . ($this->options->auth_suffix != "" ? '@' . $this->options->auth_suffix : ''); $externalLogin = $user->getLogin() ?: '-- not communicated --'; $this->logger->debug('first login via ' . $provider . ' as: ' . $externalLogin); $user->setLogin($login); $user->setPassword($password); $user->setRole($this->options->getRole()); $mail = $this->mailer('htmltemplate'); $mail->setTemplate('mail/first-socialmedia-login'); $mail->setSubject($this->options->getMailSubjectRegistration()); $mail->setVariables( array( 'displayName'=> $user->getInfo()->getDisplayName(), 'provider' => $provider, 'login' => $login, 'password' => $password, ) ); $mail->addTo($user->getInfo()->getEmail()); $loggerId = $login . ' (' . $provider . ': ' . $externalLogin . ')'; if (isset($mail) && $this->mailer($mail)) { $this->logger->info('Mail first-login for ' . $loggerId . ' sent to ' . $user->getInfo()->getEmail()); } else { $this->logger->warn('No Mail was sent for ' . $loggerId); } } catch (\Exception $e) { $this->logger->crit($e); $this->notification()->danger( /*@translate*/ 'An unexpected error has occurred, please contact your system administrator' ); } } $user = $auth->getUser(); $this->logger->info('User ' . $auth->getUser()->getInfo()->getDisplayName() . ' logged in via ' . $provider); $settings = $user->getSettings('Core'); if (null !== $settings->localization->language) { $basePath = $this->getRequest()->getBasePath(); $ref = preg_replace('~^'.$basePath . '/[a-z]{2}(?=/|$)~', $basePath . '/' . $settings->localization->language, $ref); } return $this->redirect()->toUrl($ref); }
Login with HybridAuth Passed in Params: - provider: HybridAuth provider identifier. Redirects To: Route 'home'
entailment
public function loginExternAction() { $adapter = $this->externalAdapter; $appKey = $this->params()->fromPost('appKey'); $adapter->setIdentity($this->params()->fromPost('user')) ->setCredential($this->params()->fromPost('pass')) ->setApplicationKey($appKey); $auth = $this->auth; $result = $auth->authenticate($adapter); if ($result->isValid()) { $this->logger->info( 'User ' . $this->params()->fromPost('user') . ' logged via ' . $appKey ); // the external login may include some parameters for an update $updateParams = $this->params()->fromPost(); unset($updateParams['user'], $updateParams['pass'], $updateParams['appKey']); $resultMessage = $result->getMessages(); $password = null; if (array_key_exists('firstLogin', $resultMessage) && $resultMessage['firstLogin'] === true) { $password = substr(md5(uniqid()), 0, 6); $updateParams['password'] = $password; } if (!empty($updateParams)) { $user = $auth->getUser(); try { foreach ($updateParams as $updateKey => $updateValue) { if ('email' == $updateKey) { $user->info->email = $updateValue; } $user->$updateKey = $updateValue; } } catch (\Exception $e) { } $this->repositories->store($user); } $resultMessage = $result->getMessages(); // TODO: send a mail also when required (maybe first mail failed or email has changed) if (array_key_exists('firstLogin', $resultMessage) && $resultMessage['firstLogin'] === true) { // first external Login $userName = $this->params()->fromPost('user'); $this->logger->debug('first login for User: ' . $userName); // if (preg_match('/^(.*)@\w+$/', $userName, $realUserName)) { $userName = $realUserName[1]; } $mail = $this->mailer('htmltemplate'); /* @var $mail \Core\Mail\HTMLTemplateMessage */ $apps = $this->config('external_applications'); $apps = array_flip($apps); $application = isset($apps[$appKey]) ? $apps[$appKey] : null; $mail->setVariables( array( 'application' => $application, 'login'=>$userName, 'password' => $password, ) ); $mail->setSubject($this->options->getMailSubjectRegistration()); $mail->setTemplate('mail/first-external-login'); $mail->addTo($user->getInfo()->getEmail()); try { $this->mailer($mail); $this->logger->info('Mail first-login sent to ' . $userName); } catch (\Zend\Mail\Transport\Exception\ExceptionInterface $e) { $this->logger->warn('No Mail was sent'); $this->logger->debug($e); } } return new JsonModel( array( 'status' => 'success', 'token' => session_id() ) ); } else { $this->logger->info( 'Failed to authenticate User ' . $this->params()->fromPost('user') . ' via ' . $this->params()->fromPost('appKey') ); $this->getResponse()->setStatusCode(Response::STATUS_CODE_401); return new JsonModel( array( 'status' => 'failure', 'user' => $this->params()->fromPost('user'), 'appKey' => $this->params()->fromPost('appKey'), 'code' => $result->getCode(), 'messages' => $result->getMessages(), ) ); } }
Login via an external Application. This will get obsolet as soon we'll have a full featured Rest API. Passed in params: - appKey: Application identifier key - user: Name of the user to log in - pass: Password of the user to log in Returns an json response with the session-id. Non existent users will be created!
entailment
public function logoutAction() { $auth = $this->auth; $this->logger->info('User ' . ($auth->getUser()->getLogin()==''?$auth->getUser()->getInfo()->getDisplayName():$auth->getUser()->getLogin()) . ' logged out'); $auth->clearIdentity(); unset($_SESSION['HA::STORE']); $this->notification()->success(/*@translate*/ 'You are now logged out'); return $this->redirect()->toRoute( 'lang', array('lang' => $this->params('lang')) ); }
Logout Redirects To: Route 'home'
entailment
protected function attachDefaultListeners() { parent::attachDefaultListeners(); $events = $this->getEventManager(); /* * "Redirect" action 'new' and 'edit' to 'form' and set the * route parameter 'mode' to the original action. * This must run before onDispatch, because we alter the action param */ $events->attach( MvcEvent::EVENT_DISPATCH, function ($event) { $routeMatch = $event->getRouteMatch(); $action = $routeMatch->getParam('action'); if ('new' == $action || 'edit' == $action) { $routeMatch->setParam('mode', $action); $routeMatch->setParam('action', 'form'); } }, 10 ); /* * Inject a sidebar view model in the Layout-Model, if * the result in the event is not terminal. * This must run after "InjectViewModelListener", which runs with * a priority of -100. */ $events->attach( MvcEvent::EVENT_DISPATCH, function ($event) { $model = $event->getResult(); if (!$model instanceof ViewModel || $model->terminate()) { return; } $routeMatch = $event->getRouteMatch(); $action = $routeMatch->getParam('action'); if ('form' == $action) { $action = $routeMatch->getParam('mode'); } $layout = $event->getViewModel(); $sidebar = new ViewModel(); $sidebar->setVariable('action', $action); $sidebar->setTemplate('auth/sidebar/groups-menu'); $layout->addChild($sidebar, 'sidebar_auth_groups-menu'); }, -110 ); $serviceLocator = $this->serviceLocator; $defaultServices = $serviceLocator->get('DefaultListeners'); $events->attach($defaultServices); }
Register the default events for this controller @internal Registers two hooks on "onDispatch": - change action to form and set mode parameter - inject sidebar navigation
entailment
public function formAction() { $isNew = 'new' == $this->params('mode'); $form = $this->formManager->get('Auth/Group', array('mode' => $this->params('mode'))); $repository = $this->repositories->get('Auth/Group'); if ($isNew) { $group = new \Auth\Entity\Group(); } else { if ($this->getRequest()->isPost()) { $data = $this->params()->fromPost('data'); $id = isset($data['id']) ? $data['id'] : false; } else { $id = $this->params()->fromQuery('id', false); } if (!$id) { throw new \RuntimeException('No id.'); } $group = $repository->find($id); } $form->bind($group); if ($this->getRequest()->isPost()) { $form->setData($_POST); $isOk = $form->isValid(); $isUsersOk = !empty($group->users); if ($isOk) { // We have to check here, if there are any users provided // as InputFilter does not allow "required" to be set on fieldsets. if ($isUsersOk) { if ($isNew) { $user = $this->auth()->getUser(); $group->setOwner($user); $groups = $user->getGroups(); $message = /*@translate*/ 'Group created'; $groups->add($group); } else { $message = /*@translate*/ 'Group updated'; } $this->notification()->success($message); return $this->redirect()->toRoute('lang/my-groups'); } } if (!$isUsersOk) { $form->get('data')->get('users')->setNoUsersError(true); } $this->notification()->error(/*@translate*/ 'Changes not saved.'); } return array( 'form' => $form, 'isNew' => $isNew, ); }
Handles the form. Redirects to index on save success. Expected route parameters: - 'mode': string Either 'new' or 'edit'. Expected query parameters: - 'name' string Name of the group (if mode == 'edit') @return Zend\Stdlib\ResponseInterface|array
entailment
public function searchUsersAction() { if (!$this->getRequest()->isXmlHttpRequest()) { throw new \RuntimeException('This action must be called via ajax request'); } $model = new JsonModel(); $query = $this->params()->fromPost('query', false); if (!$query) { $query = $this->params()->fromQuery('q', false); } if (false === $query) { $result = array(); } else { $repositories = $this->repositories; $repository = $repositories->get('Auth/User'); $users = $repository->findByQuery($query); $userFilter = $this->filterManager->get('Auth/Entity/UserToSearchResult'); $filterFunc = function ($user) use ($userFilter) { return $userFilter->filter($user); }; $result = array_values(array_map($filterFunc, $users->toArray())); } //$model->setVariable('users', $result); $model->setVariables($result); return $model; }
Helper action for userselect form element. @return \Zend\View\Model\JsonModel
entailment
public function toHttpQuery() { return '?' . http_build_query( [ 'institution' => $this->institution, 'identityId' => $this->identityId, 'orderBy' => $this->orderBy, 'orderDirection' => $this->orderDirection, 'p' => $this->pageNumber, ] ); }
Return the Http Query string as should be used, MUST include the '?' prefix. @return string
entailment
public function attachShared(SharedEventManagerInterface $events, $priority = 1000) { /* @var $events \Zend\EventManager\SharedEventManager */ $events->attach('Zend\Mvc\Application', MvcEvent::EVENT_BOOTSTRAP, array($this, 'onBootstrap'), $priority); $this->listener = [$this,'onBootstrap']; }
Attach to a shared event manager @param SharedEventManagerInterface $events @param integer $priority
entailment
public function detachShared(SharedEventManagerInterface $events) { if ($events->detach($this->listener,'Zend\Mvc\Application')) { $this->listener = null; } return $this; }
Detach all our listeners from the event manager @param SharedEventManagerInterface $events @return $this
entailment
public function getManagedEntities() { $entities = array(); /** @var \Symfony\Component\HttpKernel\Bundle\BundleInterface $bundle */ foreach ($this->kernel->getBundles() as $bundle) { $entityPath = $bundle->getPath() . '/Entity'; if (is_dir($entityPath)) { $iter = new \RegexIterator( new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($entityPath) ), '/\.php$/' ); foreach ($iter as $file) { $entityName = substr( ltrim(str_replace(realpath($entityPath), '', realpath($file->getPathname())), '/'), 0, -4 ); $alias = Str::classname(get_class($bundle)) . ':' . str_replace('/', '\\', $entityName); try { $repos = $this->doctrine->getRepository($alias); $className = $repos->getClassName(); $classMetaData = $this->metadata->getMetadataForClass($className); foreach ($classMetaData->propertyMetadata as $property => $metadata) { if (isset($metadata->fileManager)) { $entities[] = $alias; break; } } } catch (\Exception $e) { } } } } return $entities; }
Returns all entities having file annotations @return array
entailment
public function setDefaultUser($login, $password, $role = \Auth\Entity\User::ROLE_RECRUITER) { $this->defaultUser = array($login, $password, $role); return $this; }
Sets default user login and password. If no password is provided, @param string $login @param string $password @param string $role (default='recruiter') @return self
entailment
public function authenticate() { /* @var $users \Auth\Repository\User */ $identity = $this->getIdentity(); $users = $this->getRepository(); $user = $users->findByLogin($identity, ['allowDeactivated' => true]); $filter = new CredentialFilter(); $credential = $this->getCredential(); if (!$user || $user->getCredential() != $filter->filter($credential)) { return new Result(Result::FAILURE_CREDENTIAL_INVALID, $identity, array('User not known or invalid credential')); } return new Result(Result::SUCCESS, $user->getId()); }
Performs an authentication attempt {@inheritDoc}
entailment
public function getToken() { if (!$this->token) { $session = new Session('Auth'); if (!$session->token) { $session->token = uniqid(); } $this->token = $session->token; } return $this->token; }
Gets the anonymous identification key. @return string
entailment
public function init() { $this->setName('data') ->setLabel('Group data') ->setUseAsBaseFieldset(true) ->setHydrator(new EntityHydrator()); $this->add( array( 'type' => 'Hidden', 'name' => 'id', ) ); $this->add( array( 'type' => 'Text', 'name' => 'name', 'options' => array( 'label' => /*@translate*/ 'Group name', 'description' => /* @translate */ 'Select a group name. You can add users to your group and then work together on jobs and job applications.', ), ) ); $this->add( array( 'type' => 'Auth/Group/Users', ) ); }
Initialises the fieldset @see \Zend\Form\Element::init()
entailment
public function createDiscriminatorSelection() { $idQueryItems = array(new QueryColumn($this->getIdColumnName(), $this->registerEntityModel($this->entityModel))); $entityModels = array($this->entityModel); foreach ($this->entityModel->getAllSubEntityModels() as $subEntityModel) { $idQueryItems[] = new QueryColumn($this->getIdColumnName(), $this->registerEntityModel($subEntityModel)); $entityModels[] = $subEntityModel; } return new JoinedDiscriminatorSelection($idQueryItems, $entityModels); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\from\meta\TreePointMeta::createDiscriminatorSelection()
entailment
protected function setEntity($entityClass) { $this->repos = $this->doctrine->getRepository($entityClass); $this->className = $this->repos->getClassName(); $this->classMetaData = $this->metadataFactory->getMetadataForClass($this->className); }
Set the Entity being processed. @param string $entityClass @return void
entailment
final protected function log($str, $logLevel = 0) { if (isset($this->logger)) { call_user_func($this->logger, $str, $logLevel); } }
Write a log to the logger @param string $str @param int $logLevel @return void
entailment
public function getAutoloaderConfig() { $addProvidersDir = null; $directories = [ __DIR__.'/../../../../hybridauth/hybridauth/additional-providers', __DIR__.'/../../../../vendor/hybridauth/hybridauth/additional-providers', ]; foreach ($directories as $directory) { if (is_dir($directory)) { $addProvidersDir = $directory; break; } } if (is_null($addProvidersDir)) { throw new InvalidArgumentException('HybridAuth additional providers directories is not found.'); } return array( 'Zend\Loader\ClassMapAutoloader' => array( // This is an hack due to bad design of Hybridauth // This ensures the class from "addtional-providers" is loaded. array( 'Hybrid_Providers_XING' => $addProvidersDir . '/hybridauth-xing/Providers/XING.php', ), array( 'Hybrid_Providers_Github' => $addProvidersDir. '/hybridauth-github/Providers/GitHub.php', ), ), ); }
Loads module specific autoloader configuration. @return array
entailment
public function authenticate() { $hybridAuth = $this->getHybridAuth(); /* @var $adapter \Hybrid_Provider_Model */ $adapter = $hybridAuth->authenticate($this->_provider); $userProfile = $adapter->getUserProfile(); $email = isset($userProfile->emailVerified) && !empty($userProfile->emailVerified) ? $userProfile->emailVerified : $userProfile->email; $forceSave = false; $user = $this->getRepository()->findByProfileIdentifier($userProfile->identifier, $this->_provider, ['allowDeactivated' => true]); if (!$user) { $forceSave = true; $user = $this->getRepository()->create(); } $currentInfo = $user->getProfile($this->_provider); $socialData = []; try { $socialProfile = $this->socialProfilePlugin->fetch($this->_provider); if (false !== $socialProfile) { $socialData = $socialProfile->getData(); } } catch (\InvalidArgumentException $e) {} $newInfo = [ 'auth' => (array) $userProfile, 'data' => $socialData, ]; if ($forceSave || $currentInfo != $newInfo) { $dm = $this->getRepository()->getDocumentManager(); $userInfo = $user->getInfo(); if ('' == $userInfo->getEmail()) { $userInfo->setEmail($email); } $userInfo->setFirstName($userProfile->firstName); $userInfo->setLastName($userProfile->lastName); $userInfo->setBirthDay($userProfile->birthDay); $userInfo->setBirthMonth($userProfile->birthMonth); $userInfo->setBirthYear($userProfile->birthYear); $userInfo->setPostalCode($userProfile->zip); $userInfo->setCity($userProfile->city); $userInfo->setStreet($userProfile->address); $userInfo->setPhone($userProfile->phone); $userInfo->setGender($userProfile->gender); // $user->setLogin($email); // this may cause duplicate key exception $user->addProfile($this->_provider, $newInfo); $dm->persist($user); // make sure all ids are generated and user exists in database. $dm->flush(); /* * This must be after flush because a newly created user has no id! */ if ($forceSave || (!$userInfo->getImage() && $userProfile->photoURL)) { // get user image if ('' != $userProfile->photoURL) { $client = new \Zend\Http\Client($userProfile->photoURL, array('sslverifypeer' => false)); $response = $client->send(); $file = new GridFSFile(); $file->setBytes($response->getBody()); $userImage = new UserImage(); $userImage->setName($userProfile->lastName.$userProfile->firstName); $userImage->setType($response->getHeaders()->get('Content-Type')->getFieldValue()); $userImage->setUser($user); $userImage->setFile($file); $userInfo->setImage($userImage); $dm->persist($userImage); //$this->getRepository()->store($user->info); } // We have to flush again $dm->flush(); } } return new Result(Result::SUCCESS, $user->getId(), array('firstLogin' => $forceSave, 'user' => $user)); }
{@inheritdoc} @see \Zend\Authentication\Adapter\AdapterInterface::authenticate()
entailment
public function getEntityPropertyByName($name) { if (!$this->containsEntityPropertyName($name)) { throw new UnknownEntityPropertyException('Unkown entity property: ' . $this->class->getName() . '::$' . $name); } if (isset($this->properties[$name])) return $this->properties[$name]; return $this->superEntityModel->getEntityPropertyByName($name); }
/* (non-PHPdoc) @see \n2n\persistence\orm\model\EntityPropertyCollection::getEntityPropertyByName()
entailment
public function setExpirationDate($expirationDate) { if (is_string($expirationDate)) { $expirationDate = new \DateTime($expirationDate); } $this->expirationDate = $expirationDate; return $this; }
@param \Datetime|string $expirationDate @return self
entailment
public function createDiscriminatorSelection() { return new SingleTableDiscriminatorSelection( $this->registerColumn($this->entityModel, $this->discriminatorColumnName), $this->discriminatedEntityModels); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\from\meta\TreePointMeta::createDiscriminatorSelection()
entailment
public function getColumnByName(string $name): Column { foreach ($this->columns as $column) { if ($column->getName() == $name) return $column; } throw new UnknownColumnException('Column with name "' . $name . '" does not exist in index "' . $this->name . '" for table "' . $this->table->getName() . '"'); }
{@inheritDoc} @see \n2n\persistence\meta\structure\Index::getColumnByName() @return Column
entailment
public function proceed(InputFilterInterface $filter, Plugin\Mailer $mailer, Url $url) { if (!$filter->isValid()) { throw new \LogicException('Form is not valid'); } $identity = $filter->getValue('identity'); $suffix = $this->loginFilter->filter(); if (!($user = $this->userRepository->findByLoginOrEmail($identity, $suffix))) { throw new UserNotFoundException('User is not found'); } if (!($email = $user->getInfo()->getEmail())) { throw new UserDoesNotHaveAnEmailException('User does not have an email'); } $tokenHash = $this->tokenGenerator->generate($user); $resetLink = $url->fromRoute( 'lang/goto-reset-password', array('token' => $tokenHash, 'userId' => $user->getId()), array('force_canonical' => true) ); $e = new AuthEvent(); $e->setResetLink($resetLink); $e->setUser($user); $this->eventManager->trigger(AuthEvent::EVENT_AUTH_NEWPASSWORD, $e); }
@todo remove unused $mailer parameter an fix tests @param InputFilterInterface $filter @param Plugin\Mailer $mailer @param Url $url @throws \LogicException @throws UserDoesNotHaveAnEmailException @throws UserNotFoundException
entailment
public function getPrimaryKey(): ?Index { // if the table is not persistent so far, it is possible that it doesn't have a Primary Key $primaryKey = null; foreach ($this->getIndexes() as $index) { if ($index->getType() == IndexType::PRIMARY) { if (null === $this->primaryKey) { $primaryKey = $index; } else { throw new MetaRuntimeException('Duplicate primary key in table "' . $this->getName() . '"'); } } } return $primaryKey; }
{@inheritDoc} @see \n2n\persistence\meta\structure\Table::getPrimaryKey() @return Index
entailment
public function createIndex(string $type, array $columnNames, ?string $name = null, ?Table $refTable = null, ?array $refColumnNames = null): Index { $name = $name ?? $this->generateIndexKeyName($type); $this->triggerChangeListeners(); if ($type !== IndexType::FOREIGN) { ArgUtils::assertTrue(empty($refColumnNames) && null === $refTable); $newIndex = CommonIndex::createFromColumnNames($this, $name, $type, $columnNames); } else { if (!$this->isForeignKeyAvailable()) { throw new UnavailableTypeException('Foreign keys are not Supported.'); } $newIndex = ForeignIndex::createFromColumnNames($this, $name, $columnNames, $refTable, $refColumnNames); } $this->addIndex($newIndex); return $newIndex; }
{@inheritDoc} @see \n2n\persistence\meta\structure\Table::createIndex()
entailment
public function prepare() { if ($this->isDisabled()) return; // parent::prepare(); foreach ($this->entityAction->getEntityModel()->getEntityProperties() as $entityProperty) { if (!($entityProperty instanceof CascadableEntityProperty)) continue; $propertyString = $entityProperty->toPropertyString(); $entityProperty->prepareSupplyJob($this, $this->getValue($propertyString), $this->getOldValueHash($propertyString)); } }
}
entailment
public function bindValue($parameter, $value, $dataType = null) { $this->boundValues[$parameter] = $value; if ($dataType !== null) { return parent::bindValue($parameter, $value, $dataType); } else { return parent::bindValue($parameter, $value); } }
(non-PHPdoc) @see PDOStatement::bindValue()
entailment
public function bindParam($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) { $this->boundValues[$parameter] = $variable; return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options); }
(non-PHPdoc) @see PDOStatement::bindParam()
entailment
public function execute($input_parameters = null) { if (is_array($input_parameters)) $this->boundValues = $input_parameters; try { $mtime = microtime(true); $return = parent::execute($input_parameters); if (isset($this->logger)) { $this->logger->addPreparedExecution($this->queryString, $this->boundValues, (microtime(true) - $mtime)); } if (!$return) { $err = error_get_last(); throw new \PDOException($err['message']); } return $return; } catch (\PDOException $e) { throw new PdoPreparedExecutionException($e, $this->queryString, $this->boundValues); } }
(non-PHPdoc) @see PDOStatement::execute()
entailment
public function mergeEntity($entity) { ArgUtils::assertTrue(is_object($entity)); $objHash = spl_object_hash($entity); if (isset($this->mergedEntity[$objHash])) { return $this->mergedEntity[$objHash]; } $em = $this->actionQueue->getEntityManager(); $persistenceContext = $em->getPersistenceContext(); if ($entity instanceof EntityProxy && !$persistenceContext->getEntityProxyManager()->isProxyInitialized($entity)) { return $this->mergedEntity[$objHash] = $entity; } $entityInfo = $em->getPersistenceContext()->getEntityInfo( $entity, $em->getEntityModelManager()); $this->mergedEntity[$objHash] = $mergedEntity = $this->createMergedEntity($entityInfo, $entity); $this->mergeProperties($entityInfo->getEntityModel(), $entity, $mergedEntity); return $mergedEntity; }
/* (non-PHPdoc) @see \n2n\persistence\orm\store\operation\MergeOperation::mergeEntity()
entailment
public function onDispatchError(MvcEvent $e) { $ex = $e->getParam('exception'); $model = $e->getResult(); if ($model instanceof ViewModel && Application::ERROR_EXCEPTION == $e->getError() && 0 === strpos($ex->getMessage(), 'Your application id and secret') ) { $model->setTemplate('auth/error/social-profiles-unconfigured'); } }
Sets a specific view template if social network login is unconfigured. @param MvcEvent $e
entailment
final public function typehintMethod($class, string $method, array $custom = []) { $className = get_class($class); $reflectionMethod = new ReflectionMethod($className, $method); $reflectionParameters = $reflectionMethod->getParameters(); $params = $this->resolveParams($reflectionParameters, $custom); return call_user_func_array( [ $class, $method ], $params ); }
Typehint a class method.
entailment
final public function typehintFunction(string $functionName, array $custom = []) { $reflectionFunction = new ReflectionFunction($functionName); $reflectionParameters = $reflectionFunction->getParameters(); $params = $this->resolveParams($reflectionParameters, $custom); return call_user_func_array( $functionName, $params ); }
Typehint a function.
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('zicht_file_manager'); $rootNode->children() // Default behaviour is to lower case file names ->scalarNode('case_preservation')->defaultFalse(); $rootNode->children()->scalarNode('naming_strategy')->defaultValue(DefaultNamingStrategy::class); return $treeBuilder; }
Generates the configuration tree builder. @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
entailment
public function move($object, $parentObject = null) { $this->em->flush(); if ($parentObject !== null) { $this->valMove($object, $parentObject); } $newLft = 1; if ($parentObject === null) { if (null !== ($maxRgt = $this->lookupMaxRgt($object))) { $newLft = $maxRgt + 1; } } else { $newLft = $this->lookupLftRgt($parentObject)['rgt']; } $this->moveToLft($object, $newLft); }
@link https://rogerkeays.com/how-to-move-a-node-in-nested-sets-with-sql @param object $object @param object $parentObject @throws IllegalStateException
entailment
protected function reset() { IllegalStateException::assertTrue(!$this->init); $this->whenInitializedClosures = array(); while (null !== ($closure = array_shift($this->onResetClosures))) { $closure(); } $this->init = false; }
}
entailment
public function buildJunctionJoinColumnName(\ReflectionClass $targetClass, string $targetIdPropertyName, string $joinColumnName = null): string { if ($joinColumnName !== null) return $joinColumnName; return $targetClass->getShortName() . $targetIdPropertyName; }
/* (non-PHPdoc) @see \n2n\persistence\orm\model\NamingStrategy::buildJunctionJoinColumnName()
entailment
public function createValueBuilder() { try { return new EagerValueBuilder($this->ormDialectConfig->parseDateTime($this->value)); } catch (\InvalidArgumentException $e) { throw new CorruptedDataException(null, 0, $e); } }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::createValueBuilder()
entailment
public function setModificationDate($modificationDate = null) { if (!isset($modificationDate)) { $modificationDate = new \DateTime(); } if (is_string($modificationDate)) { $modificationDate = new \DateTime($modificationDate); } $this->modificationDate = $modificationDate; return $this; }
@param \Datetime|string $modificationDate @return self
entailment
public function buildJunctionJoinColumnName(\ReflectionClass $targetClass, string $targetIdPropertyName, string $joinColumnName = null): string { if ($joinColumnName !== null) return $joinColumnName; return StringUtils::hyphenated($targetClass->getShortName() . ucfirst($targetIdPropertyName)); }
/* (non-PHPdoc) @see \n2n\persistence\orm\model\NamingStrategy::buildJunctionJoinColumnName()
entailment
public function buildJoinColumnName(string $propertyName, string $targetIdPropertyName, string $joinColumnName = null): string { if ($joinColumnName !== null) return $joinColumnName; return StringUtils::hyphenated($propertyName . ucfirst($targetIdPropertyName)); }
/* (non-PHPdoc) @see \n2n\persistence\orm\model\NamingStrategy::buildJoinColumnName()
entailment
public function hydrate(array $data, $object) { foreach ($data as $name => $value) { if (!isset($this->profileClassMap[$name])) { continue; } if (empty($value)) { // We need to check, if collection has a profile and // remove it. foreach ($object as $p) { if ($p instanceof $this->profileClassMap[$name]) { $object->removeElement($p); continue 2; } } // No profile found, so do nothing. continue; } if (is_string($value)) { $value = \Zend\Json\Json::decode($value, \Zend\Json\Json::TYPE_ARRAY); } /* If there is already a profile of this type, we do not need to * add it, but update the data only. */ foreach ($object as $p) { if ($p instanceof $this->profileClassMap[$name]) { // Already a profile in the collection, just update and continue main loop. $p->setData($value); continue 2; } } // We need to add a new profile to the collection. $class = $this->profileClassMap[$name]; $profile = new $class(); $profile->setData($value); $object->add($profile); } return $object; }
Adds or removes a social profile from the collection. @param array $data @param Collection $object @see \Zend\Hydrator\HydratorInterface::hydrate() @return \Auth\Entity\SocialProfiles\ProfileInterface
entailment
public function extract($object) { $return = array(); foreach ($object as $profile) { $return[strtolower($profile->getName())] = $profile->getData(); } return $return; }
Extracts profile data from the collection. @param Collection $object @return array profile data in the format [profile name] => [profile data]. @see \Zend\Hydrator\HydratorInterface::extract()
entailment
public function createPropertyJoinedTreePoint(string $propertyName, $joinType): JoinedTreePoint { return $this->createCustomPropertyJoinTreePoint( $this->entityPropertyCollection->getEntityPropertyByName($propertyName), $joinType); }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\from\ExtendableTreePoint::createJoinTreePoint()
entailment
public function findBy(array $criteria, array $sort = null, $limit = null, $skip = null) { if (!array_key_exists('isDraft', $criteria)) { $criteria['isDraft'] = false; } elseif (null === $criteria['isDraft']) { unset($criteria['isDraft']); } if (!array_key_exists('status.name', $criteria)) { $criteria['status.name'] = \Jobs\Entity\StatusInterface::ACTIVE; } elseif (null === $criteria['status.name']) { unset($criteria['status.name']); } return parent::findBy($criteria, $sort, $limit, $skip); }
{@inheritDoc}
entailment
public function find($id, $lockMode = \Doctrine\ODM\MongoDB\LockMode::NONE, $lockVersion = null, array $options = []) { return $this->assertEntity(parent::find($id, $lockMode, $lockVersion), $options); }
Finds a document by its identifier @param string|object $id The identifier @param int $lockMode @param int $lockVersion @param array $options @throws Mapping\MappingException @throws LockException @throws UserDeactivatedException @return null | UserInterface
entailment
public function create(array $data = null, $persist=false) { $entity = parent::create($data); $eventArgs = new LifecycleEventArgs($entity, $this->dm); $this->dm->getEventManager()->dispatchEvent( Events::postLoad, $eventArgs ); return $entity; }
Creates a User @see \Core\Repository\AbstractRepository::create() @return UserInterface
entailment
public function findByProfileIdentifier($identifier, $provider, array $options = []) { return $this->findOneBy(array('profiles.' . $provider . '.auth.identifier' => $identifier), $options) ?: $this->findOneBy(array('profile.identifier' => $identifier), $options); }
Finds user by profile identifier @param string $identifier @param string $provider @param array $options @return UserInterface
entailment
public function isProfileAssignedToAnotherUser($curentUserId, $identifier, $provider) { $qb = $this->createQueryBuilder(null); $qb->field('_id')->notEqual($curentUserId) ->addAnd( $qb->expr() ->addOr($qb->expr()->field('profiles.' . $provider . '.auth.identifier' )->equals($identifier)) ->addOr($qb->expr()->field('profile.identifier')->equals($identifier)) ); return $qb->count() ->getQuery() ->execute() > 0; }
Returns true if profile is already assigned to anotherUser @param int $curentUserId @param string $identifier @param string $provider @return bool
entailment
public function findByEmail($email, $isDraft = false) { $entity = $this->findOneBy( array( '$or' => array( array('email' => $email), array('info.email' => $email), ), 'isDraft' => $isDraft, ) ); return $entity; }
@param $email @param bool $isDraft @return UserInterface|null
entailment
public function findByQuery($query) { $qb = $this->createQueryBuilder(); $parts = explode(' ', trim($query)); foreach ($parts as $q) { $regex = new \MongoRegex('/^' . $query . '/i'); $qb->addOr($qb->expr()->field('info.firstName')->equals($regex)); $qb->addOr($qb->expr()->field('info.lastName')->equals($regex)); $qb->addOr($qb->expr()->field('info.email')->equals($regex)); } $qb->sort(array('info.lastName' => 1)) ->sort(array('info.email' => 1)); return $qb->getQuery()->execute(); }
Find user by query @param String $query @deprecated since 0.19 not used anymore and probably broken. @return object
entailment
public function copyUserInfo(Info $info) { $contact = new Info(); $contact->fromArray(Info::toArray($info)); }
Copy user info into the applications info Entity @param \Auth\Entity\Info $info
entailment
public function createValueBuilder() { try { return new EagerValueBuilder(Url::build($this->value)); } catch (\InvalidArgumentException $e) { throw new \InvalidArgumentException(null, 0, $e); } }
/* (non-PHPdoc) @see \n2n\persistence\orm\query\select\Selection::createValueBuilder()
entailment
public function isAvailable() { if (!empty($this->adapter)) { // adapter is already etablished return true; } $user = $this->getUser(); $sessionDataStored = $user->getAuthSession($this->providerKey); if (empty($sessionDataStored)) { // for this user no session has been stored return false; } $hybridAuth = $this->getHybridAuth(); $hybridAuth->restoreSessionData($sessionDataStored); if ($hybridAuth->isConnectedWith($this->providerKey)) { return true; } return false; }
for backend there is only one possibility to get a connection, and that is by stored Session @return bool
entailment
public function getAdapter() { if (empty($this->adapter)) { $user = $this->getUser(); $sessionDataStored = $user->getAuthSession($this->providerKey); $hybridAuth = $this->getHybridAuth(); if (!empty($sessionDataStored)) { $hybridAuth->restoreSessionData($sessionDataStored); } $adapter = $hybridAuth->authenticate($this->providerKey); $sessionData = $hybridAuth->getSessionData(); if ($sessionData != $sessionDataStored) { $user->updateAuthSession($this->providerKey, $sessionData); } $this->adapter = $adapter; } return $this->adapter; }
everything relevant is happening here, included the interactive registration if the User already has a session, it is retrieved
entailment
public function sweepProvider() { $user = $this->getUser(); $hybridAuth = $this->getHybridAuth(); // first test, if there is a connection at all // that prevents an authentification just for to logout if ($hybridAuth->isConnectedWith($this->providerKey)) { $this->getAdapter($this->providerKey)->logout(); } $user->removeSessionData($this->providerKey); unset($this->adapter); return $this; }
logout and clears the stored Session,
entailment