Exemplo n.º 1
0
/**
 * Плагин для смарти
 * Подключает обработчик блоков шаблона
 *
 * @param array $aParams
 * @param Smarty $oSmarty
 * @return string
 */
function smarty_insert_block($aParams, &$oSmarty)
{
    if (!isset($aParams['block'])) {
        trigger_error('Not found param "block"', E_USER_WARNING);
        return;
    }
    /**
     * Устанавливаем шаблон
     */
    $sBlock = ucfirst(basename($aParams['block']));
    /**
     * Проверяем наличие шаблона. Определяем значения параметров работы в зависимости от того,
     * принадлежит ли блок одному из плагинов, или является пользовательским классом движка
     */
    if (isset($aParams['params']) and isset($aParams['params']['plugin'])) {
        $sBlockTemplate = Plugin::GetTemplatePath($aParams['params']['plugin']) . 'blocks/block.' . $aParams['block'] . '.tpl';
        $sBlock = 'Plugin' . func_camelize($aParams['params']['plugin']) . '_Block' . $sBlock;
    } else {
        $sBlockTemplate = 'blocks/block.' . $aParams['block'] . '.tpl';
        $sBlock = 'Block' . $sBlock;
    }
    $sBlock = Engine::getInstance()->Plugin_GetDelegate('block', $sBlock);
    /**
     * параметры
     */
    $aParamsBlock = array();
    if (isset($aParams['params'])) {
        $aParamsBlock = $aParams['params'];
    }
    /**
     * Подключаем необходимый обработчик
     */
    $oBlock = new $sBlock($aParamsBlock);
    $oBlock->SetTemplate($sBlockTemplate);
    /**
     * Запускаем обработчик
     */
    $mResult = $oBlock->Exec();
    if (is_string($mResult) or $mResult === false) {
        /**
         * Если метод возвращает строку - выводим ее вместо рендеринга шаблона
         */
        return $mResult;
    } else {
        /**
         * Получаем шаблон, возможно его переопределили в обработчике блока
         */
        $sBlockTemplate = Engine::getInstance()->Plugin_GetDelegate('template', $oBlock->GetTemplate());
        if (!Engine::getInstance()->Viewer_TemplateExists($sBlockTemplate)) {
            return "<b>Not found template for block: <i>{$sBlockTemplate} ({$sBlock})</i></b>";
        }
    }
    /**
     * Возвращаем результат в виде обработанного шаблона блока
     */
    return Engine::getInstance()->Viewer_Fetch($sBlockTemplate);
}
 /**
  * Инициализация
  */
 public function Init()
 {
     parent::Init();
     $this->aValidateRules[] = array('text', 'string', 'max' => Config::Get('module.user.complaint_text_max'), 'min' => 1, 'allowEmpty' => !Config::Get('module.user.complaint_text_required'), 'label' => $this->Lang_Get('user_complaint_text_title'));
     if (Config::Get('module.user.complaint_captcha')) {
         $sCaptchaValidateType = func_camelize('captcha_' . Config::Get('sys.captcha.type'));
         $this->aValidateRules[] = array('captcha', $sCaptchaValidateType, 'name' => 'complaint_user');
     }
 }
 public function getValueTypeObject()
 {
     if (!$this->_getDataOne('value_type_object')) {
         $oObject = Engine::GetEntity('ModuleProperty_EntityValueType' . func_camelize($this->getPropertyType()));
         $oObject->setValueObject($this);
         $this->setValueTypeObject($oObject);
     }
     return $this->_getDataOne('value_type_object');
 }
Exemplo n.º 4
0
 /**
  * Определяем дополнительные правила валидации
  *
  * @param array|bool $aParam
  */
 public function __construct($aParam = false)
 {
     $this->aValidateRules[] = array('password', 'string', 'allowEmpty' => false, 'min' => 5, 'on' => array('registration'), 'label' => $this->Lang_Get('auth.labels.password'));
     $this->aValidateRules[] = array('password_confirm', 'compare', 'compareField' => 'password', 'on' => array('registration'), 'label' => $this->Lang_Get('auth.registration.form.fields.password_confirm.label'));
     $sCaptchaValidateType = func_camelize('captcha_' . Config::Get('sys.captcha.type'));
     if (Config::Get('module.user.captcha_use_registration')) {
         $this->aValidateRules[] = array('captcha', $sCaptchaValidateType, 'name' => 'user_signup', 'on' => array('registration'), 'label' => $this->Lang_Get('auth.labels.captcha_field'));
     }
     if (Config::Get('general.login.captcha')) {
         $this->aValidateRules[] = array('captcha', $sCaptchaValidateType, 'name' => 'user_auth', 'on' => array('signIn'), 'label' => $this->Lang_Get('auth.labels.captcha_field'));
     }
     parent::__construct($aParam);
 }
