Ejemplo n.º 1
0
 /**
  * Init layout
  */
 protected function initlayout()
 {
     try {
         // get a custom template path resolver
         $templatePathResolver = $this->serviceLocator->get('Layout\\View\\Resolver\\TemplatePathStack');
         // replace the default template path stack resolver with one
         $aggregateResolver = $this->serviceLocator->get('Zend\\View\\Resolver\\AggregateResolver');
         $aggregateResolver->attach($templatePathResolver)->getIterator()->remove($this->serviceLocator->get('Zend\\View\\Resolver\\TemplatePathStack'));
         $layout = $this->serviceLocator->get('Application\\Model\\ModelManager')->getInstance('Layout\\Model\\LayoutBase');
         $request = $this->serviceLocator->get('Request');
         // get a layout from cookies
         $allowSelectLayouts = (int) SettingService::getSetting('layout_select');
         $cookieLayout = isset($request->getCookie()->{self::LAYOUT_COOKIE}) && $allowSelectLayouts ? (int) $request->getCookie()->{self::LAYOUT_COOKIE} : null;
         // init a user selected layout
         if ($cookieLayout) {
             $activeLayouts = $layout->getLayoutsById($cookieLayout);
         } else {
             $activeLayouts = !empty(UserIdentityService::getCurrentUserIdentity()['layout']) && $allowSelectLayouts ? $layout->getLayoutsById(UserIdentityService::getCurrentUserIdentity()['layout']) : $layout->getDefaultActiveLayouts();
         }
         // add layouts paths for each module
         foreach ($this->moduleManager->getModules() as $module) {
             foreach ($activeLayouts as $layoutInfo) {
                 $templatePathResolver->addPath('module/' . $module . '/view/' . $layoutInfo['name']);
             }
         }
         LayoutService::setCurrentLayouts($activeLayouts);
     } catch (Exception $e) {
         ApplicationErrorLogger::log($e);
     }
 }
Ejemplo n.º 2
0
 /**
  * Is allowed to view the site
  *
  * @return boolean
  */
 public static function isAllowedViewSite()
 {
     if ((int) SettingService::getSetting('application_disable_site')) {
         $user = UserIdentityService::getCurrentUserIdentity();
         if ($user['role'] != AclBaseModel::DEFAULT_ROLE_ADMIN) {
             // get a visitor IP
             $remote = new RemoteAddress();
             $remote->setUseProxy(true);
             $userIp = $remote->getIpAddress();
             // get list of allowed ACL roles
             if (null != ($allowedAclRoles = SettingService::getSetting('application_disable_site_acl'))) {
                 if (!is_array($allowedAclRoles)) {
                     $allowedAclRoles = [$allowedAclRoles];
                 }
             }
             // get list of allowed IPs
             if (null != ($allowedIps = SettingService::getSetting('application_disable_site_ip'))) {
                 $allowedIps = explode(',', $allowedIps);
             }
             if ($allowedAclRoles || $allowedIps) {
                 if ($allowedAclRoles && in_array($user['role'], $allowedAclRoles) || $allowedIps && in_array($userIp, $allowedIps)) {
                     return true;
                 }
             }
             return false;
         }
     }
     return true;
 }
 /**
  * Upload an image
  *
  * @param integer $membershipId
  * @param array $image
  *      string name
  *      string type
  *      string tmp_name
  *      integer error
  *      integer size
  * @param string $oldImage
  * @param boolean $deleteImage
  * @throws \Membership\Exception\MembershipException
  * @return void
  */
 protected function uploadImage($membershipId, array $image, $oldImage = null, $deleteImage = false)
 {
     // upload the membership's image
     if (!empty($image['name'])) {
         // delete old image
         if ($oldImage) {
             if (true !== ($result = $this->deleteImage($oldImage))) {
                 throw new MembershipException('Image deleting failed');
             }
         }
         // upload a new one
         if (false === ($imageName = FileSystemUtility::uploadResourceFile($membershipId, $image, self::$imagesDir))) {
             throw new MembershipException('Avatar uploading failed');
         }
         // resize the image
         ImageUtility::resizeResourceImage($imageName, self::$imagesDir, (int) ApplicationSettingService::getSetting('membership_image_width'), (int) ApplicationSettingService::getSetting('membership_image_height'));
         $update = $this->update()->table('membership_level')->set(['image' => $imageName])->where(['id' => $membershipId]);
         $statement = $this->prepareStatementForSqlObject($update);
         $statement->execute();
     } elseif ($deleteImage && $oldImage) {
         // just delete the membership's image
         if (true !== ($result = $this->deleteImage($oldImage))) {
             throw new MembershipException('Image deleting failed');
         }
         $update = $this->update()->table('membership_level')->set(['image' => null])->where(['id' => $membershipId]);
         $statement = $this->prepareStatementForSqlObject($update);
         $statement->execute();
     }
 }
