/** * Is allowed view page * * @param array $privacyOptions * @param boolean $trustedData * @return boolean */ public function isAllowedViewPage(array $privacyOptions = [], $trustedData = false) { // check a permission if (!AclService::checkPermission('news_view_news', false)) { return false; } return true; }
/** * Is allowed view page * * @param array $privacyOptions * @param boolean $trustedData * @return boolean */ public function isAllowedViewPage(array $privacyOptions = [], $trustedData = false) { // check a permission if (UserIdentityService::isDefaultUser() || !AclService::checkPermission('memberships_view_buy_page', false)) { return false; } return true; }
/** * Get list of localizations * * @throws XmlRpc\Exception\XmlRpcActionDenied * @return array */ public function getLocalizations() { // check user permission if (!AclService::checkPermission('xmlrpc_get_localizations')) { throw new XmlRpcActionDenied(self::REQUEST_DENIED); } // fire the get localizations via XmlRpc event LocalizationEvent::fireGetLocalizationsViaXmlRpcEvent(); return LocalizationService::getLocalizations(); }
/** * Check current user's permission. * * @param string $resource * @param boolean $increaseActions * @param boolean $showAccessDenied * @return boolean */ public function __invoke($resource = null, $increaseActions = true, $showAccessDenied = true) { // get an ACL resource name $resource = !$resource ? $this->getController()->params('controller') . ' ' . $this->getController()->params('action') : $resource; // check the permission if (false === ($result = AclService::checkPermission($resource, $increaseActions)) && $showAccessDenied) { // redirect to access a forbidden page $this->getController()->showErrorPage(); } return $result; }
/** * Get widget content * * @return string|boolean */ public function getContent() { if (AclService::checkPermission('slideshow_view', false) && null != ($category = $this->getWidgetSetting('slideshow_category'))) { $images = $this->getModel()->getImages($category); if (count($images)) { AclService::checkPermission('slideshow_view', true); return $this->getView()->partial('slideshow/widget/slideshow', ['enable_slideshow' => (int) $this->getWidgetSetting('slideshow_on'), 'images_width' => (int) $this->getWidgetSetting('slideshow_image_width'), 'images_height' => (int) $this->getWidgetSetting('slideshow_image_height'), 'images' => $images]); } } return false; }
/** * Get widget content * * @return string|boolean */ public function getContent() { // check a permission if (AclService::checkPermission('news_view_news', false) && false !== $this->getView()->pageUrl('news', [], null, true)) { // get widget settings $this->newsCategories = $this->getWidgetSetting('news_categories_last_news'); $this->newsCount = (int) $this->getWidgetSetting('news_count_last_news'); // select the widget mode return !$this->newsCount ? $this->paginationMode() : $this->simpleMode(); } return false; }
/** * Get user info * * @param integer $userId * @return array */ public function getUserInfo($userId) { // check user permissions if (!AclService::checkPermission('xmlrpc_view_user_info')) { throw new XmlRpcActionDenied(self::REQUEST_DENIED); } $viewerNickName = !UserIdentityService::isGuest() ? $this->userIdentity['nick_name'] : null; // get user info if (false !== ($userInfo = $this->getModel()->getXmlRpcUserInfo($userId, $this->userIdentity['user_id'], $viewerNickName))) { return $userInfo; } return []; }
/** * Get widget content * * @return string|boolean */ public function getContent() { if (AclService::checkPermission('comment_view', false)) { // get last comments $comments = $this->getModel()->getLastComments($this->getCurrentLanguage(), (int) $this->getWidgetSetting('comment_count')); if (count($comments)) { // increase ACL track AclService::checkPermission('comment_view'); return $this->getView()->partial('comment/widget/last-comments-list', ['visible_chars' => (int) $this->getWidgetSetting('comment_visible_chars'), 'show_thumbs' => (int) $this->getWidgetSetting('comment_show_thumbs'), 'comments' => $comments]); } } return false; }
/** * Index page */ public function indexAction() { if (!UserIdentityService::isGuest()) { return $this->createHttpNotFoundModel($this->getResponse()); } $this->layout($this->layout); $loginForm = $this->getServiceLocator()->get('Application\\Form\\FormManager')->getInstance('User\\Form\\UserLogin'); if ($this->getRequest()->isPost()) { // fill form with received values $loginForm->getForm()->setData($this->getRequest()->getPost()); if ($loginForm->getForm()->isValid()) { $userName = $this->getRequest()->getPost('nickname'); $password = $this->getRequest()->getPost('password'); // check an authentication $authErrors = []; $result = UserAuthenticateUtility::isAuthenticateDataValid($userName, $password, $authErrors); if (false === $result) { $this->flashMessenger()->setNamespace('error'); // add auth error messages foreach ($authErrors as $message) { $this->flashMessenger()->addMessage($this->getTranslator()->translate($message)); } return $this->reloadPage(); } $rememberMe = null != ($remember = $this->getRequest()->getPost('remember')) ? true : false; // login a user UserAuthenticateUtility::loginUser($result['user_id'], $result['nick_name'], $rememberMe); // make a redirect if (null !== ($backUrl = $this->getRequest()->getQuery('back_url', null))) { return $this->redirect()->toUrl($backUrl); } // search a first allowed admin page $adminMenu = $this->getAdminMenuModel()->getMenu(); foreach ($adminMenu as $menuItems) { foreach ($menuItems['items'] as $item) { if (AclService::checkPermission($item['controller'] . ' ' . $item['action'], false)) { return $this->redirectTo($item['controller'], $item['action']); } } } // redirect to the public home page $this->flashMessenger()->setNamespace('error'); $this->flashMessenger()->addMessage($this->getTranslator()->translate('There are no admin pages allowed for you!')); return $this->redirectTo('page', 'index', [], false, [], 'page'); } } return new ViewModel(['loginForm' => $loginForm->getForm()]); }
/** * Set event manager * * @param \Zend\EventManager\EventManagerInterface $events * @return void */ public function setEventManager(EventManagerInterface $events) { parent::setEventManager($events); $controller = $this; // execute before executing action logic $events->attach('dispatch', function ($e) use($controller) { // check permission if (!AclService::checkPermission($controller->params('controller') . ' ' . $controller->params('action'), false)) { return UserIdentityService::isGuest() ? $this->redirectTo('login-administration', 'index', [], false, ['back_url' => $this->getRequest()->getRequestUri()]) : $controller->showErrorPage(); } // set an admin layout if (!$e->getRequest()->isXmlHttpRequest()) { $controller->layout($this->layout); } }, 100); }
/** * Get widget content * * @return string|boolean */ public function getContent() { if (AclService::checkPermission('comment_view', false)) { // get the current user's info if (null != ($userInfo = UserIdentityService::getUserInfo($this->getSlug(), BaseModel::USER_INFO_BY_SLUG))) { // get last comments $comments = $this->getModel()->getLastComments($this->getCurrentLanguage(), (int) $this->getWidgetSetting('comment_count'), $userInfo['user_id']); if (count($comments)) { // increase ACL track AclService::checkPermission('comment_view'); return $this->getView()->partial('comment/widget/user-last-comments-list', ['visible_chars' => $this->getWidgetSetting('comment_visible_chars'), 'comments' => $comments]); } } } return false; }
/** * Is allowed view page * * @param array $privacyOptions * @param boolean $trustedData * @return boolean */ public function isAllowedViewPage(array $privacyOptions = [], $trustedData = false) { // check a permission if (!AclService::checkPermission('news_view_news', false)) { return false; } // get a news id from the route or params if (!$trustedData) { $newsId = $this->objectId ? $this->objectId : RouteParamUtility::getParam('slug', -1); // check an existing news if (null == ($newsInfo = $this->getModel()->getNewsInfo($newsId, true, false, 'slug', true))) { return false; } } return true; }
/** * Get widget content * * @return string|boolean */ public function getContent() { // check a permission if (AclService::checkPermission('users_view_profile')) { // get the current user's info if (null != ($userInfo = $this->getModel()->getUserInfo($this->getSlug(), UserWidgetModel::USER_INFO_BY_SLUG))) { $viewerNickName = !UserIdentityService::isGuest() ? UserIdentityService::getCurrentUserIdentity()['nick_name'] : null; // fire the get user's info event UserEvent::fireGetUserInfoEvent($userInfo['user_id'], $userInfo['nick_name'], UserIdentityService::getCurrentUserIdentity()['user_id'], $viewerNickName); // breadcrumb $this->getView()->pageBreadcrumb()->setCurrentPageTitle($userInfo['nick_name']); $this->getView()->headMeta()->setName('description', $userInfo['nick_name']); return $this->getView()->partial('user/widget/info', ['user' => $userInfo]); } } return false; }
/** * Is allowed view page * * @param array $privacyOptions * @param boolean $trusted * @return boolean */ public function isAllowedViewPage(array $privacyOptions = [], $trustedData = false) { // check a permission if (!AclService::checkPermission('users_view_profile', false)) { return false; } if (!$trustedData) { $userId = !empty($privacyOptions['user_id']) || $this->objectId ? !empty($privacyOptions['user_id']) ? $privacyOptions['user_id'] : $this->objectId : RouteParamUtility::getParam('slug', -1); $userField = !empty($privacyOptions['user_id']) ? UserWidgetModel::USER_INFO_BY_ID : UserWidgetModel::USER_INFO_BY_SLUG; // check an existing user $userInfo = $this->getModel()->getUserInfo($userId, $userField); if (!$userInfo || $userInfo['status'] != UserWidgetModel::STATUS_APPROVED) { return false; } } return true; }
/** * Get widget content * * @return string|boolean */ public function getContent() { $disableRating = !AclService::checkPermission('pages_use_rating') || $this->getModel()->isPageRated($this->pageId, $this->getPageSlug()); // process actions if ($this->getRequest()->isPost() && ApplicationCsrf::isTokenValid($this->getRequest()->getPost('csrf'))) { if (false !== ($action = $this->getRequest()->getPost('widget_action', false)) && $this->getRequest()->isXmlHttpRequest()) { switch ($action) { case 'add_rating': return $this->getView()->json($this->addPageRating($disableRating)); default: } } } // get current page's rating info $pageRating = $this->getModel()->getPageRatingInfo($this->pageId, $this->getPageSlug()); $currentRating = $pageRating ? $this->processRatingValue($pageRating['total_rating'] / $pageRating['total_count']) : 0; return $this->getView()->partial('page/widget/rating', ['csrf' => ApplicationCsrf::getToken(), 'rating' => $currentRating, 'widget_url' => $this->getWidgetConnectionUrl(), 'big_rating' => $this->getWidgetSetting('page_rating_size') == 'big_rating', 'step_rating' => (double) $this->getWidgetSetting('page_rating_min_step'), 'disable_rating' => $disableRating]); }
/** * Class constructor * * @param array $menu */ public function __construct(array $menu = []) { if ($menu) { // check menu permissions foreach ($menu as $menuPart => $menuInfo) { foreach ($menuInfo['items'] as $menuItem) { // check a permission if (!AclService::checkPermission($menuItem['controller'] . ' ' . $menuItem['action'], false)) { continue; } if (!isset($this->menu[$menuPart])) { $this->menu[$menuPart] = ['part' => $menuInfo['part'], 'icon' => $menuInfo['icon'], 'module' => $menuInfo['module'], 'items' => [0 => ['name' => $menuItem['name'], 'controller' => $menuItem['controller'], 'action' => $menuItem['action'], 'category' => $menuItem['category'], 'category_icon' => $menuItem['category_icon'], 'category_module' => $menuItem['category_module']]]]; } else { $this->menu[$menuPart]['items'][] = ['name' => $menuItem['name'], 'controller' => $menuItem['controller'], 'action' => $menuItem['action'], 'category' => $menuItem['category'], 'category_icon' => $menuItem['category_icon'], 'category_module' => $menuItem['category_module']]; } } } } }
/** * Get widget content * * @return string|boolean */ public function getContent() { // check a permission if (AclService::checkPermission('news_view_news', false)) { $calendar = $this->getView()->applicationCalendar(); // set calendar options $calendar->setUrl($this->getWidgetConnectionUrl(['month', 'year']))->setWrapperId('news-calendar'); if (null !== ($month = $this->getRequest()->getQuery('month', null))) { $calendar->setMonth($month); } if (null !== ($year = $this->getRequest()->getQuery('year', null))) { $calendar->setYear($year); } $categoryFilter = $this->isNewsListPage() ? $this->getRouteParam('category') : null; // get calendar news if (null != ($news = $this->getModel()->getCalendarNews($calendar->getStartDate(), $calendar->getEndDate(), $categoryFilter))) { $calendarLinks = []; $pageName = $this->getView()->pageUrl(self::NEWS_LIST_PAGE); $routeParams = []; $routeQueries = []; // save all router params and queries on the 'news-list' page if ($this->isNewsListPage()) { $routeParams = $this->getView()->applicationRoute()->getAllDefaultRouteParams(); $routeQueries = $this->getView()->applicationRoute()->getQuery(); // remove this widget's specific params from queries $routeQueries = array_merge($routeQueries, ['month' => null, 'year' => null, 'widget_connection' => null, 'widget_position' => null, '_' => null]); } // process list of news foreach ($news as $newsInfo) { $date = str_replace('-', '/', $newsInfo->news_date); $title = sprintf($this->getView()->translatePlural('count one news', 'count many news', $newsInfo->news_count), $newsInfo->news_count); $calendarLinks[$newsInfo->news_date] = ['title' => $title, 'url' => $this->getView()->url('page', array_merge($routeParams, ['page_name' => $pageName, 'date' => $date]), ['force_canonical' => true, 'query' => $routeQueries])]; } $calendar->setLinks($calendarLinks); } if ($this->getRequest()->isXmlHttpRequest()) { return $calendar->getCalendar(); } return $this->getView()->partial('news/widget/calendar', ['calendar' => $calendar->getCalendar()]); } return false; }
/** * Get widget content * * @return string|boolean */ public function getContent() { if (null != ($questionId = $this->getWidgetSetting('poll_question'))) { // get a question info if (null != ($questionInfo = $this->getModel()->getQuestionInfo($questionId))) { // get list of answers $answers = $this->getModel()->getAnswers($questionId); $isVotingDisabled = $this->getModel()->isAnswerVoteExist($questionId) || !AclService::checkPermission('polls_make_votes', false); if (count($answers) > 1) { // process post actions if ($this->getRequest()->isPost() && ApplicationCsrf::isTokenValid($this->getRequest()->getPost('csrf'))) { if (false !== ($action = $this->getRequest()->getPost('widget_action', false)) && $this->getRequest()->isXmlHttpRequest()) { switch ($action) { case 'make_vote': if (false !== ($answerId = $this->getRequest()->getPost('answer_id', false)) && !$isVotingDisabled) { if (true === ($result = $this->getModel()->addAnswerVote($questionId, $answerId))) { // increase acl track AclService::checkPermission('polls_make_votes'); } } return $this->getView()->json(['data' => $this->getPollResult($questionId, $answers)]); default: } } } // process get actions if (false !== ($action = $this->getRequest()->getQuery('widget_action', false)) && $this->getRequest()->isXmlHttpRequest()) { switch ($action) { case 'get_answers': return $this->getView()->json(['data' => $this->getPollAnswers($answers, $isVotingDisabled)]); case 'get_results': default: return $this->getView()->json(['data' => $this->getPollResult($questionId, $answers)]); } } return $this->getView()->partial('poll/widget/poll-init', ['csrf' => ApplicationCsrf::getToken(), 'widget_url' => $this->getWidgetConnectionUrl(), 'connection_id' => $this->widgetConnectionId, 'question_info' => $questionInfo, 'answers' => $this->getPollAnswers($answers, $isVotingDisabled)]); } } } return false; }
/** * Get widget content * * @return string|boolean */ public function getContent() { // check a permission if (AclService::checkPermission('news_view_news')) { // get a news info if (null != ($newsInfo = $this->getModel()->getNewsInfo($this->getSlug(), true, false, 'slug', true))) { // set breadcrumb and default metas $this->getView()->pageBreadcrumb()->setCurrentPageTitle($newsInfo['title']); $this->getView()->layout()->setVariables(['defaultMetaDescription' => $newsInfo['title'], 'defaultMetaKeywords' => $newsInfo['title']]); // set meta keywords if ($newsInfo['meta_keywords']) { $this->getView()->headMeta()->setName('keywords', $newsInfo['meta_keywords']); } // set meta description if ($newsInfo['meta_description']) { $this->getView()->headMeta()->setName('description', $newsInfo['meta_description']); } return $this->getView()->partial('news/widget/news-info', ['news' => $newsInfo, 'categories' => $this->getModel()->getNewsCategories($newsInfo['id'])]); } } return false; }
/** * Get widget content * * @return string|boolean */ public function getContent() { if (AclService::checkPermission('miniphotogallery_view', false) && null != ($category = $this->getWidgetSetting('miniphotogallery_category'))) { // get a pagination page number $pageParamName = 'page_' . $this->widgetConnectionId; $page = $this->getView()->applicationRoute()->getQueryParam($pageParamName, 1); $paginator = $this->getModel()->getImages($page, $category, (int) $this->getWidgetSetting('miniphotogallery_per_page')); if ($paginator->count()) { AclService::checkPermission('miniphotogallery_view', true); $galleryWrapperId = 'mini-photo-gallery-list-' . $this->widgetConnectionId; // get data list $dataList = $this->getView()->partial('partial/data-list', ['ajax' => ['wrapper_id' => $galleryWrapperId, 'widget_connection' => $this->widgetConnectionId, 'widget_position' => $this->widgetPosition], 'paginator' => $paginator, 'paginator_page_query' => $pageParamName, 'unit' => 'mini-photo-gallery/partial/_photo-unit', 'unit_params' => ['thumbs_width_medium' => $this->getWidgetSetting('miniphotogallery_thumbs_width_medium'), 'thumbs_width_small' => $this->getWidgetSetting('miniphotogallery_thumbs_width_small'), 'thumbs_width_extra_small' => $this->getWidgetSetting('miniphotogallery_thumbs_width_extra_small')], 'uniform_height' => '#' . $galleryWrapperId . ' .thumbnail']); // add an init script $content = $this->getView()->partial('mini-photo-gallery/widget/_photos-list-init', ['wrapper' => $galleryWrapperId, 'data' => $dataList, 'title_type' => $this->getWidgetSetting('miniphotogallery_title_type')]); if ($this->getRequest()->isXmlHttpRequest()) { return $content; } // wrap all data return $this->getView()->partial('mini-photo-gallery/widget/photos-list', ['wrapper' => $galleryWrapperId, 'data' => $content]); } } return false; }
/** * Check routes permission * * @param array $routes * string controller required * string action required * boolean check_acl optional * string acl_resource optional * @param boolean $increaseActions * @param boolean $collectDisallowed * @return array */ public function __invoke(array $routes, $increaseActions = false, $collectDisallowed = false) { $processedRoutes = []; // process routes foreach ($routes as $route) { // check a route acl if (isset($route['check_acl']) && $route['check_acl'] === true) { $aclResource = !empty($route['acl_resource']) ? $route['acl_resource'] : $route['controller'] . ' ' . $route['action']; // check permission for the specific controller and action // check a permission if (!AclService::checkPermission($aclResource, $increaseActions)) { if (!$collectDisallowed) { continue; } else { $route['permission'] = false; } } } // fill actions $processedRoutes[] = $route; } return $processedRoutes; }
/** * Test acl by date */ public function testAclByDate() { $role = AclModelBase::DEFAULT_ROLE_MEMBER; $testResources = ['test_application_settings_administration', 'test_application_modules_administration']; $this->addAclResources($testResources, true, $role); $currentTime = time(); // add acl resources connections settings foreach ($this->aclResourcesConnections as $connectId) { $query = $this->aclModelBase->insert()->into('acl_resource_connection_setting')->values(['connection_id' => $connectId, 'user_id' => $this->userId, 'date_start' => $currentTime, 'date_end' => $currentTime + 1]); $statement = $this->aclModelBase->prepareStatementForSqlObject($query); $statement->execute(); } $this->initAcl($role); // all created acl resources must be active foreach ($testResources as $resource) { $this->assertTrue(AclService::checkPermission($resource)); } // wait two seconds and check acl resources again sleep(2); $this->initAcl($role); // now all created acl resources must be expired foreach ($testResources as $resource) { $this->assertFalse(AclService::checkPermission($resource)); } }
/** * Get comments list * * @param boolean $allowApprove * @param boolean $getTree * @param integer $lastRightKey * @param boolean $asArray * @param array $ownReplies * @return string|array */ protected function getCommentsList($allowApprove, $getTree = true, $lastRightKey = null, $asArray = false, $ownReplies = null) { // get comments $commentsList = $this->getModel()->getComments($allowApprove, $this->pageId, (int) $this->getWidgetSetting('comment_per_page'), $this->getPageSlug(), $getTree, $lastRightKey, $ownReplies); // process comments if (null != ($commentsList = $this->processComments($commentsList, $asArray))) { // increase ACL track AclService::checkPermission('comment_view'); } return $commentsList; }
/** * Check permission * * @param string $resource * @param boolean $increaseActions * @return boolean */ public function __invoke($resource, $increaseActions = false) { return AclService::checkPermission($resource, $increaseActions); }
/** * Class constructor * * @param string $formName * @param array $formElements * string name required * string type required * string label optional * string description optional * array description_params optional * string category label optional * integer max_length optional * integer min_length optional * boolean|integer required optional * string value optional * array values required for radios, multicheckboxes and selects * string values_provider (PHP function that returns the list of values) * array attributes optional * array filters optional * array validators optional * array extra_options optional * @param object $translator * @param string $method * @param array $ignoredElements * @throws Zend\Form\Exception\InvalidArgumentException */ public function __construct($formName, array $formElements, Translator $translator, array $ignoredElements = [], array $notValidatedElements = [], $method = 'post') { parent::__construct($formName); $useFilters = true; $this->setAttribute('method', $method == 'post' ? $method : 'get'); // ignored elements $this->ignoredElements = array_merge(['csrf', 'submit'], $ignoredElements); // not validated elements $this->notValidatedElements = $notValidatedElements; $this->translator = $translator; $this->inputFilter = new InputFilter(); $this->inputFactory = new InputFactory(); // add elements foreach ($formElements as $element) { $elementType = isset($element['type']) ? $element['type'] : null; $elementName = isset($element['name']) ? $element['name'] : null; $elementRequired = !empty($element['required']) ? true : false; $elementValue = isset($element['value']) ? $element['value'] : null; $elementValues = isset($element['values']) ? $element['values'] : []; $elementAttrs = isset($element['attributes']) && is_array($element['attributes']) ? $element['attributes'] : []; $elementAttrs = array_merge(['class' => 'form-control'], $elementAttrs); if (!empty($element['values_provider'])) { $valuesProvider = eval($element['values_provider']); if (!is_array($valuesProvider)) { throw new InvalidArgumentException('Values provider should return only an array'); } $elementValues = $elementValues + $valuesProvider; } if (!$elementType || !$elementName) { throw new InvalidArgumentException('Type and name are required'); } // remember all elements $this->customElements[$elementName] = $elementType; // list of default element validators $elementValidators = []; $extraOptions = []; $applyLengthValidator = false; switch ($elementType) { case self::FIELD_NOTIFICATION_MESSAGE: case self::FIELD_HTML_AREA: $applyLengthValidator = true; // add custom filters $element['filters'] = array_merge(isset($element['filters']) ? $element['filters'] : [], [['name' => 'StringTrim'], ['name' => 'callback', 'options' => ['callback' => function ($value) { $config = \HTMLPurifier_Config::createDefault(); $config->set('Cache.DefinitionImpl', null); $config->set('HTML.SafeObject', true); $config->set('Output.FlashCompat', true); $purifier = new \HTMLPurifier($config); // clear js return AclService::checkPermission('application_use_js') ? $value : $purifier->purify($value); }]]]); $elementAttrs = array_merge($elementAttrs, ['class' => 'htmlarea', 'required' => false]); $elementType = 'Textarea'; break; case self::FIELD_DATE: case self::FIELD_DATE_UNIXTIME: $elementValidators[] = ['name' => 'dateTime', 'options' => ['dateType' => IntlDateFormatter::MEDIUM]]; $elementAttrs = array_merge($elementAttrs, ['class' => 'date form-control']); $elementValue = LocaleUtility::convertToLocalizedValue($elementValue, $elementType); $elementType = 'Text'; break; case self::FIELD_SELECT: case self::FIELD_RADIO: $elementValidators[] = ['name' => 'inArray', 'options' => ['haystack' => array_keys($elementValues)]]; // add an empty value if ($elementType == self::FIELD_SELECT) { $elementValues = ['' => ''] + $elementValues; } if ($elementType == self::FIELD_RADIO) { $elementAttrs = array_merge($elementAttrs, ['class' => '']); } $elementType = $elementType == self::FIELD_SELECT ? 'Select' : 'Radio'; break; case self::FIELD_MULTI_SELECT: case self::FIELD_MULTI_CHECKBOX: if ($elementType == self::FIELD_MULTI_SELECT) { $elementAttrs = array_merge($elementAttrs, ['multiple' => true]); } $elementValidators[] = ['name' => 'callback', 'options' => ['message' => 'The input was not found in the haystack', 'callback' => function ($values) use($elementValues) { if (!is_array($values)) { return false; } foreach ($values as $value) { if (!array_key_exists($value, $elementValues)) { return false; } } return true; }]]; $useFilters = false; if ($elementType == self::FIELD_MULTI_CHECKBOX) { $extraOptions = ['unchecked_value' => '', 'use_hidden_element' => true]; $elementAttrs = array_merge($elementAttrs, ['class' => '']); $elementAttrs = array_merge(['required' => false], $elementAttrs); $elementType = 'MultiCheckbox'; } else { $elementType = 'Select'; } break; case self::FIELD_CHECKBOX: $extraOptions = ['checked_value' => 1, 'unchecked_value' => '', 'use_hidden_element' => true]; $elementValidators[] = ['name' => 'inArray', 'options' => ['haystack' => [1]]]; if ($elementRequired) { $elementValidators[] = ['name' => 'callback', 'options' => ['message' => 'You need to select the checkbox', 'callback' => function ($value) { return (int) $value >= 1; }]]; } $elementAttrs = array_merge($elementAttrs, ['class' => '']); $elementType = 'Checkbox'; break; case self::FIELD_HIDDEN: $applyLengthValidator = true; $elementType = 'Hidden'; break; case self::FIELD_FILE: $elementAttrs = array_merge($elementAttrs, ['class' => '']); $elementType = 'File'; $useFilters = false; break; case self::FIELD_IMAGE: $validExtensions = ['gif', 'png', 'jpeg', 'jpg']; $elementValidators[] = ['name' => 'fileExtension', 'options' => ['message' => sprintf($this->translator->translate('Allowed images extensions: %s'), implode(',', $validExtensions)), 'extension' => $validExtensions]]; $elementAttrs = array_merge($elementAttrs, ['class' => '']); $elementType = 'File'; $useFilters = false; break; case self::FIELD_INTEGER: $elementValidators[] = ['name' => 'int']; $elementType = 'Text'; break; case self::FIELD_FLOAT: $elementValue = LocaleUtility::convertToLocalizedValue($elementValue, $elementType); $elementValidators[] = ['name' => 'float']; $elementType = 'Text'; break; case self::FIELD_URL: $applyLengthValidator = true; $elementValidators[] = ['name' => 'uri', 'options' => ['allowRelative' => false]]; $elementType = 'Url'; break; case self::FIELD_EMAIL: $applyLengthValidator = true; $elementValidators[] = ['name' => 'emailAddress']; $elementType = 'Email'; break; case self::FIELD_TEXT_AREA: $applyLengthValidator = true; $elementType = 'Textarea'; break; case self::FIELD_PASSWORD: $applyLengthValidator = true; $elementType = 'Password'; break; case self::FIELD_CSRF: $this->addCsrf($elementName); continue 2; case self::FIELD_SUBMIT: $this->addSubmit($elementName, !empty($element['label']) ? $element['label'] : null); continue 2; case self::FIELD_CAPTCHA: $this->addCaptcha($elementName, !empty($element['label']) ? $element['label'] : null, !empty($element['category']) ? $element['category'] : null); continue 2; case self::FIELD_SLUG: $applyLengthValidator = true; $element['filters'] = array_merge(isset($element['filters']) ? $element['filters'] : [], [['name' => 'stringToLower']]); $elementValidators[] = ['name' => 'regex', 'options' => ['pattern' => '/^[' . self::FIELD_SLUG_PATTERN . ']+$/i', 'message' => 'You can use only latin, numeric or dashes characters']]; $elementType = 'Text'; break; case self::FIELD_TEXT: case self::FIELD_NOTIFICATION_TITLE: default: $applyLengthValidator = true; $elementType = 'Text'; } $this->add(['type' => 'Zend\\Form\\Element\\' . $elementType, 'name' => $elementName, 'attributes' => array_merge(['id' => $elementName, 'required' => $elementRequired, 'value' => '' !== $elementValue ? $elementValue : null], $elementAttrs), 'options' => array_merge($extraOptions, ['category' => !empty($element['category']) ? $element['category'] : null, 'extra_options' => !empty($element['extra_options']) ? $element['extra_options'] : null, 'value_options' => $elementValues, 'label' => !empty($element['label']) ? $elementRequired ? '*' . $this->translator->translate($element['label']) : $element['label'] : null, 'description' => !empty($element['description']) ? !empty($element['description_params']) ? vsprintf($this->translator->translate($element['description']), $element['description_params']) : $this->translator->translate($element['description']) : null])]); // define element filters $filters = []; if ($useFilters) { $filters = isset($element['filters']) ? $element['filters'] : $this->defaultFilters; } // add a string max length validator if (!empty($element['max_length']) && $applyLengthValidator) { $elementValidators[] = ['name' => 'StringLength', 'options' => ['max' => (int) $element['max_length']]]; $elementAttrs = array_merge(['maxlength' => (int) $element['max_length']], $elementAttrs); } // add a string min length validator if (!empty($element['min_length']) && $applyLengthValidator) { $elementValidators[] = ['name' => 'StringLength', 'options' => ['min' => (int) $element['min_length']]]; } // add validators $this->inputFilter->add($this->inputFactory->createInput(['name' => $elementName, 'required' => $elementRequired, 'filters' => $filters, 'validators' => !empty($element['validators']) ? array_merge($elementValidators, $element['validators']) : $elementValidators])); } $this->setInputFilter($this->inputFilter); }