Exemplo n.º 5
0
 public function actionNew($aArgs)
 {
     // Передано ли имя нового плагина
     if (!isset($aArgs[0])) {
         die("The plugin name is not specified.\n");
     }
     $this->_name_under = func_underscore($aArgs[0]);
     $this->_name = func_camelize($this->_name_under);
     $path = strtr($this->_name_under, '/\\', DIRECTORY_SEPARATOR);
     $path = Config::Get('path.application.plugins.server') . '/' . $path;
     if (strpos($path, DIRECTORY_SEPARATOR) === false) {
         $path = '.' . DIRECTORY_SEPARATOR . $path;
     }
     $dir = rtrim(realpath(dirname($path)), '\\/');
     if ($dir === false || !is_dir($dir)) {
         die("The directory '{$path}' is not valid. Please make sure the parent directory exists.\n");
     }
     $sourceDir = realpath(dirname(__FILE__) . '/../protected/plugin');
     if ($sourceDir === false) {
         die("\nUnable to locate the source directory.\n");
     }
     // Создаем массив файлов для функции копирования
     $aList = $this->buildFileList($sourceDir, $path);
     // Парсим имена плагинов и пересоздаем массив
     foreach ($aList as $sName => $aFile) {
         $sTarget = str_replace('Example', $this->_name, $aFile['target']);
         $sTarget = str_replace('example', $this->_name_under, $sTarget);
         $sNewName = str_replace('Example', $this->_name, $sName);
         $sNewName = str_replace('example', $this->_name_under, $sNewName);
         if ($sName != $sNewName) {
             unset($aList[$sName]);
         }
         $aFile['target'] = $sTarget;
         $aList[$sNewName] = $aFile;
         $aList[$sNewName]['callback'] = array($this, 'generatePlugin');
     }
     // Копируем файлы
     $this->copyFiles($aList);
     echo "\nYour plugin has been created successfully under {$path}.\n";
 }
 /**
  * Определяет тип блока
  *
  * @param string $sName	Название блока
  * @param string|null $sPlugin	код плагина, если блок принадлежит плагину
  * @return string ('block','template','undefined')
  */
 protected function DefineTypeBlock($sName, $sPlugin = null)
 {
     $sDir = $sPlugin ? Plugin::GetTemplatePath($sPlugin) : null;
     /**
      * Если ли обработчик блока?
      */
     $sClassBlock = ($sPlugin ? 'Plugin' . func_camelize($sPlugin) . '_' : '') . 'Block' . func_camelize($sName);
     if (class_exists($sClassBlock)) {
         return 'block';
     } elseif ($this->TemplateExists(is_null($sDir) ? $sName : rtrim($sDir, '/') . '/' . ltrim($sName, '/'))) {
         /**
          * Если найден шаблон по имени блока то считаем его простым шаблоном
          */
         return 'template';
     } else {
         /**
          * Считаем что тип не определен
          */
         throw new Exception('Can not find the block`s template: ' . $sName);
         return 'undefined';
     }
 }