Ejemplo n.º 4
0
 /**
  * Get users
  *
  * @param integer $page
  * @param integer $perPage
  * @param string $orderBy
  * @param string $orderType
  * @param array $filters
  *      string nickname
  *      string email
  *      string status
  *      integer role
  * @return object
  */
 public function getUsers($page = 1, $perPage = 0, $orderBy = null, $orderType = null, array $filters = [])
 {
     $orderFields = ['id', 'nickname', 'email', 'registered', 'status'];
     $orderType = !$orderType || $orderType == 'desc' ? 'desc' : 'asc';
     $orderBy = $orderBy && in_array($orderBy, $orderFields) ? $orderBy : 'id';
     $select = $this->select();
     $select->from(['a' => 'user_list'])->columns(['id' => 'user_id', 'nickname' => 'nick_name', 'email', 'status', 'registered', 'role_id' => 'role'])->join(['b' => 'acl_role'], 'a.role = b.id', ['role' => 'name'])->order($orderBy . ' ' . $orderType);
     // filter by nickname
     if (!empty($filters['nickname'])) {
         $select->where([new LikePredicate('nick_name', $filters['nickname'] . '%')]);
     }
     // filter by email
     if (!empty($filters['email'])) {
         $select->where(['email' => $filters['email']]);
     }
     // filter by status
     if (!empty($filters['status'])) {
         $select->where(['status' => $filters['status']]);
     }
     // filter by role
     if (!empty($filters['role'])) {
         $select->where(['role' => $filters['role']]);
     }
     $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage(PaginationUtility::processPerPage($perPage));
     $paginator->setPageRange(SettingService::getSetting('application_page_range'));
     return $paginator;
 }
 /**
  * Get the payment type info
  *
  * @param string $name
  * @return array
  */
 public function getPaymentTypeInfo($name)
 {
     $select = $this->select();
     $select->from('payment_type')->columns(['id', 'name', 'description', 'enable_option', 'handler'])->where(['name' => $name]);
     $statement = $this->prepareStatementForSqlObject($select);
     $result = $statement->execute();
     $payment = $result->current();
     return (int) SettingService::getSetting($payment['enable_option']) ? $payment : [];
 }
 /**
  * Get all expired not paid transactions
  *
  * @param integer $limit
  * @return array
  */
 public function getExpiredTransactions($limit)
 {
     $predicate = new Predicate();
     $select = $this->select();
     $select->from('payment_transaction_list')->columns(['id', 'slug'])->where(['paid' => self::TRANSACTION_NOT_PAID, $predicate->lessThanOrEqualTo('date', time() - (int) SettingService::getSetting('payment_clearing_time'))])->limit($limit);
     $statement = $this->prepareStatementForSqlObject($select);
     $resultSet = new ResultSet();
     $resultSet->initialize($statement->execute());
     return $resultSet->toArray();
 }
 /**
  * Get user's membership connections
  *
  * @param integer $userId
  * @param integer $page
  * @param integer $perPage
  * @return \Zend\Paginator\Paginator
  */
 public function getUserMembershipConnections($userId, $page = 1, $perPage = 0)
 {
     $select = $this->select();
     $select->from(['a' => 'membership_level_connection'])->columns(['id', 'active', 'expire_date', 'expire_value'])->join(['b' => 'membership_level'], 'a.membership_id = b.id', ['title', 'role_id', 'cost', 'lifetime', 'expiration_notification', 'description', 'language', 'image'])->where(['user_id' => $userId])->order('a.id');
     $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage($perPage);
     $paginator->setPageRange(SettingService::getSetting('application_page_range'));
     return $paginator;
 }
 /**
  * Get images
  *
  * @param integer $page
  * @param integer $category
  * @param integer $perPage
  * @return \Zend\Paginator\Paginator
  */
 public function getImages($page, $category, $perPage)
 {
     $select = $this->select();
     $select->from('miniphotogallery_image')->columns(['name', 'description', 'image'])->order('order asc, created desc')->where(['category_id' => $category]);
     $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage($perPage);
     $paginator->setPageRange(SettingService::getSetting('application_page_range'));
     return $paginator;
 }