Exemplo n.º 7
0
 /**
  * Проверяет разрешение для конкретного пользователя
  *
  * @param ModuleUser_EntityUser $oUser Пользователь
  * @param string $sPermissionCode Код разрешения
  * @param array $aParams Параметры
  * @param mixed $sPlugin Плагин, можно указать код плагина, название класса или объект
  *
  * @return bool
  */
 protected function IsAllowUserFull($oUser, $sPermissionCode, $aParams = array(), $sPlugin = null)
 {
     if (!$sPermissionCode) {
         return false;
     }
     $sPlugin = $sPlugin ? Plugin::GetPluginCode($sPlugin) : '';
     /**
      * Загружаем все роли и пермишены
      */
     $this->LoadRoleAndPermissions();
     $sUserId = self::ROLE_CODE_GUEST;
     if ($oUser) {
         $sUserId = $oUser->getId();
     }
     /**
      * Смотрим роли в кеше
      */
     if (!isset($this->aUserRoleCache[$sUserId])) {
         if ($sUserId == self::ROLE_CODE_GUEST) {
             $aRoles = $this->GetRoleByCodeAndState(self::ROLE_CODE_GUEST, self::ROLE_STATE_ACTIVE);
             $aRoles = $aRoles ? array($aRoles) : array();
         } else {
             $aRoles = $this->GetRolesByUser($oUser);
         }
         $this->aUserRoleCache[$sUserId] = $aRoles;
     } else {
         $aRoles = $this->aUserRoleCache[$sUserId];
     }
     /**
      * Получаем пермишены для ролей
      */
     $sPermissionCode = func_underscore($sPermissionCode);
     $mResult = false;
     foreach ($aRoles as $oRole) {
         /**
          * У роли есть необходимый пермишен, то проверим на возможную кастомную обработку с параметрами
          */
         if ($this->CheckPermissionByRole($oRole, $sPermissionCode, $sPlugin)) {
             /**
              * Проверяем на передачу коллбека
              */
             if (isset($aParams['callback']) and is_callable($aParams['callback'])) {
                 $mResult = call_user_func($aParams['callback'], $oUser, $aParams);
             } else {
                 /**
                  * Для плагинов: CheckCustomPluginArticleCreate
                  * Для ядра: CheckCustomCreate
                  */
                 $sAdd = $sPlugin ? 'Plugin' . func_camelize($sPlugin) : '';
                 $sMethod = 'CheckCustom' . $sAdd . func_camelize($sPermissionCode);
                 if (method_exists($this, $sMethod)) {
                     $mResult = call_user_func(array($this, $sMethod), $oUser, $aParams);
                 } else {
                     return true;
                 }
             }
             break;
         }
     }
     /**
      * Дефолтное сообщение об ошибке
      */
     $sMsg = 'У вас нет прав на "' . $sPermissionCode . '"';
     /**
      * Проверяем результат кастомной обработки
      */
     if ($mResult === true) {
         return true;
     } elseif (is_string($mResult)) {
         /**
          * Вернули кастомное сообщение об ошибке
          */
         $sMsg = $mResult;
     } else {
         /**
          * Формируем сообщение об ошибке
          */
         if (isset($this->aPermissionCache[$sPlugin][$sPermissionCode])) {
             $aPerm = $this->aPermissionCache[$sPlugin][$sPermissionCode];
             if ($aPerm['msg_error']) {
                 $sMsg = $this->Lang_Get($aPerm['msg_error']);
             } else {
                 $sMsg = 'У вас нет прав на "' . ($aPerm['title'] ? $aPerm['title'] : $aPerm['code']) . '"';
             }
         }
     }
     $this->sMessageLast = $sMsg;
     return false;
 }
 /**
  * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля.
  * Также обрабатывает различные ORM методы сущности, например
  * <pre>
  * $oUser->Save();
  * $oUser->Delete();
  * </pre>
  * И методы модуля ORM, например
  * <pre>
  *    $this->User_getUserItemsByName('Claus');
  *    $this->User_getUserItemsAll();
  * </pre>
  * @see Engine::_CallModule
  *
  * @param string $sName Имя метода
  * @param array $aArgs Аргументы
  * @return mixed
  */
 public function __call($sName, $aArgs)
 {
     $sNameUnderscore = func_underscore($sName);
     if (preg_match("@^add([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_AddEntity($aArgs[0]);
     }
     if (preg_match("@^update([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_UpdateEntity($aArgs[0]);
     }
     if (preg_match("@^save([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_SaveEntity($aArgs[0]);
     }
     if (preg_match("@^delete([a-z]+)\$@i", $sName, $aMatch) and !strpos($sNameUnderscore, 'items_by_filter')) {
         return $this->_DeleteEntity($aArgs[0]);
     }
     if (preg_match("@^reload([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_ReloadEntity($aArgs[0]);
     }
     if (preg_match("@^showcolumnsfrom([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_ShowColumnsFrom($aArgs[0]);
     }
     if (preg_match("@^showprimaryindexfrom([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_ShowPrimaryIndexFrom($aArgs[0]);
     }
     if (preg_match("@^getchildrenof([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_GetChildrenOfEntity($aArgs[0]);
     }
     if (preg_match("@^getparentof([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_GetParentOfEntity($aArgs[0]);
     }
     if (preg_match("@^getdescendantsof([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_GetDescendantsOfEntity($aArgs[0]);
     }
     if (preg_match("@^getancestorsof([a-z]+)\$@i", $sName, $aMatch)) {
         return $this->_GetAncestorsOfEntity($aArgs[0]);
     }
     if (preg_match("@^loadtreeof([a-z]+)\$@i", $sName, $aMatch)) {
         $sEntityFull = array_key_exists(1, $aMatch) ? $aMatch[1] : null;
         return $this->LoadTree(isset($aArgs[0]) ? $aArgs[0] : array(), $sEntityFull);
     }
     $iEntityPosEnd = 0;
     if (strpos($sNameUnderscore, '_items') >= 3) {
         $iEntityPosEnd = strpos($sNameUnderscore, '_items');
     } else {
         if (strpos($sNameUnderscore, '_by') >= 3) {
             $iEntityPosEnd = strpos($sNameUnderscore, '_by');
         } else {
             if (strpos($sNameUnderscore, '_all') >= 3) {
                 $iEntityPosEnd = strpos($sNameUnderscore, '_all');
             }
         }
     }
     if ($iEntityPosEnd && $iEntityPosEnd > 4) {
         $sEntityName = substr($sNameUnderscore, 4, $iEntityPosEnd - 4);
     } else {
         $sEntityName = func_underscore(Engine::GetModuleName($this)) . '_';
         $sNameUnderscore = substr_replace($sNameUnderscore, $sEntityName, 4, 0);
         $iEntityPosEnd = strlen($sEntityName) - 1 + 4;
     }
     $sNameUnderscore = substr_replace($sNameUnderscore, str_replace('_', '', $sEntityName), 4, $iEntityPosEnd - 4);
     $sEntityName = func_camelize($sEntityName);
     /**
      * getMaxRatingFromUserByFilter() get_max_rating_from_user_by_filter
      */
     if (preg_match("@^get_(max|min|avg|sum)_([a-z][_a-z0-9]*)_from_([a-z][_a-z0-9]*)_by_filter\$@i", func_underscore($sName), $aMatch)) {
         return $this->GetAggregateFunctionByFilter($aMatch[1], $aMatch[2], isset($aArgs[0]) ? $aArgs[0] : array(), func_camelize($aMatch[3]));
     }
     /**
      * getMaxRatingFromUserByStatusAndActive() get_max_rating_from_user_by_status_and_active
      */
     if (preg_match("@^get_(max|min|avg|sum)_([a-z][_a-z0-9]*)_from_([a-z][_a-z0-9]*)_by_([_a-z]+)\$@i", func_underscore($sName), $aMatch)) {
         $aSearchParams = explode('_and_', $aMatch[4]);
         $aSplit = array_chunk($aArgs, count($aSearchParams));
         $aFilter = array_combine($aSearchParams, $aSplit[0]);
         if (isset($aSplit[1][0])) {
             $aFilter = array_merge($aFilter, $aSplit[1][0]);
         }
         return $this->GetAggregateFunctionByFilter($aMatch[1], $aMatch[2], $aFilter, func_camelize($aMatch[3]));
     }
     /**
      * getCountFromUserByFilter() get_count_from_user_by_filter
      */
     if (preg_match("@^get_count_from_([a-z][_a-z0-9]*)_by_filter\$@i", func_underscore($sName), $aMatch)) {
         return $this->GetCountItemsByFilter(isset($aArgs[0]) ? $aArgs[0] : array(), func_camelize($aMatch[1]));
     }
     /**
      * getUserItemsByFilter() get_user_items_by_filter
      */
     if (preg_match("@^get_([a-z]+)((_items)|())_by_filter\$@i", $sNameUnderscore, $aMatch)) {
         if ($aMatch[2] == '_items') {
             return $this->GetItemsByFilter($aArgs[0], $sEntityName);
         } else {
             return $this->GetByFilter($aArgs[0], $sEntityName);
         }
     }
     /**
      * deleteUserItemsByFilter() delete_user_items_by_filter
      */
     if (preg_match("@^delete_([a-z\\_]+)_items_by_filter\$@i", func_underscore($sName), $aMatch)) {
         return $this->DeleteItemsByFilter(isset($aArgs[0]) ? $aArgs[0] : array(), func_camelize($aMatch[1]));
     }
     /**
      * getUserItemsByArrayId() get_user_items_by_array_id
      */
     if (preg_match("@^get_([a-z]+)_items_by_array_([_a-z]+)\$@i", $sNameUnderscore, $aMatch)) {
         return $this->GetItemsByArray(array($aMatch[2] => $aArgs[0]), $sEntityName);
     }
     /**
      * getUserItemsByJoinEntity() get_user_items_by_join_entity
      */
     if (preg_match("@^get_([a-z]+)_items_by_join_entity\$@i", $sNameUnderscore, $aMatch)) {
         return $this->GetItemsByJoinEntity($aArgs[0], $aArgs[1], $aArgs[2], $aArgs[3], $aArgs[4], func_camelize($sEntityName));
     }
     /**
      * getUserByLogin()                    get_user_by_login
      * getUserByLoginAndMail()            get_user_by_login_and_mail
      * getUserItemsByName()                get_user_items_by_name
      * getUserItemsByNameAndActive()    get_user_items_by_name_and_active
      * getUserItemsByDateRegisterGte()    get_user_items_by_date_register_gte        (>=)
      * getUserItemsByProfileNameLike()    get_user_items_by_profile_name_like
      * getUserItemsByCityIdIn()            get_user_items_by_city_id_in
      */
     if (preg_match("@^get_([a-z]+)((_items)|())_by_([_a-z]+)\$@i", $sNameUnderscore, $aMatch)) {
         $aAliases = array('_gte' => ' >=', '_lte' => ' <=', '_gt' => ' >', '_lt' => ' <', '_like' => ' LIKE', '_in' => ' IN');
         $sSearchParams = str_replace(array_keys($aAliases), array_values($aAliases), $aMatch[5]);
         $aSearchParams = explode('_and_', $sSearchParams);
         $aSplit = array_chunk($aArgs, count($aSearchParams));
         $aFilter = array_combine($aSearchParams, $aSplit[0]);
         if (isset($aSplit[1][0])) {
             $aFilter = array_merge($aFilter, $aSplit[1][0]);
         }
         if ($aMatch[2] == '_items') {
             return $this->GetItemsByFilter($aFilter, $sEntityName);
         } else {
             return $this->GetByFilter($aFilter, $sEntityName);
         }
     }
     /**
      * getUserAll()            get_user_all        OR
      * getUserItemsAll()    get_user_items_all
      */
     if (preg_match("@^get_([a-z]+)_all\$@i", $sNameUnderscore, $aMatch) || preg_match("@^get_([a-z]+)_items_all\$@i", $sNameUnderscore, $aMatch)) {
         $aFilter = array();
         if (isset($aArgs[0]) and is_array($aArgs[0])) {
             $aFilter = $aArgs[0];
         }
         return $this->GetItemsByFilter($aFilter, $sEntityName);
     }
     return parent::__call($sName, $aArgs);
 }
Exemplo n.º 9
0
 /**
  * Загрузка плагинов и делегирование
  *
  */
 protected function LoadPlugins()
 {
     if ($aPluginList = func_list_plugins()) {
         foreach ($aPluginList as $sPluginName) {
             $sClassName = 'Plugin' . func_camelize($sPluginName);
             $oPlugin = new $sClassName();
             $oPlugin->Delegate();
             $this->aPlugins[$sPluginName] = $oPlugin;
         }
     }
 }
Exemplo n.º 10
0
 public function CallbackParserTag($sTag, $aParams, $sContent)
 {
     $sParserClass = 'ModuleText_EntityParserTag' . func_camelize($sTag);
     if (class_exists($sParserClass)) {
         $oParser = Engine::GetEntity($sParserClass);
         return $oParser->parse($sContent, $aParams);
     }
     return '';
 }
Exemplo n.º 11
0
 /**
  * Ajax валидация каптчи
  */
 protected function EventCaptchaValidate()
 {
     $sName = isset($_REQUEST['params']['name']) ? $_REQUEST['params']['name'] : '';
     $sValue = isset($_REQUEST['fields'][0]['value']) ? $_REQUEST['fields'][0]['value'] : '';
     $sField = isset($_REQUEST['fields'][0]['field']) ? $_REQUEST['fields'][0]['field'] : '';
     $sCaptchaValidateType = func_camelize('captcha_' . Config::Get('sys.captcha.type'));
     if (!$this->Validate_Validate($sCaptchaValidateType, $sValue, array('name' => $sName))) {
         $aErrors = $this->Validate_GetErrors();
         $this->Viewer_AssignAjax('aErrors', array(htmlspecialchars($sField) => array(reset($aErrors))));
     }
 }
Exemplo n.º 12
0
 /**
  * Возвращает объект бекенда кеша
  *
  * @param string|null $sCacheType Тип кеша
  *
  * @return ModuleCache_EntityBackend    Объект бекенда кеша
  * @throws Exception
  */
 protected function GetCacheBackend($sCacheType = null)
 {
     if ($sCacheType) {
         $sCacheType = strtolower($sCacheType);
     } else {
         $sCacheType = $this->sCacheType;
     }
     /**
      * Устанавливает алиас memory == memcached
      */
     if ($sCacheType == 'memory') {
         $sCacheType = 'memcached';
     }
     if (isset($this->aCacheBackends[$sCacheType])) {
         return $this->aCacheBackends[$sCacheType];
     }
     $sCacheTypeCam = func_camelize($sCacheType);
     /**
      * Формируем имя класса бекенда
      */
     $sClass = "ModuleCache_EntityBackend{$sCacheTypeCam}";
     $sClass = Engine::GetEntityClass($sClass);
     if (class_exists($sClass)) {
         /**
          * Создаем объект и проверяем доступность его использования
          */
         $oBackend = new $sClass();
         if (true === ($mResult = $oBackend->IsAvailable())) {
             $oBackend->Init(array('stats_callback' => array($this, 'CalcStats')));
             $this->aCacheBackends[$sCacheType] = $oBackend;
             return $oBackend;
         } else {
             throw new Exception("Cache '{$sCacheTypeCam}' not available: {$mResult}");
         }
     }
     throw new Exception("Not found class for cache type: " . $sCacheTypeCam);
 }
Exemplo n.º 13
0
 /**
  * Возвращает относительный путь
  *
  * @param string $sPath Исходный путь с префиксом, например, [server]/home/webmaster/site.com/image.jpg
  * @param bool $bWithType
  *
  * @return string
  */
 public function GetPathRelative($sPath, $bWithType = false)
 {
     list($sType, $sPath) = $this->GetParsedPath($sPath);
     if ($sType != self::PATH_TYPE_RELATIVE) {
         /**
          * Пробуем вызвать метод GetPathRelativeFrom[Type]()
          */
         $sMethod = 'GetPathRelativeFrom' . func_camelize($sType);
         if (method_exists($this, $sMethod)) {
             $sPath = $this->{$sMethod}($sPath);
         }
     }
     if ($bWithType) {
         $sPath = $this->MakePath($sPath, self::PATH_TYPE_RELATIVE);
     }
     return $sPath;
 }
Exemplo n.º 14
0
 public function CheckAllowTargetObject($sTargetType, $iTargetId, $aParams = array())
 {
     $sMethod = 'CheckAllowTargetObject' . func_camelize($sTargetType);
     if (method_exists($this, $sMethod)) {
         if (!array_key_exists('user', $aParams)) {
             $aParams['user'] = $this->oUserCurrent;
         }
         return $this->{$sMethod}($iTargetId, $aParams);
     }
     /**
      * По умолчанию считаем доступ разрешен
      */
     return true;
 }
 /**
  * Выполняет откат изменений плагина к БД
  * Обратный по действию метод - ApplyPluginUpdate (@see ApplyPluginUpdate)
  *
  * @param $sPlugin
  */
 protected function PurgePluginUpdate($sPlugin)
 {
     $sPlugin = strtolower($sPlugin);
     $sPluginDir = Plugin::GetPath($sPlugin) . 'update/';
     /**
      * Получаем список выполненых миграций из БД
      */
     $aMigrationItemsGroup = $this->GetMigrationItemsByFilter(array('code' => $sPlugin, '#order' => array('file' => 'asc'), '#index-group' => 'version'));
     $aMigrationItemsGroup = array_reverse($this->SortVersions($aMigrationItemsGroup, true), true);
     foreach ($aMigrationItemsGroup as $sVersion => $aMigrationItems) {
         foreach ($aMigrationItems as $oMigration) {
             $sPath = $sPluginDir . $sVersion . '/' . $oMigration->getFile();
             if (file_exists($sPath)) {
                 require_once $sPath;
                 $sClass = 'Plugin' . func_camelize($sPlugin) . '_Update_' . basename($oMigration->getFile(), '.php');
                 $oUpdate = new $sClass();
                 $oUpdate->down();
             }
             /**
              * Удаляем запись из БД
              */
             $oMigration->Delete();
         }
     }
     /**
      * Удаляем версию
      */
     if ($oVersion = $this->GetVersionByCode($sPlugin)) {
         $oVersion->Delete();
     }
     /**
      * Удаляем данные плагина из хранилища настроек
      */
     $this->Storage_RemoveAll('Plugin' . func_camelize($sPlugin));
     $this->Storage_Remove('__config__', 'Plugin' . func_camelize($sPlugin));
     // хардим удаление конфига админки
 }
Exemplo n.º 16
0
 /**
  * Создает и возвращает объект валидатора
  *
  * @param $sName	Имя валидатора или метода при использовании параметра $oObject
  * @param $oObject	Объект в котором необходимо вызвать метод валидации
  * @param null $aFields	Список полей сущности для которых необходимо провести валидацию
  * @param array $aParams
  *
  * @return mixed
  */
 public function CreateValidator($sName, $oObject, $aFields = null, $aParams = array())
 {
     if (is_string($aFields)) {
         $aFields = preg_split('/[\\s,]+/', $aFields, -1, PREG_SPLIT_NO_EMPTY);
     }
     /**
      * Определяем список сценариев валидации
      */
     if (isset($aParams['on'])) {
         if (is_array($aParams['on'])) {
             $aOn = $aParams['on'];
         } else {
             $aOn = preg_split('/[\\s,]+/', $aParams['on'], -1, PREG_SPLIT_NO_EMPTY);
         }
     } else {
         $aOn = array();
     }
     /**
      * Если в качестве имени валидатора указан метод объекта, то создаем специальный валидатор
      */
     $sMethod = 'validate' . func_camelize($sName);
     if (method_exists($oObject, $sMethod)) {
         $oValidator = Engine::GetEntity('ModuleValidate_EntityValidatorInline');
         if (!is_null($aFields)) {
             $oValidator->fields = $aFields;
         }
         $oValidator->object = $oObject;
         $oValidator->method = $sMethod;
         $oValidator->params = $aParams;
         if (isset($aParams['skipOnError'])) {
             $oValidator->skipOnError = $aParams['skipOnError'];
         }
     } else {
         /**
          * Иначе создаем валидатор по имени
          */
         if (!is_null($aFields)) {
             $aParams['fields'] = $aFields;
         }
         $sValidateName = 'Validator' . func_camelize($sName);
         $oValidator = Engine::GetEntity('ModuleValidate_Entity' . $sValidateName);
         foreach ($aParams as $sNameParam => $sValue) {
             $oValidator->{$sNameParam} = $sValue;
         }
     }
     $oValidator->on = empty($aOn) ? array() : array_combine($aOn, $aOn);
     return $oValidator;
 }
Exemplo n.º 17
0
 public function __get($sName)
 {
     // Обработка обращений к обёрткам связей MANY_TO_MANY
     // Если связь загружена, возвращаем объект связи
     if (isset($this->_aManyToManyRelations[func_underscore($sName)])) {
         return $this->_aManyToManyRelations[func_underscore($sName)];
         // Есл не загружена, но связь с таким именем существет, пробуем загрузить и вернуть объект связи
     } elseif (isset($this->aRelations[func_underscore($sName)]) && $this->aRelations[func_underscore($sName)][0] == self::RELATION_TYPE_MANY_TO_MANY) {
         $sMethod = 'get' . func_camelize($sName);
         $this->__call($sMethod, array());
         if (isset($this->_aManyToManyRelations[func_underscore($sName)])) {
             return $this->_aManyToManyRelations[func_underscore($sName)];
         }
         // В противном случае возвращаем то, что просили у объекта
     } else {
         return $this->{$sName};
     }
 }
Exemplo n.º 18
0
 /**
  * Создает и возврашает объект типа
  *
  * @param string $sType
  *
  * @return bool|ModuleAsset_EntityType
  */
 public function CreateObjectType($sType)
 {
     /**
      * Формируем имя класса для типа
      */
     $sClass = "ModuleAsset_EntityType" . func_camelize($sType);
     if (class_exists(Engine::GetEntityClass($sClass))) {
         return Engine::GetEntity($sClass);
     }
     return false;
 }
Exemplo n.º 19
0
 /**
  * Возвращает список тегов для объекта избранного
  *
  * @param string $sTargetType	Тип владельца
  * @param int $iTargetId	ID владельца
  * @return bool|array
  */
 public function GetTagsTarget($sTargetType, $iTargetId)
 {
     $sMethod = 'GetTagsTarget' . func_camelize($sTargetType);
     if (method_exists($this, $sMethod)) {
         return $this->{$sMethod}($iTargetId);
     }
     return false;
 }
 /**
  * Устанавливает значение поля текущей сущности
  *
  * @param string $sField
  * @param string|mixed $sValue
  */
 protected function setValueOfCurrentEntity($sField, $sValue)
 {
     if ($this->oEntityCurrent) {
         call_user_func_array(array($this->oEntityCurrent, 'set' . func_camelize($sField)), array($sValue));
     }
 }
Exemplo n.º 21
0
 /**
  * Запускает валидацию конкретного поля сущности
  *
  * @param $oEntity	Объект сущности
  * @param $sField	Поле сущности
  *
  * @return bool
  */
 public function validateEntityField($oEntity, $sField)
 {
     /**
      * Получаем значение поля у сущности через геттер
      */
     $sValue = call_user_func_array(array($oEntity, 'get' . func_camelize($sField)), array());
     if (($sMsg = $this->validate($sValue)) !== true) {
         /**
          * Подставляем имя поля в сообщение об ошибке валидации
          */
         $sMsg = str_replace('%%field%%', is_null($this->label) ? $sField : $this->label, $sMsg);
         $oEntity->_addValidateError($sField, $sMsg);
     } else {
         return true;
     }
 }
Exemplo n.º 22
0
 /**
  * Проверка объекта
  *
  * @param string $sTargetType Тип владельца
  * @param int $iTargetId ID владельца
  * @return bool
  */
 public function CheckTarget($sTargetType, $iTargetId)
 {
     if (!$this->IsAllowTargetType($sTargetType)) {
         return false;
     }
     $sMethod = 'CheckTarget' . func_camelize($sTargetType);
     if (method_exists($this, $sMethod)) {
         return $this->{$sMethod}($iTargetId);
     }
     return false;
 }
Exemplo n.º 23
0
 public function NotifyRemovePreviewTarget($sTargetType, $iTargetId, $oRelationTarget)
 {
     if (!$this->IsAllowTargetType($sTargetType)) {
         return false;
     }
     $sMethod = 'NotifyRemovePreviewTarget' . func_camelize($sTargetType);
     if (method_exists($this, $sMethod)) {
         return $this->{$sMethod}($iTargetId, $oRelationTarget);
     }
     return false;
 }
Exemplo n.º 24
0
 /**
  * Переключает состояние плагина  активный/не активный
  *
  * @param string $sPlugin	Название плагина(код)
  * @param $sAction	Действие - activate/deactivate
  * @return null|bool
  */
 public function Toggle($sPlugin, $sAction)
 {
     $aPlugins = $this->GetList();
     if (!isset($aPlugins[$sPlugin])) {
         return null;
     }
     $sPluginName = func_camelize($sPlugin);
     switch ($sAction) {
         case 'activate':
         case 'deactivate':
             $sAction = ucfirst($sAction);
             $sFile = "{$this->sPluginsDir}{$sPlugin}/Plugin{$sPluginName}.class.php";
             if (is_file($sFile)) {
                 require_once $sFile;
                 $sClassName = "Plugin{$sPluginName}";
                 $oPlugin = new $sClassName();
                 if ($sAction == 'Activate') {
                     /**
                      * Проверяем совместимость с версией LS
                      */
                     if (defined('LS_VERSION') and version_compare(LS_VERSION, (string) $aPlugins[$sPlugin]['property']->requires->livestreet, '<')) {
                         $this->Message_AddError($this->Lang_Get('plugins_activation_version_error', array('version' => $aPlugins[$sPlugin]['property']->requires->livestreet)), $this->Lang_Get('error'), true);
                         return;
                     }
                     /**
                      * Проверяем наличие require-плагинов
                      */
                     if ($aPlugins[$sPlugin]['property']->requires->plugins) {
                         $aActivePlugins = $this->GetActivePlugins();
                         $iConflict = 0;
                         foreach ($aPlugins[$sPlugin]['property']->requires->plugins->children() as $sReqPlugin) {
                             if (!in_array($sReqPlugin, $aActivePlugins)) {
                                 $iConflict++;
                                 $this->Message_AddError($this->Lang_Get('plugins_activation_requires_error', array('plugin' => func_camelize($sReqPlugin))), $this->Lang_Get('error'), true);
                             }
                         }
                         if ($iConflict) {
                             return;
                         }
                     }
                     /**
                      * Проверяем, не вступает ли данный плагин в конфликт с уже активированными
                      * (по поводу объявленных делегатов)
                      */
                     $aPluginDelegates = $oPlugin->GetDelegates();
                     $aPluginInherits = $oPlugin->GetInherits();
                     $iConflict = 0;
                     foreach ($this->aDelegates as $sGroup => $aReplaceList) {
                         $iCount = 0;
                         if (isset($aPluginDelegates[$sGroup]) and is_array($aPluginDelegates[$sGroup]) and $iCount = count($aOverlap = array_intersect_key($aReplaceList, $aPluginDelegates[$sGroup]))) {
                             $iConflict += $iCount;
                             foreach ($aOverlap as $sResource => $aConflict) {
                                 $this->Message_AddError($this->Lang_Get('plugins_activation_overlap', array('resource' => $sResource, 'delegate' => $aConflict['delegate'], 'plugin' => $aConflict['sign'])), $this->Lang_Get('error'), true);
                             }
                         }
                         if (isset($aPluginInherits[$sGroup]) and is_array($aPluginInherits[$sGroup]) and $iCount = count($aOverlap = array_intersect_key($aReplaceList, $aPluginInherits[$sGroup]))) {
                             $iConflict += $iCount;
                             foreach ($aOverlap as $sResource => $aConflict) {
                                 $this->Message_AddError($this->Lang_Get('plugins_activation_overlap', array('resource' => $sResource, 'delegate' => $aConflict['delegate'], 'plugin' => $aConflict['sign'])), $this->Lang_Get('error'), true);
                             }
                         }
                         if ($iCount) {
                             return;
                         }
                     }
                     /**
                      * Проверяем на конфликт с наследуемыми классами
                      */
                     $iConflict = 0;
                     foreach ($aPluginDelegates as $sGroup => $aReplaceList) {
                         foreach ($aReplaceList as $sResource => $aConflict) {
                             if (isset($this->aInherits[$sResource])) {
                                 $iConflict += count($this->aInherits[$sResource]['items']);
                                 foreach ($this->aInherits[$sResource]['items'] as $aItem) {
                                     $this->Message_AddError($this->Lang_Get('plugins_activation_overlap_inherit', array('resource' => $sResource, 'plugin' => $aItem['sign'])), $this->Lang_Get('error'), true);
                                 }
                             }
                         }
                     }
                     if ($iConflict) {
                         return;
                     }
                 }
                 $bResult = $oPlugin->{$sAction}();
             } else {
                 /**
                  * Исполняемый файл плагина не найден
                  */
                 $this->Message_AddError($this->Lang_Get('plugins_activation_file_not_found'), $this->Lang_Get('error'), true);
                 return;
             }
             if ($bResult) {
                 /**
                  * Переопределяем список активированных пользователем плагинов
                  */
                 $aActivePlugins = $this->GetActivePlugins();
                 if ($sAction == 'Activate') {
                     /**
                      * Вносим данные в файл об активации плагина
                      */
                     $aActivePlugins[] = $sPlugin;
                 } else {
                     /**
                      * Вносим данные в файл о деактивации плагина
                      */
                     $aIndex = array_keys($aActivePlugins, $sPlugin);
                     if (is_array($aIndex)) {
                         unset($aActivePlugins[array_shift($aIndex)]);
                     }
                 }
                 /**
                  * Сбрасываем весь кеш, т.к. могут быть закешированы унаследованые плагинами сущности
                  */
                 $this->Cache_Clean();
                 if (!$this->SetActivePlugins($aActivePlugins)) {
                     $this->Message_AddError($this->Lang_Get('plugins_activation_file_write_error'), $this->Lang_Get('error'), true);
                     return;
                 }
                 /**
                  * Очищаем компиленые шаблоны от Smarty
                  */
                 $oSmarty = $this->Viewer_GetSmartyObject();
                 $oSmarty->clearCompiledTemplate();
             }
             return $bResult;
         default:
             return null;
     }
 }
Exemplo n.º 25
0
 /**
  * Удаляет плагины с сервера
  *
  * @param array $aPlugins	Список плагинов для удаления
  */
 public function Delete($aPlugins)
 {
     if (!is_array($aPlugins)) {
         $aPlugins = array($aPlugins);
     }
     $aActivePlugins = $this->GetActivePlugins();
     foreach ($aPlugins as $sPluginCode) {
         if (!is_string($sPluginCode)) {
             continue;
         }
         /**
          * Если плагин активен, деактивируем его
          */
         if (in_array($sPluginCode, $aActivePlugins)) {
             $this->Toggle($sPluginCode, 'deactivate');
         }
         /**
          * Выполняем кастомный метод удаление плагина
          */
         $sPluginName = func_camelize($sPluginCode);
         $sFile = "{$this->sPluginsDir}{$sPluginCode}/Plugin{$sPluginName}.class.php";
         if (is_file($sFile)) {
             require_once $sFile;
             $sClassName = "Plugin{$sPluginName}";
             $oPlugin = new $sClassName();
             if ($oPlugin->Delete()) {
                 /**
                  * Удаляем директорию с плагином
                  */
                 func_rmdir($this->sPluginsDir . $sPluginCode);
             }
         }
     }
 }