Ejemplo n.º 9
0
 /**
  * Get per page ranges
  *
  * @return array
  */
 public static function getPerPageRanges()
 {
     $ranges = [];
     $minRange = (int) SettingService::getSetting('application_min_per_page_range');
     $maxRange = (int) SettingService::getSetting('application_max_per_page_range');
     $step = (int) SettingService::getSetting('application_per_page_step');
     for ($i = $minRange; $i <= $maxRange; $i += $step) {
         $ranges[$i] = $i;
     }
     return $ranges;
 }
Ejemplo n.º 10
0
 /**
  * Get form instance
  *
  * @return object
  */
 public function getForm()
 {
     // get form builder
     if (!$this->form) {
         // add descriptions params
         $this->formElements['file']['description_params'] = [strtolower(SettingService::getSetting('file_manager_allowed_extensions')), FileSystemUtility::convertBytes((int) SettingService::getSetting('file_manager_allowed_size'))];
         // add extra validators
         $this->formElements['file']['validators'] = [['name' => 'fileextension', 'options' => ['extension' => explode(',', strtolower(SettingService::getSetting('file_manager_allowed_extensions')))]], ['name' => 'filesize', 'options' => ['max' => (int) SettingService::getSetting('file_manager_allowed_size')]]];
         $this->form = new ApplicationCustomFormBuilder($this->formName, $this->formElements, $this->translator, $this->ignoredElements, $this->notValidatedElements, $this->method);
     }
     return $this->form;
 }
Ejemplo n.º 11
0
 /**
  * Login user
  *
  * @param integer $userId
  * @param string $nickName
  * @param boolean $rememberMe
  * @return void
  */
 public static function loginUser($userId, $nickName, $rememberMe)
 {
     $user = [];
     $user['user_id'] = $userId;
     // save user id
     UserIdentityService::getAuthService()->getStorage()->write($user);
     UserIdentityService::setCurrentUserIdentity(UserIdentityService::getUserInfo($userId));
     AclService::clearCurrentAcl();
     // fire the user login event
     UserEvent::fireLoginEvent($userId, $nickName);
     if ($rememberMe) {
         ServiceLocatorService::getServiceLocator()->get('Zend\\Session\\SessionManager')->rememberMe((int) SettingService::getSetting('user_session_time'));
     }
 }
Ejemplo n.º 12
0
 /**
  * Get form instance
  *
  * @return \Application\Form\ApplicationCustomFormBuilder
  */
 public function getForm()
 {
     // get form builder
     if (!$this->form) {
         // add extra filters
         $this->formElements['name']['filters'] = [['name' => 'stringtolower']];
         // add descriptions params
         $this->formElements['name']['description_params'] = [SettingService::getSetting('file_manager_file_name_length')];
         // add extra validators
         $this->formElements['name']['validators'] = [['name' => 'regex', 'options' => ['pattern' => '/^[' . FileManagerBaseModel::getDirectoryNamePattern() . ']+$/', 'message' => 'You can use only latin, numeric and underscore symbols']], ['name' => 'callback', 'options' => ['callback' => [$this, 'validateExistingDirectory'], 'message' => 'Directory already exist']]];
         // add a directory name length limit
         $this->formElements['name']['max_length'] = (int) SettingService::getSetting('file_manager_file_name_length');
         $this->form = new ApplicationCustomFormBuilder($this->formName, $this->formElements, $this->translator, $this->ignoredElements, $this->notValidatedElements, $this->method);
     }
     return $this->form;
 }
Ejemplo n.º 13
0
 /**
  * Log an error
  *
  * @param string $errorMessage
  * @return boolean
  */
 public static function log($errorMessage)
 {
     try {
         $writer = new LogWriterStream(ServiceLocatorService::getServiceLocator()->get('Config')['paths']['error_log']);
         $logger = new Logger();
         $logger->addWriter($writer);
         $logger->err($errorMessage);
         // do we need send this error via email?
         if (null != ($errorEmail = SettingService::getSetting('application_errors_notification_email'))) {
             ApplicationEmailNotification::sendNotification($errorEmail, SettingService::getSetting('application_error_notification_title', LocalizationService::getDefaultLocalization()['language']), SettingService::getSetting('application_error_notification_message', LocalizationService::getDefaultLocalization()['language']), ['find' => ['ErrorDescription'], 'replace' => [$errorMessage]]);
         }
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
Ejemplo n.º 14
0
 /**
  * Get form instance
  *
  * @return object
  */
 public function getForm()
 {
     // get form builder
     if (!$this->form) {
         // add extra filters
         $this->formElements['name']['filters'] = [['name' => 'stringtolower']];
         // set the default file name
         $this->formElements['name']['value'] = $this->isDirectory ? $this->fileName : FileSystemUtility::getFileName($this->fileName);
         // remove the file's extension
         // init the max file name length
         $this->maxFileNameLength = $this->isDirectory ? (int) SettingService::getSetting('file_manager_file_name_length') : (int) SettingService::getSetting('file_manager_file_name_length') - (strlen(FileSystemUtility::getFileExtension($this->fileName)) + 1);
         // init a directory or file settings
         $this->isDirectory ? $this->initDirectorySettings() : $this->initFileSettings();
         $this->form = new ApplicationCustomFormBuilder($this->formName, $this->formElements, $this->translator, $this->ignoredElements, $this->notValidatedElements, $this->method);
     }
     return $this->form;
 }
 /**
  * Log action
  *
  * @param integer $actionId
  * @param string $description
  * @param array $params
  * @return boolean|string
  */
 public function logAction($actionId, $description, array $params = [])
 {
     try {
         $this->adapter->getDriver()->getConnection()->beginTransaction();
         $insert = $this->insert()->into('action_tracker_log')->values(['action_id' => $actionId, 'description' => $description, 'description_params' => serialize($params), 'registered' => time()]);
         $statement = $this->prepareStatementForSqlObject($insert);
         $statement->execute();
         $this->adapter->getDriver()->getConnection()->commit();
     } catch (Exception $e) {
         $this->adapter->getDriver()->getConnection()->rollback();
         ApplicationErrorLogger::log($e);
         return $e->getMessage();
     }
     // send an email notification about add the adding new action
     if (SettingService::getSetting('action_tracker_send_actions')) {
         $defaultLocalization = LocalizationService::getDefaultLocalization();
         $actionDescription = vsprintf($this->serviceLocator->get('Translator')->translate($description, 'default', $defaultLocalization['locale']), $params);
         EmailNotificationUtility::sendNotification(SettingService::getSetting('application_site_email'), SettingService::getSetting('action_tracker_title', $defaultLocalization['language']), SettingService::getSetting('action_tracker_message', $defaultLocalization['language']), ['find' => ['Action', 'Date'], 'replace' => [$actionDescription, $this->serviceLocator->get('viewHelperManager')->get('applicationDate')->__invoke(time(), [], $defaultLocalization['language'])]]);
     }
     return true;
 }
Ejemplo n.º 16
0
 /**
  * Init time zone
  */
 protected function initTimeZone()
 {
     try {
         // get list of all registered time zones
         $registeredTimeZones = TimeZoneService::getTimeZones();
         // what should we use here, user's or default time zone
         $defaultTimeZone = !empty($this->userIdentity['time_zone_name']) ? $this->userIdentity['time_zone_name'] : SettingService::getSetting('application_default_time_zone');
         // check default time zone existing
         if (!in_array($defaultTimeZone, $registeredTimeZones)) {
             $defaultTimeZone = current($registeredTimeZones);
         }
         // change time zone settings
         if ($defaultTimeZone != date_default_timezone_get()) {
             date_default_timezone_set($defaultTimeZone);
         }
         // get difference to greenwich time (GMT) with colon between hours and minutes
         $date = new DateTime();
         $applicationInit = $this->serviceLocator->get('Application\\Model\\ModelManager')->getInstance('Application\\Model\\ApplicationInit')->setTimeZone($date->format('P'));
     } catch (Exception $e) {
         ApplicationErrorLogger::log($e);
     }
 }
Ejemplo n.º 17
0
 /**
  * Get date
  *
  * @param string|integer $date
  * @param array $options
  *      string  type (date or date_unixtime)
  *      string format (full, long, medium, short)
  * @param string $locale
  * @return string
  */
 public function __invoke($date, array $options = [], $locale = null)
 {
     $type = !empty($options['type']) && $options['type'] == 'date' ? 'date' : 'date_unixtime';
     if ($type == 'date_unixtime' && !(int) $date) {
         return;
     }
     $format = isset($options['format']) ? $options['format'] : SettingService::getSetting('application_default_date_format');
     $format = strtolower($format);
     switch ($format) {
         case 'full':
             $format = IntlDateFormatter::FULL;
             break;
         case 'long':
             $format = IntlDateFormatter::LONG;
             break;
         case 'medium':
             $format = IntlDateFormatter::MEDIUM;
             break;
         case 'short':
         default:
             $format = IntlDateFormatter::SHORT;
     }
     return LocaleUtility::convertToLocalizedValue($date, $type, $format, $locale);
 }
 /**
  * Get actions log
  *
  * @param integer $page
  * @param integer $perPage
  * @param string $orderBy
  * @param string $orderType
  * @param array $filters
  *      array modules
  * @return \Zend\Paginator\Paginator
  */
 public function getActionsLog($page = 1, $perPage = 0, $orderBy = null, $orderType = null, array $filters = [])
 {
     $orderFields = ['id', 'registered'];
     $orderType = !$orderType || $orderType == 'desc' ? 'desc' : 'asc';
     $orderBy = $orderBy && in_array($orderBy, $orderFields) ? $orderBy : 'id';
     $select = $this->select();
     $select->from(['a' => 'action_tracker_log'])->columns(['id', 'description', 'description_params', 'registered'])->join(['b' => 'application_event'], 'a.action_id = b.id', [])->join(['c' => 'application_module'], new Expression('b.module = c.id and c.status = ?', [self::MODULE_STATUS_ACTIVE]), ['module' => 'name'])->order($orderBy . ' ' . $orderType);
     // filter by modules
     if (!empty($filters['modules']) && is_array($filters['modules'])) {
         $select->where->in('b.module', $filters['modules']);
     }
     $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage(PaginationUtility::processPerPage($perPage));
     $paginator->setPageRange(SettingService::getSetting('application_page_range'));
     return $paginator;
 }
Ejemplo n.º 19
0
 /**
  * Validate cache ttl
  *
  * @param $value
  * @param array $context
  * @return boolean
  */
 public function validateCacheTtl($value, array $context = [])
 {
     $value = (int) $value;
     return $value >= 0 && $value <= (int) SettingService::getSetting('application_dynamic_cache_life_time');
 }
Ejemplo n.º 20
0
 /**
  * Rounding a cost
  *
  * @param float|integer $cost
  * @return integer|float
  */
 public static function roundingCost($cost)
 {
     switch (SettingService::getSetting('payment_type_rounding')) {
         case 'type_round':
             return round($cost);
         case 'type_ceil':
             return ceil($cost);
         case 'type_floor':
             return floor($cost);
         default:
             return $cost;
     }
 }
Ejemplo n.º 21
0
 /**
  * Get a setting
  *
  * @param string $setting
  * @param string $language
  * @return string
  */
 public function __invoke($setting, $language = null)
 {
     return SettingService::getSetting($setting, $language);
 }
Ejemplo n.º 22
0
 /**
  * Get setting
  *
  * @param string $setting
  * @param string $language
  * @return string|boolean
  */
 protected function getSetting($setting, $language = null)
 {
     return SettingService::getSetting($setting, $language);
 }
Ejemplo n.º 23
0
 /**
  * Clear dynamic cache
  *
  * @return boolean
  */
 public static function clearDynamicCache()
 {
     if (null == ($dynamicCache = ApplicationSettingService::getSetting('application_dynamic_cache'))) {
         return true;
     }
     try {
         return ServiceLocatorService::getServiceLocator()->get('Application\\Cache\\Dynamic')->flush();
     } catch (Exception $e) {
         ApplicationErrorLogger::log($e);
     }
     return false;
 }
Ejemplo n.º 24
0
 /**
  * Check css cache status
  *
  * @return boolean
  */
 protected function isCssCacheEnabled()
 {
     return (int) SettingService::getSetting('application_css_cache');
 }
Ejemplo n.º 25
0
 /**
  * Get resources
  *
  * @param integer $roleId
  * @param integer $page
  * @param integer $perPage
  * @param string $orderBy
  * @param string $orderType
  * @param array $filters
  *      array modules
  *      string status
  * @return object
  */
 public function getResources($roleId, $page = 1, $perPage = 0, $orderBy = null, $orderType = null, array $filters = [])
 {
     $orderFields = ['id', 'connection'];
     $orderType = !$orderType || $orderType == 'desc' ? 'desc' : 'asc';
     $orderBy = $orderBy && in_array($orderBy, $orderFields) ? $orderBy : 'id';
     $select = $this->select();
     $select->from(['a' => 'acl_resource'])->columns(['id', 'description'])->join(['b' => 'application_module'], new Expression('a.module = b.id and b.status = ?', [self::MODULE_STATUS_ACTIVE]), ['module' => 'name'])->join(['c' => 'acl_resource_connection'], new Expression('a.id = c.resource and c.role = ?', [$roleId]), ['connection' => 'id'], 'left')->order($orderBy . ' ' . $orderType);
     // filter by modules
     if (!empty($filters['modules']) && is_array($filters['modules'])) {
         $select->where->in('module', $filters['modules']);
     }
     // filter by status
     if (!empty($filters['status'])) {
         switch ($filters['status']) {
             case 'disallowed':
                 $select->where->IsNull('c.id');
                 break;
             case 'allowed':
             default:
                 $select->where->IsNotNull('c.id');
         }
     }
     $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage(PaginationUtility::processPerPage($perPage));
     $paginator->setPageRange(SettingService::getSetting('application_page_range'));
     return $paginator;
 }
Ejemplo n.º 26
0
 /**
  * Set user's language
  *
  * @param string $language
  * @return void
  */
 protected function setUserLanguage($language)
 {
     if (!$this->userIdentity['language'] || $this->userIdentity['language'] != $language) {
         // save language
         if ($this->userIdentity['role'] != AclBaseModel::DEFAULT_ROLE_GUEST) {
             $this->serviceLocator->get('Application\\Model\\ModelManager')->getInstance('User\\Model\\UserBase')->setUserLanguage($this->userIdentity['user_id'], $language);
         }
         // set language cookie
         $header = new SetCookie();
         $header->setName(self::LOCALIZATION_COOKIE)->setValue($language)->setPath('/')->setExpires(time() + (int) SettingService::getSetting('application_localization_cookie_time'));
         $this->serviceLocator->get('Response')->getHeaders()->addHeader($header);
         $this->userIdentity['language'] = $language;
         // change globally user's identity
         UserIdentityService::setCurrentUserIdentity($this->userIdentity);
         UserIdentityService::getAuthService()->getStorage()->write($this->userIdentity);
     }
 }
 /**
  * Get answers
  *
  * @param integer $questionId
  * @param integer $page
  * @param integer $perPage
  * @param string $orderBy
  * @param string $orderType
  * @return \Zend\Paginator\Paginator
  */
 public function getAnswers($questionId, $page = 1, $perPage = 0, $orderBy = null, $orderType = null)
 {
     $orderFields = ['id', 'answer', 'created', 'order'];
     $orderType = !$orderType || $orderType == 'desc' ? 'desc' : 'asc';
     $orderBy = $orderBy && in_array($orderBy, $orderFields) ? $orderBy : 'id';
     $select = $this->select();
     $select->from(['a' => 'poll_answer'])->columns(['id', 'answer', 'order', 'created'])->where(['question_id' => $questionId])->order($orderBy . ' ' . $orderType);
     $paginator = new Paginator(new DbSelectPaginator($select, $this->adapter));
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage(PaginationUtility::processPerPage($perPage));
     $paginator->setPageRange(SettingService::getSetting('application_page_range'));
     return $paginator;
 }
Ejemplo n.º 28
0
 /**
  * Get default active layouts
  *
  * @return array
  */
 public function getDefaultActiveLayouts()
 {
     // generate cache name
     $cacheName = CacheUtility::getCacheName(self::CACHE_LAYOUTS_ACTIVE);
     // check data in cache
     if (null === ($layouts = $this->staticCacheInstance->getItem($cacheName))) {
         $defaultActiveCustomLayout = (int) SettingService::getSetting('layout_active');
         $select = $this->select();
         $select->from('layout_list')->columns(['name'])->order('type')->where(['type' => self::LAYOUT_TYPE_SYSTEM]);
         if ($defaultActiveCustomLayout) {
             $select->where->or->equalTo('id', $defaultActiveCustomLayout)->and->equalTo('type', self::LAYOUT_TYPE_CUSTOM);
         }
         $statement = $this->prepareStatementForSqlObject($select);
         $resultSet = new ResultSet();
         $resultSet->initialize($statement->execute());
         $layouts = $resultSet->toArray();
         // save data in cache
         $this->staticCacheInstance->setItem($cacheName, $layouts);
         $this->staticCacheInstance->setTags($cacheName, [self::CACHE_LAYOUTS_DATA_TAG]);
     }
     return $layouts;
 }
Ejemplo n.º 29
0
 /**
  * Get form instance
  *
  * @return \Application\Form\ApplicationCustomFormBuilder
  */
 public function getForm()
 {
     // get form builder
     if (!$this->form) {
         // remove the captcha field
         if (!$this->isCaptchaEnabled) {
             unset($this->formElements['captcha']);
         }
         // skip some required flags
         if ($this->userId) {
             $this->formElements['password']['required'] = false;
             $this->formElements['confirm_password']['required'] = false;
             $this->formElements['avatar']['required'] = false;
         }
         // add preview for the avatar
         if ($this->avatar) {
             $this->formElements['avatar']['extra_options']['preview'] = true;
             $this->formElements['avatar']['extra_options']['file_url'] = ApplicationService::getResourcesUrl() . UserBaseModel::getThumbnailsDir() . $this->avatar;
         }
         // add descriptions params
         $this->formElements['nick_name']['description_params'] = [SettingService::getSetting('user_nickname_min'), SettingService::getSetting('user_nickname_max')];
         // add extra validators
         $this->formElements['slug']['validators'] = [['name' => 'callback', 'options' => ['callback' => [$this, 'validateSlug'], 'message' => 'Display name already used']]];
         $this->formElements['confirm_password']['validators'] = [['name' => 'callback', 'options' => ['callback' => [$this, 'validatePassword'], 'message' => 'Passwords do not match']]];
         $this->formElements['password']['validators'] = [['name' => 'callback', 'options' => ['callback' => [$this, 'validatePassword'], 'message' => 'Passwords do not match']]];
         // validate email
         $this->formElements['email']['validators'] = [['name' => 'callback', 'options' => ['callback' => [$this, 'validateEmail'], 'message' => 'Email already used']]];
         // validate nickname
         $this->formElements['nick_name']['validators'] = [['name' => 'callback', 'options' => ['callback' => [$this, 'validateNickname'], 'message' => 'Nickname already used']]];
         $this->formElements['nick_name']['max_length'] = (int) SettingService::getSetting('user_nickname_max');
         $this->formElements['nick_name']['min_length'] = (int) SettingService::getSetting('user_nickname_min');
         // fill the form with default values
         $this->formElements['time_zone']['values'] = $this->timeZones;
         $this->form = new ApplicationCustomFormBuilder($this->formName, $this->formElements, $this->translator, $this->ignoredElements, $this->notValidatedElements, $this->method);
     }
     return $this->form;
 }
 /**
  * Upload module updates
  *
  * @param array $formData
  *      string login required
  *      string password required
  *      array module required
  * @param string $host
  * @return array|string
  */
 public function uploadModuleUpdates(array $formData, $host)
 {
     $uploadResult = true;
     try {
         // create a tmp dir
         $tmpDirName = $this->generateTmpDir();
         ApplicationFileSystemUtility::createDir($tmpDirName);
         // unzip a module updates into the tmp dir
         $this->unzipFiles($formData['module']['tmp_name'], $tmpDirName);
         // check the module's config
         if (!file_exists($tmpDirName . '/update_config.php')) {
             throw new ApplicationException('Cannot define the module\'s config file');
         }
         // get the module's config
         $updateModuleConfig = (include $tmpDirName . '/update_config.php');
         $moduleCompatable = !empty($updateModuleConfig['compatable']) ? $updateModuleConfig['compatable'] : null;
         $moduleName = !empty($updateModuleConfig['module']) ? $updateModuleConfig['module'] : null;
         $moduleVersion = !empty($updateModuleConfig['version']) ? $updateModuleConfig['version'] : null;
         $moduleVendor = !empty($updateModuleConfig['vendor']) ? $updateModuleConfig['vendor'] : null;
         $moduleVendorEmail = !empty($updateModuleConfig['vendor_email']) ? $updateModuleConfig['vendor_email'] : null;
         // check the module existing
         if (!$moduleName) {
             throw new ApplicationException('Module not found');
         }
         $moduleInstalled = true;
         // get module info from db
         if (null == ($moduleInfo = $this->getModuleInfo($moduleName))) {
             // get info from config
             if (false === ($moduleInfo = $this->getCustomModuleInstallConfig($moduleName))) {
                 // nothing to update
                 throw new ApplicationException('Module not found');
             }
             $moduleInstalled = false;
         }
         // compare the modules options
         if (!$moduleVendor || !$moduleVendorEmail || empty($moduleInfo['vendor']) || empty($moduleInfo['vendor_email']) || strcasecmp($moduleVendor, $moduleInfo['vendor']) != 0 || strcasecmp($moduleVendorEmail, $moduleInfo['vendor_email']) != 0) {
             throw new ApplicationException('Module not found');
         }
         if (!$moduleCompatable || true !== ($result = version_compare(SettingService::getSetting('application_generator_version'), $moduleCompatable, '>='))) {
             throw new ApplicationException('These updates are not compatible with current CMS version');
         }
         // compare the module versions
         if (!$moduleVersion || empty($moduleInfo['version']) || version_compare($moduleVersion, $moduleInfo['version']) <= 0) {
             throw new ApplicationException('This module updates are not necessary or not defined');
         }
         // get the module's path
         $modulePath = !empty($updateModuleConfig['module_path']) ? $tmpDirName . '/' . $updateModuleConfig['module_path'] : null;
         // check the module existing
         if ($modulePath && (!file_exists($modulePath) || !is_dir($modulePath))) {
             throw new ApplicationException('Cannot define the module\'s path into the config file');
         }
         // check the module layout existing
         $moduleLayoutPath = !empty($updateModuleConfig['layout_path']) && $moduleInfo['layout_path'] ? $tmpDirName . '/' . $updateModuleConfig['layout_path'] : null;
         if ($moduleLayoutPath && (!file_exists($moduleLayoutPath) || !is_dir($moduleLayoutPath))) {
             throw new ApplicationException('Cannot define the module\'s layout path into the config file');
         }
         // check system requirements
         $requirements = $this->getNotValidatedModuleSystemRequirements($updateModuleConfig);
         if (count($requirements)) {
             throw new ApplicationException('You have to install all system requirements before apply these module updates. Check the readme file');
         }
         // check the module depends
         if (false === ($result = $this->checkModuleDepends($updateModuleConfig))) {
             throw new ApplicationException('You have to install all dependent modules before apply these module updates. Check the readme file');
         }
         // install updates
         if ($moduleInstalled) {
             // clear caches
             $this->clearCaches(!empty($updateModuleConfig['clear_caches']) ? $updateModuleConfig['clear_caches'] : []);
             // create resources dirs
             if (!empty($updateModuleConfig['create_resources'])) {
                 $this->createResourceDirs($updateModuleConfig['create_resources']);
             }
             // execute an update sql file
             if (!empty($updateModuleConfig['update_sql'])) {
                 $this->executeSqlFile($tmpDirName . '/' . $updateModuleConfig['update_sql']);
             }
             // delete unnecessary resources dirs
             if (!empty($updateModuleConfig['delete_resources'])) {
                 foreach ($updateModuleConfig['delete_resources'] as $dir) {
                     if (!empty($dir['dir_name'])) {
                         if (file_exists(ApplicationService::getResourcesDir() . $dir['dir_name'])) {
                             ApplicationFileSystemUtility::deleteFiles(ApplicationService::getResourcesDir() . $dir['dir_name'], [], false, true);
                         }
                     }
                 }
             }
         }
         // update files via FTP
         if ($modulePath || $moduleLayoutPath && $moduleInfo['layout_path']) {
             $ftp = new ApplicationFtpUtility($host, $formData['login'], $formData['password']);
             if ($modulePath) {
                 $ftp->copyDirectory($modulePath, ApplicationService::getModulePath(false) . '/' . $moduleName);
             }
             if ($moduleLayoutPath && $moduleInfo['layout_path']) {
                 $ftp->copyDirectory($moduleLayoutPath, basename(APPLICATION_PUBLIC) . '/' . ApplicationService::getBaseLayoutPath(false) . '/' . $moduleInfo['layout_path']);
             }
         }
         if ($moduleInstalled) {
             // update version
             $update = $this->update()->table('application_module')->set(['version' => $moduleVersion])->where(['name' => $moduleName]);
             $statement = $this->prepareStatementForSqlObject($update);
             $statement->execute();
         }
     } catch (Exception $e) {
         ApplicationErrorLogger::log($e);
         $uploadResult = $e->getMessage();
     }
     // remove the tmp dir
     if (file_exists($tmpDirName)) {
         ApplicationFileSystemUtility::deleteFiles($tmpDirName, [], false, true);
     }
     // fire the upload module updates event
     if (true === $uploadResult) {
         ApplicationEvent::fireUploadModuleUpdatesEvent($moduleName);
         return $updateModuleConfig;
     }
     // return an error description
     return $uploadResult;
 }