sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
private function initDebug()
{
if (!$this->getVar('debug_level') && !isset($_REQUEST['debug_level'])) return;
$this->debugMode = $this->getVar('debug_level') | $_REQUEST['debug_level'];
$this->_debug_writer = new \Zend_Log_Writer_Firebug();
$this->_debugger_request = new \Zend_Controller_Request_Http();
$this->_debugger_response = new \Zend_Controller_Response_Http();
$this->_debugger_channel = \Zend_Wildfire_Channel_HttpHeaders::getInstance();
$this->_debugger_channel->setRequest($this->_debugger_request);
$this->_debugger_channel->setResponse($this->_debugger_response);
$this->_debugger = new \Zend_Log($this->_debug_writer);
$this->_debugger->addPriority('SQL', DEBUG_SQL);
$this->_debugger->addPriority('CACHE', DEBUG_CACHE);
$this->_debugger->addPriority('BANNER', DEBUG_BANNER);
ob_start();
ini_set('display_errors', 1);
}
|
Инициализация дебаггера
@return void
|
entailment
|
public function initSession()
{
if (php_sapi_name() != 'cli') {
if (!isset($_COOKIE['ccms'])) {
$this->_uid = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'].rand());
} else {
$a = explode('.', $_COOKIE['ccms']);
$this->_uid = $a[0];
$this->_last_visit = $a[1];
}
setcookie('ccms',$this->_uid.'.'.time(),time()+REMEMBER_ME_SECONDS,'/');
}
\Zend_Session::setSaveHandler(new SessionSaveHandler());
$this->_session = new \Zend_Session_Namespace(SESSION_NAMESPACE);
if (isset($this->_session->locale) && $this->_session->locale) {
$this->_locale->setLocale($this->_session->locale);
}
}
|
Инициализация сессии
@return void
|
entailment
|
public static function shutdown()
{
if (self::$_instance->_debugger_channel) {
self::$_instance->_debugger_channel->flush();
self::$_instance->_debugger_response->sendHeaders();
ob_end_flush();
}
if (self::$_instance->cronMode) {
if ( php_sapi_name() == 'cli' ) {
$txt = ob_get_contents();
ob_end_clean();
if (self::$_instance->cronLog) {
file_put_contents(self::$_instance->cronLog, date('Y.m.d H:i:s')."\n===================\n".$txt."\n\n", FILE_APPEND);
}
exit(self::$_instance->exitCode);
}
}
if ( php_sapi_name() != 'cli' ) {
if (self::$_instance->exitCode) {
http_response_code(500);
}
}
}
|
Завершение работы приложения
@return void
|
entailment
|
public function debug($mode, $str)
{
if (!$this->_debugger) return;
$this->_debugger->log($str, $mode);
}
|
/*
Принимает отладочное сооющение
@param string тип сообщения
@param string сообщение
@return void
|
entailment
|
public function getServer()
{
if (!$this->_server) {
$this->_server = Server::getByDomain($_SERVER['HTTP_HOST']);
if ($this->_server)
$this->debug(DEBUG_COMMON, 'Server ID: '.$this->_server->id);
}
return $this->_server;
}
|
Возвращает текущий сервер
@return Server
|
entailment
|
public function setServer($server)
{
if (is_a($server,'Cetera\\Server')) {
$this->_server = $server;
return $this;
}
if (is_int($server)) {
$this->_server = Server::getById($server);
return $this;
}
}
|
Установливает текущий сервер.
@param int|Server $server сервер
@return void
|
entailment
|
private function decodeRequestUri()
{
foreach ($this->routes['general'] as $p => $callable)
{
if (preg_match('|^'.$p.'|', $_SERVER['REQUEST_URI'], $matches)) {
list($url) = explode('?',$_SERVER['REQUEST_URI']);
$this->_unparsedUrl = trim(str_replace($matches[0], '', $url),'/');
$res = $callable($matches);
if ($res) die();
}
/*
if (substr($_SERVER['REQUEST_URI'],0,strlen($p)) == $p )
{
list($url) = explode('?',$_SERVER['REQUEST_URI']);
$this->_unparsedUrl = trim(str_replace($p, '', $url),'/');
$res = $callable();
if ($res) die();
}
*/
}
$this->_unparsedUrl = null;
$this->_catalog = $this->getServer();
$this->_urlPath[] = $this->_catalog;
if (!$this->_catalog) return;
list($url) = explode('?',$_SERVER['REQUEST_URI']);
$url = trim($url, '/');
$dir = explode("/", $url);
/*
if (sizeof($dir) && $dir[0] == PREVIEW_PREFIX) {
array_shift($dir);
$this->_previewMode = true;
}
*/
while ($alias = array_shift($dir)) {
try {
$c = $this->_catalog->prototype->getChildByAlias($alias);
$this->_catalog = $c;
$this->_urlPath[] = $this->_catalog;
$this->debug(DEBUG_COMMON, 'Catalog: '.$alias.'('.$c->id.')');
} catch (\Exception $e) {
array_unshift($dir, $alias);
break;
}
}
$this->_unparsedUrl = implode('/', $dir);
}
|
Парсит REQUEST_URI
@return void
|
entailment
|
public function setFrontOffice($fo = TRUE)
{
if ($fo != $this->_fo) $this->_translator = FALSE;
$this->_fo = $fo;
}
|
Указать приложению, работает FrontOffice или нет
@param bool
@return void
|
entailment
|
public function getGroups()
{
if (!sizeof($this->_groups)) {
$translator = $this->getTranslator();
$this->_groups = array(
GROUP_ALL => array(
'id' => GROUP_ALL,
'name' => $translator->_('Все'),
'describ' => '',
'user_defined' => 0
),
GROUP_BACKOFFICE => array(
'id' => GROUP_BACKOFFICE,
'name' => $translator->_('Пользователи BackOffice'),
'describ' => $translator->_('Имеют право входа в систему управления сайтом'),
'user_defined' => 0
),
GROUP_ADMIN => array(
'id' => GROUP_ADMIN,
'name' => $translator->_('Администраторы'),
'describ' => $translator->_('Администраторы имеют полные, ничем неограниченные права доступа'),
'user_defined' => 0
),
);
}
return $this->_groups + $this->_user_groups;
}
|
Возвращает список встроенных в систему групп пользователей
@return array
|
entailment
|
public function initPlugins()
{
if ($this->_plugins_loaded) return;
$this->_plugins_loaded = array();
$translator = $this->getTranslator();
foreach (Plugin::enum() as $plugin) {
if (!$plugin->isEnabled()) continue;
if (file_exists(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.PLUGIN_CLASSES) && is_dir(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.PLUGIN_CLASSES)) {
$loader = new \Composer\Autoload\ClassLoader();
$parts = explode('_',$plugin->name);
$prefix = '';
foreach ($parts as $p) $prefix .= ucfirst($p);
$loader->add($prefix, DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.PLUGIN_CLASSES);
$loader->register();
}
if (file_exists(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.'widgets') && is_dir(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.'widgets')) {
$this->_widgetPaths[] = DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.'widgets';
}
$this->_plugins_loaded[] = $plugin;
}
foreach ($this->_plugins_loaded as $plugin) {
if (file_exists(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.PLUGIN_CONFIG)) try {
include(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.PLUGIN_CONFIG);
}
catch (\Exception $e) {
}
}
foreach (Theme::enum() as $theme) {
if (file_exists(DOCROOT.THEME_DIR.DIRECTORY_SEPARATOR.$theme->name.DIRECTORY_SEPARATOR.'classes') && is_dir(DOCROOT.THEME_DIR.DIRECTORY_SEPARATOR.$theme->name.DIRECTORY_SEPARATOR.'classes'))
{
$loader = new \Composer\Autoload\ClassLoader();
$parts = explode('_',$theme->name);
$prefix = '';
foreach ($parts as $p) $prefix .= ucfirst($p);
$loader->add($prefix, DOCROOT.THEME_DIR.DIRECTORY_SEPARATOR.$theme->name.DIRECTORY_SEPARATOR.'classes');
$loader->register();
}
if (file_exists(DOCROOT.THEME_DIR.DIRECTORY_SEPARATOR.$theme->name.DIRECTORY_SEPARATOR.PLUGIN_CONFIG)) try {
include(DOCROOT.THEME_DIR.DIRECTORY_SEPARATOR.$theme->name.DIRECTORY_SEPARATOR.PLUGIN_CONFIG);
}
catch (\Exception $e) {
}
}
}
|
/*
@ignore
|
entailment
|
public function getUserVar($name, $server = 0)
{
if (!$server) $server = $this->getServer()->id;
$server = (int)$server;
if (!$server) return FALSE;
$slot = new Cache\Slot\Variable($server, $name);
if (false === ($value = $slot->load())) {
$value = $this->getConn()->fetchColumn("SELECT IFNULL(B.value, A.value) FROM vars A LEFT JOIN vars_servers B ON (A.id=B.var_id and B.server_id=?) where A.name=?",
array($server, $name),
0
);
if ($value) {
$slot->addTag(new Cache\Tag\Variable());
$slot->save($value);
}
}
return $value;
}
|
Получить пользовательскую переменную
@param string $name имя переменной
@return mixed
|
entailment
|
public function eventLog($event_code, $text = FALSE)
{
if (!$this->_connected) return;
$this->getConn()->insert(
'event_log',
array(
'dat' => new \DateTime(),
'user_id' => (int)$this->getUser()->id,
'code' => $event_code,
'text' => $text,
),
array('datetime')
);
}
|
Делает запись в журнал аудита
@param int $event_code код события
@param string $text дополнительное описание
@return void
|
entailment
|
public function getLoggableEvents() {
$list = [
EVENT_CORE_USER_REGISTER,
EVENT_CORE_BO_LOGIN_OK,
EVENT_CORE_BO_LOGIN_FAIL,
EVENT_CORE_LOG_CLEAR,
//EVENT_CORE_DIR_CREATE,
//EVENT_CORE_DIR_EDIT,
//EVENT_CORE_DIR_DELETE,
//EVENT_CORE_MATH_CREATE,
//EVENT_CORE_MATH_EDIT,
//EVENT_CORE_MATH_DELETE,
//EVENT_CORE_MATH_PUB,
//EVENT_CORE_MATH_UNPUB,
//EVENT_CORE_USER_PROP,
];
return array_diff(
array_merge ( $list, (array)$this->configGet('events_log_enabled') ),
(array)$this->configGet('events_log_disabled')
);
}
|
Возвращает список событий, сохраняемых в журнал аудита
@return array
|
entailment
|
public function addLoggableEvent($event_code) {
$disabled = (array)$this->configGet('events_log_disabled');
$key = array_search($event_code, $disabled);
if ($key !== false) {
unset($disabled[$key]);
$this->configSet('events_log_disabled', $disabled);
}
if (!in_array($event_code, $this->getLoggableEvents())) {
$enabled = (array)$this->configGet('events_log_enabled');
$enabled[] = $event_code;
$this->configSet('events_log_enabled', $enabled);
}
}
|
Разрешает сохранение события в журнал аудита
@param int $event_code код события
@return void
|
entailment
|
public function eventHandler($event, $params) {
if (in_array($event, $this->getLoggableEvents())) {
$text = false;
if (isset($params['message'])) {
$text = $params['message'];
}
$this->eventLog($event, $text);
}
$data = self::getDbConnection()->fetchAll('SELECT * FROM mail_templates WHERE active=1 and event = ?', array($event));
foreach ($data as $template) {
$twig = new \Twig_Environment(
new \Twig_Loader_Array( $template ),
array(
'autoescape' => false,
)
);
$twig->addFunction(new \Twig_SimpleFunction('_', function($text) {
return \Cetera\Application::getInstance()->getTranslator()->_($text);
}));
$mail = new \PHPMailer(true);
$params['mailer'] = $mail;
$emailStr = $twig->render('mail_to', $params);
if (!$emailStr) continue;
$toEmails = preg_split("/[,;]/", $emailStr );
if(!empty($toEmails)) {
foreach($toEmails as $address) {
if (trim($address)) {
$mail->AddAddress(trim($address));
}
}
}
else {
continue;
}
$mail->CharSet = 'utf-8';
$mail->ContentType = $template['content_type'];
$mail->setFrom($twig->render('mail_from_email', $params), $twig->render('mail_from_name', $params));
$mail->Subject = $twig->render('mail_subject', $params);
$mail->Body = $twig->render('mail_body', $params);
$mail->Send();
}
}
|
Глобальный обработчик событий. Записывает события в журнал аудита. Рассылает почтовые уведомления.
@return void
|
entailment
|
public function getWidget($name, $params = null, $uid = null)
{
$id = 0;
$f = null;
$widgetName = null;
if (is_array($name)) {
$params = $name;
if (!isset($params['name'])) throw new \Exception('Не задан параметр "name"');
$widgetName = $params['name'];
}
elseif (is_int($name)) {
$id = (int)$name;
$f = $this->getConn()->fetchAssoc('SELECT * FROM widgets WHERE id=?', array($id));
if (!$f) throw new \Exception('Не удалось загрузить виджет id='.$name);
$widgetName = $f['widgetName'];
$params = unserialize($f['params']);
}
elseif(!$params) {
$f = $this->getConn()->fetchAssoc('SELECT * FROM widgets WHERE widgetAlias=? ORDER BY id DESC', array($name));
if ($f) {
$id = $f['id'];
$widgetName = $f['widgetName'];
$params = unserialize($f['params']);
} else {
$widgetName = $name;
}
}
else {
$widgetName = $name;
}
$this->initWidgets();
if (!isset($this->_widgets[$widgetName])) {
if (!isset($this->_widgetAliases[$widgetName]))
throw new \Exception( sprintf($this->getTranslator()->_('Виджет "%s" не зарегистрирован'),$widgetName) );
$widgetName = $this->_widgetAliases[$widgetName];
}
$class = $this->_widgets[$widgetName]['class'];
$widget = new $class($id, $params, $uid);
$widget->application = $this;
$widget->widgetName = $widgetName;
$widget->widgetDescrib = $this->_widgets[$widgetName]['describ'];
if ($f)
{
$widget->widgetAlias = $f['widgetAlias'];
$widget->widgetTitle = $f['widgetTitle'];
$widget->widgetDisabled = $f['widgetDisabled'];
$widget->widgetProtected = $f['protected'];
}
return $widget;
}
|
Возвращает виджет
@param mixed $param<br>
integer - возвращает сохраненный в БД виджет с указанным id<br>
string - возвращает созданный в БО виджет с указанным Alias или создает экземпляр виджета c указанным Name<br>
array - создает экземпляр виджета с заданными параметрами. Обязательный параметр в массиве - Name виджета<br>
@return Widget
|
entailment
|
public function registerWidget($config)
{
if (!isset($config['name'])) return false;
$config['path'] = $this->getCallerPath();
$name = $config['name'];
if (class_exists($config['class']) && is_subclass_of($config['class'], '\\Cetera\\Widget\\Widget')) {
$config['class']::setData($config);
}
else {
$config['class'] = '\\Cetera\\Widget\\Widget';
}
$config['icon'] = $this->getCallerPath().'/'.$config['icon'];
$this->initWidgets();
$this->_widgets[$name] = $config;
}
|
Добавляет виджет в коллекцию
@return void
|
entailment
|
public function ping()
{
try {
$last_ping = (int)self::configGet('last_ping');
if ( time() - $last_ping < 60*60*24 ) return;
$plugins = array();
foreach ( $this->getPlugins() as $p)
{
$plugins[] = array(
'id' => $p->id,
'version' => $p->version,
'title' => $p->title
);
}
$client = new \GuzzleHttp\Client();
$res = $client->post(PING_URL, array(
'verify' => false,
'form_params' => array(
'server' => $_SERVER,
'version' => VERSION,
'plugins' => $plugins
)
));
self::configSet('last_ping', time() );
} catch (\Exception $e) {}
}
|
/*
@internal
|
entailment
|
public function getTwig()
{
if (!$this->twig)
{
$loader = new \Twig_Loader_Filesystem( $this->getTemplateDir().'/'.TWIG_TEMPLATES_PATH, getcwd() );
if (file_exists($this->getTemplateDir().'/widgets'))
$loader->addPath( $this->getTemplateDir().'/widgets' ,'widget' );
foreach ($this->_widgetPaths as $p) $loader->addPath( $p ,'widget' );
$loader->addPath( CMSROOT.'/widgets' ,'widget' );
foreach ($this->_widgetPaths as $p) $loader->addPath( $p ,'widget_distrib' );
$loader->addPath( CMSROOT.'/widgets' ,'widget_distrib' );
$options = array(
'cache' => TWIG_CACHE_DIR,
'auto_reload' => true,
'strict_variables' => true,
);
if ($this->debugMode) {
$options['cache'] = false;
$options['debug'] = true;
}
$this->twig = new \Twig_Environment($loader, $options);
$this->twig->addTokenParser( new Twig\TokenParser\Widget() );
$this->twig->addExtension( new \Twig_Extensions_Extension_Text() );
$this->twig->addExtension(new \Twig_Extensions_Extension_I18n());
$this->twig->addExtension(new \Twig_Extension_Debug());
$this->twig->addFunction(new \Twig_SimpleFunction('_', function($text) {
return Application::getInstance()->getTranslator()->_($text);
}));
$this->twig->addFilter( new \Twig_SimpleFilter('phone', function($num) {
return preg_replace('/[^\+^\d]/i','', $num);
} ) );
$this->twig->addGlobal('application', $this);
$this->twig->addGlobal('t', $this->getTranslator());
$this->twig->addGlobal('s', $_SERVER);
}
return $this->twig;
}
|
Создает и возвращает шаблонизатор Twig
@return Twig_Environment
|
entailment
|
public function showAdminPanel()
{
$u = $this->getUser();
if ($u && $u->allowBackOffice())
{
if (COMPOSER_INSTALL) {
$this->addCSS('/cms/css/global.css');
$this->addScript('/cms/js/vendor.js');
$this->addScript('/cms/config.php');
$this->addScript('/cms/js/admin-panel.js');
}
else {
$this->addCSS('/'.LIBRARY_PATH.'/extjs4/resources/css/ext-all.css');
$this->addCSS('/'.LIBRARY_PATH.'/cropper/cropper.min.css');
$this->addCSS('/cms/css/main.css');
$this->addScript('/'.LIBRARY_PATH.'/extjs4/ext-all.js');
$this->addScript('/'.LIBRARY_PATH.'/ace/ace.js');
$this->addScript('/'.LIBRARY_PATH.'/cropper/cropper.min.js');
$this->addScript('/cms/config.php');
$this->addScript('/cms/admin-panel.js');
}
}
}
|
Выводит на странице фронтофиса админ-панель
@return void
|
entailment
|
public function setPageProperty($name, $value, $array = false, $unique = true)
{
if (!$array)
{
$this->params[$name] = $value;
}
else
{
if (!isset($this->params[$name]) || !is_array($this->params[$name]))
{
$this->params[$name] = array();
}
if (is_bool($unique))
{
if ( $unique && in_array($value, $this->params[$name]) ) return $this;
$this->params[$name][] = $value;
}
else
{
$this->params[$name][$unique] = $value;
}
}
return $this;
}
|
Устанавливает определенное свойство страницы фронтофиса
@param string $name Имя свойства
@param string $value Значение свойства
@param boolean $array Используется ли свойство как массив значений. Если true, то новое значение добавляется в массив
@param boolean $unique Проверять значение на уникальность. Если значение уже есть в массиве, то новое добавлено не будет
@return Cetera\Application Экземпляр приложения
|
entailment
|
public function cronJob($logFile = false)
{
$this->cronMode = true;
$this->cronLog = $logFile;
if ( php_sapi_name() == 'cli' ) {
ob_start();
}
else {
header('Content-type: text/plain; charset=UTF-8');
}
}
|
Переключает приложение в режим cron-работы.
При этом весь выходной поток, включая сообщения об ошибках направляются в лог-файл
По окончании работы скрипта в лог записывается текущее время
@param string $logFile Имя лог-файла
@return void
|
entailment
|
public function contentExists() {
$r = Catalog::getRoot();
if (count($r->children) > 1) return true;
if (count($r->children) < 1) return false;
$s = $r->children[0];
if (count($s->children)) return true;
if (count($s->getMaterials()->unpublished())) return true;
return false;
}
|
Определеет, опубликован ли пользовательский контент
@return boolean
|
entailment
|
public function getXml()
{
$res = '<widget widgetTitle="'.htmlspecialchars($this->widgetTitle).'" widgetName="'.htmlspecialchars($this->widgetName).'">'."\n";
$res .= "<![CDATA[\n".serialize($this->getParams())."\n]]>\n";
$res .= '</widget>'."\n";
return $res;
}
|
Экспорт виджета в XML
|
entailment
|
private function getFieldsForEdit() {
global $editors, $field_editors, $translator;
if ($this->fields_def) return;
ob_start();
$fields = $this->objectDefinition->getFields($this->catalog);
$this->fields_def = array();
foreach ($fields as $id => $f) {
if (!$f['shw'] && $f['name'] != 'alias') continue;
$this->fields_def[$id] = $f;
$_editor = (int)$f['editor'];
if ($f['pseudo_type'])
$f['type'] = $f['pseudo_type'];
if (isset($editors[EDITOR_HIDDEN]))
$this->fields_def[$id]['editor_str'] = $editors[EDITOR_HIDDEN];
if (is_array($field_editors[$f['type']])) {
if (!in_array($_editor, $field_editors[$f['type']]))
$_editor = $field_editors[$f['type']][0];
if ($_editor == EDITOR_USER) {
if (file_exists(PLUGIN_MATH_DIR.'/'.$f['editor_user'].'.php')) {
$this->fields_def[$id]['editor_str'] = $f['editor_user'];
include_once(PLUGIN_MATH_DIR.'/'.$f['editor_user'].'.php');
}
else {
$_editor = $field_editors[$f['type']][0];
}
}
if ( isset($editors[$_editor]) ) {
$this->fields_def[$id]['editor_str'] = $editors[$_editor];
if ( file_exists('editors/'.$editors[$_editor].'.php') )
include_once('editors/'.$this->fields_def[$id]['editor_str'].'.php');
}
}
}
$this->initData = ob_get_contents();
ob_end_clean();
}
|
getFieldsForEdit
возвращает список полей в материалах
подгружает необходимые редакторы полей
@return array
|
entailment
|
private function getLinks()
{
if (!$this->objectId) return;
// поля типа FIELD_MATERIAL
$fields = self::getDbConnection()->fetchAll('SELECT * FROM types_fields WHERE type='.FIELD_MATERIAL.' and pseudo_type=0 and len='.$this->objectDefinition->id);
// поля типа PSEUDO_FIELD_TAGS
$fields2 = self::getDbConnection()->fetchAll('SELECT * FROM types_fields WHERE pseudo_type='.PSEUDO_FIELD_TAGS.' and len='.$this->objectDefinition->id);
$fields = array_merge($fields, $fields2);
// поля типа FIELD_LINK или FIELD_LINKSET
if ($this->catalog > 0) {
$catalog = Catalog::getById($this->catalog);
// итератор всех разделов имеющих тип материалов как у редактируемого материала
$sections = new Iterator\Catalog\Catalog();
$sections->where('typ='.$this->objectDefinition->id);
if (!count($sections)) return;
// получаем все поля, ссылающиеся на эти разделы
$data = self::getDbConnection()->fetchAll('SELECT * FROM types_fields WHERE type IN ('.FIELD_LINK.','.FIELD_LINKSET.') and pseudo_type=0 and len IN ('.implode(',',$sections->idArray()).')');
foreach ($data as $f) {
$c = Catalog::getById($f['len']);
// оставляем только поля, ссылающиеся на раздел текущего материала или его родителей
if ($catalog->path->has( $c )) {
$fields[] = $f;
}
}
}
ob_start();
foreach ($fields as $f) try {
$od = ObjectDefinition::findById($f['id']);
$f['describ'] = $od->getDescriptionDisplay();
$f['editor_str'] = 'editor_linkset_link';
if ( file_exists('editors/'.$f['editor_str'].'.php') )
include_once('editors/'.$f['editor_str'].'.php');
$this->fields_def[] = $f;
} catch (\Exception $e) {}
$this->initData .= ob_get_contents();
ob_end_clean();
}
|
getLinkTypes
возвращает список типов материалов в которых есть поля типа FIELD_LINK или FIELD_MATERIAL - ссылки на редактируемый материал
@return array
|
entailment
|
public function multiLoad($ids, $doNotTestCacheValidity = false)
{
if (!is_array($ids)) {
\Zend_Cache::throwException('multiLoad() expects parameter 1 to be array, ' . gettype($ids) . ' given');
}
if ($doNotTestCacheValidity) {
$this->_log("\Zend_Cache_Backend_Memcached::load() : \$doNotTestCacheValidity=true is unsupported by the Memcached backend");
}
$tmp = $this->_getHandle()->get($ids);
foreach ($tmp as $k => $v) {
if (is_array($v)) {
$tmp[$k] = $v[0];
}
}
return $tmp;
}
|
Loads an array of items from the memcached.
Extends \Zend_Cache_Backend_Memcached with support of multi-get feature.
@param array $ids A list of IDs to be loaded.
@param bool $doNotTestCacheValidity See parent method.
@return array An array of values for each ID.
|
entailment
|
private static function _getPrivateProp($obj, $name)
{
$arraized = (array)$obj;
foreach ($arraized as $k => $v) {
if (substr($k, -strlen($name)) === $name) {
return $v;
}
}
throw new Exception\CMS(
"Cannot find $name property in \Zend_Cache_Backend_Memcached; properties are: "
. array_map('addslashes', array_keys($arraized))
);
}
|
Reads a private or protected property from the object.
Unfortunately we have to use this hack, because \Zend_Cache_Backend_Memcached
does not declare $_memcache handle as protected.
In PHP private properties are named with \x00 in the name.
@param object $obj Object to read a property from.
@param string $name Name of a protected or private property.
@return mixed Property value or exception if property is not found.
|
entailment
|
public function idArray() {
$data = [];
foreach ($this->getElements() as $item) $data[] = $item->id;
return $data;
}
|
Массив идентификаторов объектов
@return array
|
entailment
|
public function valid()
{
if ($this->dontUsePaging || !$this->itemCountPerPage)
{
return $this->position >= 0 && $this->position < count($this->getElements());
}
if ($this->position < 0) return false;
if ($this->itemCountPerPage && $this->position >= $this->itemCountPerPage) return false;
if ($this->getPosition() >= count($this->getElements())) return false;
return true;
}
|
Текущий элемент существует?
@return bool
|
entailment
|
public function append($obj, $check = true)
{
if ( $check && $this->findIndexById( $obj->id ) >= 0) return $this;
$this->elements[] = $obj;
return $this;
}
|
Добавляет элемент
@param $elm FSObject добавляемый раздел
@return Iterator\Object
|
entailment
|
public function getLastIndex()
{
if (!$this->itemCountPerPage) return $this->getCountAll();
$count = $this->itemCountPerPage + $this->itemCountPerPage * ($this->pageNumber - 1);
if ($count > $this->getCountAll()) $count = $this->getCountAll();
return $count;
}
|
Порядковый номер последнего элемента
@return int
|
entailment
|
public function offsetSet($offset, $value) {
$this->getElements();
$this->elements[$this->getPosition($offset)] = $value;
}
|
Нельзя изменять содержимое
@return void
|
entailment
|
public function offsetExists($offset) {
$this->getElements();
return isset($this->elements[$this->getPosition($offset)]);
}
|
Существует ли элемент на данной позиции
@param int $offser позиция
@return bool
|
entailment
|
public function offsetGet($offset) {
$this->getElements();
return isset($this->elements[$this->getPosition($offset)]) ? $this->elements[$this->getPosition($offset)] : null;
}
|
Получить элемент на данной позиции
@param int $offser позиция
@return FSObject
|
entailment
|
public function implode($element = 'name', $filter = false)
{
$ret = '';
$total = 0;
$skip = array();
foreach ($this as $id => $item) {
$skip[$id] = 1;
if (is_callable($filter))
{
if (substr_count($filter, '::')) {
list($class, $method) = explode('::', $filter);
$c = new $class($item);
if (!$c->$method($item)) continue;
} else {
if (!$filter($item)) continue;
}
}
$skip[$id] = 0;
$total++;
}
$index = 0;
foreach ($this as $id => $item) {
if ($skip[$id]) continue;
if (is_callable($element)) {
if (is_string($element) && substr_count($element, '::')) {
list($class, $method) = explode('::', $element);
$c = new $class();
$string = $c->$method($item, $index, $index == 0, $index == $total-1, $total);
} else {
$string = $element($item, $index, $index == 0, $index == $total-1, $total);
}
} elseif (method_exists($item, $element)) {
$string = $item->$element();
} else {
$string = $item->$element;
}
$index++;
$ret .= $string;
}
return $ret;
}
|
Выстраивает элементы в строку
@param mixed $element свойство объекта, которое использовать для формирования строки или функция, которая возвращает строку
@param string $filter функция фильтрации элементов, должна возвращать false, если элемент следует пропустить
@return string
@todo когда будет PHP5.3, заменить $c = new $class(); $c->$method(... на $class::$method(...
|
entailment
|
public static function install($theme, $status = null, $translator = null, $extract_initial_data = false, $content = null)
{
if (!$translator) $translator = Application::getInstance()->getTranslator();
// предыдущая версия темы
$previousTheme = self::find($theme);
if ($previousTheme) $previousTheme->grabInfo();
$themePath = WWWROOT.THEME_DIR.'/'.$theme;
$archiveFile = WWWROOT.THEME_DIR.'/'.$theme.'.zip';
// Загрузка
if ($status) $status($translator->_('Загрузка темы'), true);
if (!file_exists(WWWROOT.THEME_DIR)) mkdir(WWWROOT.THEME_DIR);
if (!file_exists(WWWROOT.THEME_DIR))
throw new \Exception($translator->_('Каталог').' '.DOCROOT.THEME_DIR.' '.$translator->_('не существует'));
if (!is_writable(WWWROOT.THEME_DIR))
throw new \Exception($translator->_('Каталог').' '.DOCROOT.THEME_DIR.' '.$translator->_('недоступен для записи'));
$client = new \GuzzleHttp\Client();
if (!$content) $content = $theme;
$res = $client->get(THEMES_INFO.'?download='.$content, ['verify' => false]);
$d = $res->getBody();
if (!$d) throw new \Exception($translator->_('Не удалось скачать тему'));
file_put_contents($archiveFile, $d);
if ($status) $status('OK', false);
/* не удаляем предыдущую версию, чтобы сохранить пользовательские файлы
if (file_exists($themePath)) {
// Удаление предыдущей версии
if ($status) $status($translator->_('Удаление предыдущей версии'), true);
Util::delTree($themePath);
if ($status) $status('OK', false);
}
*/
// Распаковка архива
if ($status) $status($translator->_('Распаковка архива'), true);
$zip = new \ZipArchive;
if($zip->open($archiveFile) === TRUE)
{
if(!$zip->extractTo(WWWROOT.THEME_DIR)) throw new Exception($translator->_('Не удалось распаковать архив').' '.$archiveFile);
$zip->close();
unlink($archiveFile);
if (file_exists(DOCROOT.THEME_DIR.'/'.$theme.'/'.PLUGIN_CONFIG))
include(DOCROOT.THEME_DIR.'/'.$theme.'/'.PLUGIN_CONFIG);
} else throw new \Exception('Не удалось открыть архив '.$archiveFile);
if ($status) $status('OK', false);
// Модификация БД
if ($status) $status($translator->_('Модификация БД'), true);
$schema = new Schema();
$schema->fixSchema('theme_'.$theme);
if ($status) $status('OK', false);
$t = new self($theme);
Plugin::installRequirements($t->requires, $status, $translator);
if ($extract_initial_data) {
$dbData = $themePath.'/'.THEME_DB_DATA;
if (file_exists($dbData)) {
if ($status) $status($translator->_('Начальная структура сайта'), true);
$schema->readDumpFile($dbData, true);
if ($status) $status('OK', false);
}
}
// В файле config.json конфингурация темы "по умолчанию". Устанавливаем её для всех серверов
if (file_exists($themePath.'/config.json')) {
$config = json_decode( file_get_contents($themePath.'/config.json'), true );
foreach (Server::enum() as $s) {
$t->loadConfig( $s );
if (!$t->config) {
$res = $config;
}
else {
$current = get_object_vars($t->config);
$res = array_merge( $config, $current );
}
$t->setConfig( $res, $s );
}
}
//
if (file_exists($themePath.'/'.THEME_INSTALL))
{
$currentTheme = self::find($theme);
include $themePath.'/'.THEME_INSTALL;
}
}
|
Установить тему из Marketplace
@param string $theme название темы
@param Callable $status метод или функция для приема сообщений
@param Zend_Translate $translator класс-переводчик
@param boolean $extract_initial_data распаковать данные БД: тексты, разделы и т.д.
|
entailment
|
public static function find($name)
{
if (!is_dir(DOCROOT.THEME_DIR.'/'.$name)) return false;
if (!file_exists(DOCROOT.THEME_DIR.'/'.$name.'/'.THEME_INFO)) return false;
return new self($name);
}
|
Возвращает тему с указанным именем
@return Cetera\Theme
|
entailment
|
public function addTranslation($translator)
{
if (!file_exists( $this->getPath().'/'.TRANSLATIONS )) return;
$translator->addTranslation( $this->getPath().'/'.TRANSLATIONS );
}
|
Добавлаяет переведенные ресурсы темы в переводчик
@param Zend_Translate $translator переводчик
@return void
|
entailment
|
public function delete()
{
Util::delTree( $this->getPath() );
foreach (Server::enum() as $s) {
$tname = str_replace( THEME_DIR.'/', '', $s->templateDir );
if ($tname == $this->name) {
$s->setTheme();
}
}
}
|
Удаляет установленную тему
@return void
|
entailment
|
public static function registerClass($id, $className)
{
if (! is_subclass_of($className, '\Cetera\Material') ) throw new \Exception('Класс '.$className.' должен быть наследником \Cetera\Material');
self::$userClasses[$id] = $className;
}
|
Зарегистрировать пользовательский класс для определенного типа материалов
@param int $id ID типа материалов
@param string $className Имя класса. Класс должен быть наследником \Cetera\Material
@return void
|
entailment
|
public static function create()
{
$params = func_get_arg(0);
$params = self::fix_params($params);
if (!$params['fixed'] && in_array($params['alias'], self::$reserved_aliases)) {
throw new Exception\CMS(Exception\CMS::TYPE_RESERVED);
}
$conn = DbConnection::getDbConnection();
$r = $conn->fetchAll("select id from types where alias='".$params['alias']."'");
if (count($r)) throw new Exception\CMS(Exception\CMS::TYPE_EXISTS);
$conn->executeQuery('DROP TABLE IF EXISTS '.$params['alias']);
$conn->executeQuery("create table ".$params['alias']." (
id int(11) NOT NULL auto_increment, idcat int(11), dat datetime, dat_update datetime, name varchar(2048),
type int(11), autor int(11) DEFAULT '0' NOT NULL, tag int(11) DEFAULT '1' NOT NULL, alias varchar(255) NOT NULL,
PRIMARY KEY (id), KEY idcat (idcat), KEY dat (dat), KEY alias (alias)
)");
$conn->executeQuery(
"INSERT INTO types (alias,describ, fixed) values (?,?,?)",
array($params['alias'], $params['describ'], (int)$params['fixed'])
);
$id = $conn->lastInsertId();
$translator = Application::getInstance()->getTranslator();
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag) values ($id,'tag', 3,'Sort[ru=Сортировка]', 1, 1, 0, 1, 1)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag) values ($id,'name', 1,'Title[ru=Заголовок]', 99, 1, 0, 1, 2)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag) values ($id,'alias', 1,'Alias', 255, 1, 1, 1, 3)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag) values ($id,'dat', 5,'Date create[ru=Дата создания]', 1, 1, 1, 0, 5)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag) values ($id,'dat_update', 5,'Edit date[ru=Дата изменения]', 1, 1, 1, 0, 6)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag,pseudo_type) values ($id,'autor', 6,'Author[ru=Автор]', -2, 1, 1, 0, 4,1003)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag) values ($id,'type', 3,'Properties[ru=Свойства]', 1, 1, 1, 0, 7)");
$conn->executeQuery("insert into types_fields (id,name,type,describ,len,fixed,required,shw,tag,pseudo_type) values ($id,'idcat', 6,'Section[ru=Раздел]', 0, 1, 1, 0, 8, 1008)");
return new self($id, $params['alias']);
}
|
Создает новый тип материалов
@param array $params параметры типа материалов:<br>
alias - alias типа, он же название создаваемой таблицы БД под этот тип материалов<br>
fixed - системный тип (невозможно удалить из админки)<br>
@return ObjectDefinition
@throws Exception\CMS если тип с таким alias уже существует
@throws Exception\CMS если alias зарезервирован
|
entailment
|
public function getFields( $dir = null ) {
$inherit = false;
if ($dir !== false && !is_a($dir, 'Cetera\\Catalog') && (int)$dir && $dir > 0) $dir = Catalog::getById($dir);
if (is_a($dir, 'Cetera\\Catalog'))
{
while ($dir->inheritFields && !$dir->isRoot()) $dir = $dir->getParent();
if (!$dir->inheritFields) {
$r = DbConnection::getDbConnection()->fetchAll('SELECT * FROM types_fields_catalogs WHERE type_id=? and catalog_id=?',[$this->id,$dir->id]);
$inherit = array();
foreach ($r as $f) $inherit[$f['field_id']] = $f;
}
}
$res = $this->_get_fields();
if ($inherit && count($inherit)) {
foreach ($res as $key => $val) {
if (isset($inherit[$val['field_id']])) {
if ($inherit[$val['field_id']]['force_hide'])
$res[$key]['shw'] = 0;
if ($inherit[$val['field_id']]['force_show'])
$res[$key]['shw'] = 1;
}
}
}
return $res;
}
|
Возвращает все поля данного типа материалов
@param int|Catalog $dir если указан раздел, то учитывается видимость полей, заданная для этого раздела
@return array
|
entailment
|
public function getField($fieldName) {
$fields = $this->_get_fields();
if (isset($fields[$fieldName])) {
return $fields[$fieldName];
} else {
throw new \Exception('Поле "'.$fieldName.'" не найдено');
}
}
|
Возвращает поле данного типа материалов
@param string $fieldName имя поля
@return ObjectField
|
entailment
|
public function delete() {
$r = DbConnection::getDbConnection()->fetchAll( "select id from dir_data where typ=?", [$this->id] );
foreach ($r as $f) {
$c = Catalog::getById($f[0]);
$c->delete();
}
DbConnection::getDbConnection()->executeQuery("drop table ".$this->table);
DbConnection::getDbConnection()->executeQuery("delete from types where id=".$this->id);
DbConnection::getDbConnection()->executeQuery("delete from types_fields where id=".$this->id);
// удалить все поля - ссылки на материалы этого типа
$r = DbConnection::getDbConnection()->fetchAll('SELECT A.field_id, A.name, B.alias FROM types_fields A, types B WHERE A.type=? and A.len=? and A.id=B.id', [FIELD_MATSET, $this->id]);
foreach ($r as $f) {
DbConnection::getDbConnection()->executeQuery('DROP TABLE '.$f['alias'].'_'.$alias.'_'.$f['name']);
DbConnection::getDbConnection()->executeQuery('DELETE FROM types_fields WHERE field_id='.$f['field_id']);
}
}
|
Удаляет тип материалов
|
entailment
|
public function update($params) {
$params = self::fix_params($params);
$oldalias = $this->getAlias();
$alias = $params['alias'];
if ($alias != $oldalias) { // Переименуем тип
if (!$params['fixed'] && in_array($params['alias'], self::$reserved_aliases)) {
throw new Exception\CMS(Exception\CMS::TYPE_RESERVED);
}
$r = DbConnection::getDbConnection()->fetchAll("select id from types where alias=?",[$alias]);
if (count($r)) throw new Exception\CMS(Exception\CMS::TYPE_EXISTS);
$r = DbConnection::getDbConnection()->fetchAll("select A.alias, B.name from types A, types_fields B, dir_data C where C.typ=".$this->id." and C.id=B.len and B.type=7 and A.id=B.id");
foreach ($r as $f) {
DbConnection::getDbConnection()->executeQuery('ALTER TABLE '.$f['alias'].'_'.$oldalias.'_'.$f['name'].' RENAME '.$f['alias'].'_'.$alias.'_'.$f['name']);
}
$r = DbConnection::getDbConnection()->fetchAll("select A.alias, B.name from types A, types_fields B, dir_data C where C.typ=B.len and C.id=A.id and B.type=7 and B.id=".$this->id);
foreach ($r as $f) {
DbConnection::getDbConnection()->executeQuery('ALTER TABLE '.$oldalias.'_'.$f['alias'].'_'.$f['name'].' RENAME '.$alias.'_'.$f['alias'].'_'.$f['name']);
}
$r = DbConnection::getDbConnection()->fetchAll("select A.alias, B.name from types A, types_fields B where B.type=8 and A.id=B.id and B.len=".$this->id);
foreach ($r as $f) {
DbConnection::getDbConnection()->executeQuery('ALTER TABLE '.$f['alias'].'_'.$oldalias.'_'.$f['name'].' RENAME '.$f['alias'].'_'.$alias.'_'.$f['name']);
}
$r = DbConnection::getDbConnection()->fetchAll("select A.alias, B.name from types A, types_fields B where B.type=8 and B.id=".$this->id." and B.len=A.id");
foreach ($r as $f) {
DbConnection::getDbConnection()->executeQuery('ALTER TABLE '.$oldalias.'_'.$f['alias'].'_'.$f['name'].' RENAME '.$alias.'_'.$f['alias'].'_'.$f['name']);
}
DbConnection::getDbConnection()->executeQuery("ALTER TABLE $oldalias RENAME $alias");
DbConnection::getDbConnection()->update('types', array('alias'=>$alias), array('id'=>$this->id));
$this->_table = $alias;
} // if
$sql = array();
if (isset($params['fixed'])) {
$sql[] = 'fixed='.(int)$params['fixed'];
$this->_fixed = (int)$params['fixed'];
}
if (isset($params['describ'])) {
$sql[] = 'describ='.DbConnection::getDbConnection()->quote($params['describ']);
$this->_description = $params['describ'];
}
if (count($sql)) DbConnection::getDbConnection()->executeQuery('update types set '.implode(',',$sql).' where id='.$this->id);
return $this;
}
|
Изменяет тип материалов
@param array $params параметры типа материалов:<br>
alias - alias типа, он же название создаваемой таблицы БД под этот тип материалов<br>
fixed - системный тип (невозможно удалить из админки)<br>
@return ObjectDefinition
|
entailment
|
public function addField($params)
{
$params = self::fix_field_params($params);
if ($params['type'] > 0) {
$r = DbConnection::getDbConnection()->fetchColumn('SELECT COUNT(*) FROM types_fields WHERE id=? and name=?',[$this->id,$params['name']],0);
if ( $r>0 ) throw new Exception\CMS(Exception\CMS::FIELD_EXISTS);
$alias = $this->table;
if ( $params['type'] != FIELD_LINKSET && $params['type'] != FIELD_LINKSET2 && $params['type'] != FIELD_MATSET )
{
$params['len'] = stripslashes($params['len']);
$def = str_replace('%',$params['len'],$this->field_def[$params['type']]);
$sql = "ALTER TABLE $alias ADD `".$params['name']."` $def";
$params['len'] = (integer) $params['len'];
DbConnection::getDbConnection()->executeQuery($sql);
}
else
{
self::create_link_table($alias, $params['name'], $params['type'], $params['len'], $this->id, $params['pseudo_type']);
}
}
$tag = DbConnection::getDbConnection()->fetchColumn("select max(tag) from types_fields where id=?",[$this->id],0) + 10;
DbConnection::getDbConnection()->executeQuery(
"INSERT INTO types_fields (tag,name,type,pseudo_type,len,describ,shw,required,fixed,id,editor,editor_user, default_value, page) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
[$tag,$params['name'],$params['type'],$params['pseudo_type'],$params['len'],$params['describ'],$params['shw'],$params['required'],$params['fixed'],$this->id,(int)$params['editor'],$params['editor_user'],$params['default_value'],$params['page']]
);
return DbConnection::getDbConnection()->lastInsertId();
}
|
Добавляет новое поле в тип материалов
@internal
@param array $params параметры поля
|
entailment
|
public function updateField($params)
{
$params = self::fix_field_params($params);
$alias = $this->table;
$f = DbConnection::getDbConnection()->fetchArray('SELECT type,len,name FROM types_fields WHERE field_id='.$params['field_id']);
if (!$f) throw new Exception\CMS(Exception\CMS::EDIT_FIELD);
$type_old = $f[0];
$len_old = $f[1];
$name_old = $f[2];
if (isset($params['type']) && $params['type']) {
if ($type_old != $params['type']) {
// изменился тип поля
if ($params['type'] != FIELD_LINKSET && $params['type'] != FIELD_LINKSET2 && $params['type'] != FIELD_MATSET) {
$params['len'] = stripslashes($params['len']);
$def = str_replace('%',$params['len'],$this->field_def[$params['type']]);
$params['len'] = (integer) $params['len'];
if ($type_old == FIELD_LINKSET || $type_old == FIELD_LINKSET2 || $type_old == FIELD_MATSET) {
if ($params['type'] >= 0)
$action = 'ADD';
else $action = false;
self::drop_link_table($alias, $name_old, $type_old, $len_old, $this->id, $params['pseudo_type']);
}
else {
if ($type_old >= 0) {
if ($params['type'] >= 0)
{
$action = "CHANGE `".$name_old."`";
}
else
{
DbConnection::getDbConnection()->executeQuery("alter table `$alias` drop `".$name_old."`");
$action = false;
}
} else {
$action = 'ADD';
}
}
if ($action)
DbConnection::getDbConnection()->executeQuery("alter table `$alias` $action `".$params['name']."` $def");
} else {
if ($type_old >= 0) {
if ($type_old != FIELD_LINKSET && $type_old != FIELD_LINKSET2 && $type_old != FIELD_MATSET ) {
DbConnection::getDbConnection()->executeQuery("alter table `$alias` drop `".$name_old."`");
}
else {
self::drop_link_table($alias, $name_old, $type_old, $len_old, $this->id, $params['pseudo_type']);
}
}
self::create_link_table($alias, $params['name'], $params['type'], $params['len'], $this->id, $params['pseudo_type']);
}
}
elseif ($type_old >= 0 && ($params['name'] != $name_old || $params['len'] != $len_old)) {
if ($params['type']!=FIELD_LINKSET && $params['type']!=FIELD_LINKSET2 && $params['type']!=FIELD_MATSET) {
$params['len'] = stripslashes($params['len']);
$def = str_replace('%',$params['len'],$this->field_def[$params['type']]);
$sql = "alter table `$alias` change `".trim($f[2])."` `".$params['name']."` $def";
$params['len'] = (integer) $params['len'];
}
else {
$tbl = self::get_table($params['type'], $params['len'], $this->id,$params['pseudo_type']);
$tbl1 = self::get_table($f[0],$f[1], $this->id,$params['pseudo_type']);
$sql = "alter table ".$alias."_".$tbl1."_".$f[2]." rename ".$alias."_".$tbl."_".$params['name'];
}
DbConnection::getDbConnection()->executeQuery($sql);
}
$sql = "UPDATE types_fields
SET name='".$params['name']."',
type=".$params['type'].",
pseudo_type=".$params['pseudo_type'].",
len=".$params['len'].",
describ='".$params['describ']."',
shw=".$params['shw'].",
required=".$params['required'].",
default_value='".$params['default_value']."',
editor=".$params['editor'].",
editor_user='".$params['editor_user']."',
page='".$params['page']."',
tag='".$params['tag']."'
WHERE field_id=".$params['field_id'];
}
else
{
$sql = "UPDATE types_fields
SET
describ='".$params['describ']."',
default_value='".$params['default_value']."',
page='".$params['page']."'
WHERE field_id=".$params['field_id'];
}
DbConnection::getDbConnection()->executeQuery($sql);
}
|
Изменяет поле в типе материалов
@internal
@param array $params параметры поля
|
entailment
|
public function getMaterials()
{
if ($this->table == 'users') return new Iterator\User();
if ($this->table == 'dir_data') return new Iterator\Catalog\Catalog();
return new Iterator\Material($this);
}
|
Возвращает материалы данного типа
@return Iterator\Material
|
entailment
|
public function setFields($fields)
{
if (!isset($fields['alias']) && isset($fields['tablename'])) {
$fields['alias'] = $fields['tablename'];
unset($fields['tablename']);
}
if (!isset($fields['materialsType']) && isset($fields['typ'])) {
$fields['materialsType'] = $fields['typ'];
unset($fields['typ']);
}
if ($fields['type']&Catalog::LINKED) {
try {
$fields['prototype'] = Catalog::getById($fields['materialsType']);
$fields['materialsType'] = $fields['prototype']->materialsType;
} catch (\Exception $e) {
$fields['prototype'] = Catalog::getRoot();
}
} else {
$fields['prototype'] = $this;
}
parent::setFields($fields);
$this->_catalogType = $fields['type'];
$this->_inheritFields = isset($fields['inheritFields'])?$fields['inheritFields']:false;
}
|
Устанавливает поля раздела
@internal
@param array $fields поля объекта
@return void
|
entailment
|
public function getPath()
{
if (!$this->_path) {
$this->_path = new Iterator\Catalog\Path( $this );
}
return $this->_path;
}
|
Возвращает путь от корня до раздела
@api
@return Iterator\Catalog\Path
|
entailment
|
public function getPreviewUrl()
{
$s = $this->getParentServer();
if (!$s) return false;
return $s->getFullUrl().PREVIEW_PREFIX.$this->getUrl();
}
|
Возвращает URL предварительного просмотра материалов раздела
@return string
|
entailment
|
private function fillPath()
{
$this->_url = '';
$this->_fullUrl = '';
$this->_treePath = '';
foreach ($this->getPath() as $item) {
$this->_treePath .= '/item-'.$item->id;
if ($item->isRoot()) continue;
$this->_fullUrl .= '/'.$item->alias;
if ($item->isServer()) continue;
$this->_url .= '/'.$item->alias;
}
$this->_url = $this->_url.'/';
$this->_fullUrl = $this->_fullUrl.'/';
$this->_treePath = '/root'.$this->_treePath;
if ($this->_url == '') $this->_url = '/';
//die('***');
}
|
Вычисляет путь до раздела
@internal
@see getUrl(), getFullUrl(), getTreePath()
@return void
|
entailment
|
public function getUrl()
{
if ($this->isLink()) {
if ($this->getParentServer()->id != $this->prototype->getParentServer()->id) {
return $this->prototype->getFullUrl();
}
else {
return $this->prototype->getUrl();
}
}
else {
if ($this->_url === FALSE) $this->fillPath();
return $this->_url;
}
}
|
Возвращает абсолютный URL раздела
@api
@return string
|
entailment
|
public function getFullUrl($prefix = TRUE)
{
if ($this->_fullUrl === FALSE) $this->fillPath();
if ($prefix) {
if (
(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
(!empty($_SERVER['HTTP_HTTPS']) && $_SERVER['HTTP_HTTPS'] !== 'off') ||
(!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)
)
$schema = 'https:/';
else $schema = 'http:/';
return $schema.$this->_fullUrl;
}
return $this->_fullUrl;
}
|
Возвращает полный URL раздела (http://сервер/раздел1/.../разделN/)
@api
@param boolean $prefix добавлять http:// вначале
@return string
|
entailment
|
public function getChildren()
{
if (!$this->_children) {
$this->_children = new Iterator\Catalog\Children( $this );
}
return $this->_children;
}
|
Возвращает дочерние разделы
@api
@return Iterator\Catalog
|
entailment
|
public function getSubs()
{
$r = self::getDbConnection()->query('
SELECT A.*, B.level
FROM dir_data A, dir_structure B, dir_structure C
WHERE A.id=B.data_id and C.data_id='.$this->id.' and B.lft BETWEEN C.lft and C.rght');
$result = [];
while ($f = $r->fetch()) {
$c = Catalog::fetch($f);
$result[] = $c->prototype->id;
}
return $result;
}
|
Возвращает массив из идентификаторов раздела и дочерних разделов
@api
@return array
|
entailment
|
public function getParentServer()
{
if ($this->_parentServer) return $this->_parentServer;
$fields = self::getDbConnection()->fetchAssoc(
" SELECT C.*
FROM dir_structure B, dir_structure A, dir_data C
WHERE A.data_id=? and B.lft<=A.lft and B.rght>=A.lft and
B.data_id=C.id and C.is_server<>0",
array( (int)$this->id )
);
if ($fields) {
$this->_parentServer = Server::fetch($fields);
return $this->_parentServer;
}
return FALSE;
}
|
Возвращает родительский сервер
@api
@return Server
|
entailment
|
public function getParent()
{
if ($this->isRoot()) throw new Exception\CMS('No parent for root Catalog');
if (!$this->_parent) {
$fields = self::getDbConnection()->fetchAssoc(
" SELECT A.*
FROM dir_data A, dir_structure B, dir_structure C
WHERE C.data_id=? and B.data_id=A.id and B.lft<C.lft and B.rght>C.rght and B.level=C.level-1",
array( (int)$this->id )
);
if ($fields) {
$this->_parent = Catalog::fetch($fields);
} else {
$this->_parent = Catalog::getRoot();
}
}
return $this->_parent;
}
|
Возвращает родительский раздел
@api
@return Catalog
|
entailment
|
public function getMaterialsObjectDefinition()
{
if (!$this->materialsType) return null;
if (!$this->_materialsObjectDefinition)
$this->_materialsObjectDefinition = new ObjectDefinition($this->materialsType);
return $this->_materialsObjectDefinition;
}
|
Возвращает таблицу БД, в которой хранятся материалы раздела
@return string
|
entailment
|
public function findChildByAlias($alias)
{
$id = self::getDbConnection()->fetchColumn("select A.id from dir_data A, dir_structure B, dir_structure C where C.data_id=? and B.data_id=A.id and B.lft BETWEEN C.lft and C.rght and A.tablename=?", array($this->id, $alias));
if ($id) {
return Catalog::getById($id);
} else return FALSE;
}
|
Ищет среди дочерних разделов раздел с заданным алиасом
@api
@param string @alias алиас раздела
@return Catalog|FALSE
|
entailment
|
public function getChildByAlias($alias)
{
$f = self::getDbConnection()->fetchAssoc("select A.* from dir_data A, dir_structure B, dir_structure C where C.data_id=? and B.data_id=A.id and B.level=C.level+1 and B.lft BETWEEN C.lft and C.rght and A.tablename=?", array($this->id, $alias));
if (!$f) throw new Exception\CMS(Exception\CMS::CAT_NOT_FOUND);
$f['parent'] = $this;
$cat = Catalog::fetch($f);
return $cat;
}
|
Возвращает дочерний раздел с заданным алиасом
@api
@param string $alias алиас раздела
@return Catalog
|
entailment
|
public function getChildByPath($path)
{
if (!is_array($path)) {
$path = trim($path, " /");
$pieces = explode("/", $path);
} else {
$pieces = $path;
}
if (!sizeof($pieces)) return $this;
if ($alias = array_shift($pieces)) {
$c = $this->getChildByAlias($alias);
if (sizeof($pieces)) {
return $c->getChildByPath($pieces);
} else {
return $c;
}
}
return $this;
}
|
Возвращает дочерний раздел по заданному пути
@api
@param string|array $path путь, строка 'alias1/alias2/.../aliasN' или массив из алиасов
@return Catalog
@throws Exception
|
entailment
|
public function getLastMaterial($fields = null, $subs = false)
{
$m = $this->getMaterials()->orderBy('main.dat', 'DESC')->setItemCountPerPage(1)->subfolders($subs);
if ($fields) $m->select($fields);
if (!count($m)) return false;
return $m->current();
}
|
Возвращает последний опубликованный материал раздела.
@api
@param string $fields список простых полей материала, которые выбирать из БД в конструктор материала
@return Material
|
entailment
|
public function getMaterialByAlias($alias, $fields = null, $unpublished = false)
{
$m = $this->getMaterials()->where('alias=:alias')->setParameter('alias', $alias)->unpublished($unpublished);
if ($fields) $m->select($fields);
if (!count($m)) throw new Exception\CMS(Exception\CMS::MATERIAL_NOT_FOUND);
return $m->current();
}
|
Ищет материал c заданным алиасом
@api
@param string $alias алиас материала
@param string $fields список простых полей материала, которые выбирать из БД в конструктор материала
@param boolean $unpublished искать также среди неопубликованных материалов
@return Material
@throws Exception\CMS
|
entailment
|
public function getDefaultTemplate() {
if ($this->_defaultTemplate) return $this->_defaultTemplate;
if ($this->template) {
$path_parts = pathinfo($this->template);
if ($path_parts['extension'] == 'php') {
$app = Application::getInstance();
if (file_exists( $app->getTemplatePath($this->template))) {
$this->_defaultTemplate = $this->template;
}
else {
$this->_defaultTemplate = $this->parent->getDefaultTemplate();
}
}
else {
$this->_defaultTemplate = $this->template;
}
}
else {
$this->_defaultTemplate = $this->parent->getDefaultTemplate();
}
return $this->_defaultTemplate;
}
|
Возвращает php шаблон, исполняемый "по умолчанию" для раздела
@api
@return string
|
entailment
|
public function createChild($fields)
{
if (!isset($fields['alias'])) throw new Exception\Form(Exception\CMS::INVALID_PARAMS, 'alias');
if (!isset($fields['name'])) throw new Exception\Form(Exception\CMS::INVALID_PARAMS, 'name');
if (!isset($fields['typ'])) throw new Exception\Form(Exception\CMS::INVALID_PARAMS, 'typ'); // тип материалов
if (!isset($fields['server'])) $fields['server'] = 0;
try {
$c = $this->getChildByAlias($fields['alias']);
} catch (\Exception $e) {
$c = false;
}
if ($c) throw new Exception\Form(Exception\CMS::CAT_EXISTS, 'alias',$fields['alias']);
if ($this->id == 0 && file_exists(DOCROOT.$fields['alias']))
throw new Exception\Form(Exception\CMS::CAT_PHYSICAL_EXISTS, 'alias', $fields['alias']);
$type = 0;
if ($fields['link']) {
$type = $type | Catalog::LINKED;
if (!$fields['name'] || !$fields['alias']) {
$c = Catalog::getById((int)$fields['typ']);
if (!$fields['name']) $fields['name'] = $c->name;
if (!$fields['alias']) $fields['alias'] = $c->alias;
}
} else {
$type = $type | Catalog::INHERIT;
}
if ($fields['autoalias']) {
$type = $type | Catalog::AUTOALIAS | $fields['autoalias'];
}
if (isset($fields['autoalias'])) unset($fields['autoalias']);
$conn = self::getDbConnection();
$tag = $conn->fetchColumn("SELECT MAX(A.tag)+1
FROM dir_data A, dir_structure B, dir_structure C
WHERE A.id=B.data_id and C.data_id=? and B.lft BETWEEN C.lft and C.rght and B.level=C.level+1", array($this->id));
if (!$tag) $tag = 1;
$sql="INSERT INTO dir_data
SET tag=$tag,
name=".$conn->quote($fields['name']).",
tablename=".$conn->quote($fields['alias']).",
type=$type,
typ=".(int)$fields['typ'].",
dat=NOW(),
is_server=".(int)$fields['server'];
if ((int)$fields['id']) {
$sql .= ',id='.(int)$fields['id'];
unset($fields['id']);
}
$conn->executeQuery($sql);
$id = $conn->lastInsertId();
$p = array();
foreach ($fields as $name => $value)
if ($name!='alias'&&$name!='server'&&$name!='name'&&$name!='typ'&&$name!='link')
$p[] = "$name='".addslashes($value)."'";
if (sizeof($p) && $id)
$conn->executeQuery('UPDATE dir_data SET '.implode(',', $p).' WHERE id='.$id);
$tree = new CDBTree('dir_structure');
$prnt = $conn->fetchColumn('select id from dir_structure where data_id=?', array($this->id));
$tree->insert($prnt, array('data_id'=>$id));
if ($fields['server']) {
$conn->executeQuery("delete from server_aliases where id=$id");
$conn->executeQuery("insert into server_aliases (id,name) values ($id,'".$fields['alias']."')");
$slot = new Cache\Slot\ServerByDomain($fields['alias']);
$slot->remove();
}
$this->updateCache();
return $id;
}
|
Создает дочерний раздел
@api
@param array $fields свойства нового раздела
@return integer ID созданного раздела
@throws Exception\CMS
|
entailment
|
public function delete()
{
// нельзя удалить корневой раздел
if ($this->id == 0) throw new Exception\CMS(Exception\CMS::NO_RIGHTS);
$tree = new CDBTree('dir_structure');
$ids_arr = array($this->id);
if (!$this->isLink()) {
$r = self::getDbConnection()->query('SELECT A.data_id, A.level, C.tablename, D.alias
FROM dir_structure A, dir_structure B, dir_data C, types D
WHERE C.id=A.data_id and B.data_id='.$this->id.' and A.lft BETWEEN B.lft and B.rght and D.id=C.typ');
while ($f = $r->fetch()) {
try {
$r1 = self::getDbConnection()->query('SELECT id FROM '.$f['alias'].' WHERE idcat='.$f['data_id']);
while ($f1 = $r1->fetch(\PDO::FETCH_NUM)) {
$m = Material::getById($f1[0], 0, $f['alias']);
$m->delete();
}
} catch (Exception $e) {}
$ids_arr[] = $f['data_id'];
}
}
$parent = array();
$r = self::getDbConnection()->query('SELECT A.id, B.data_id
FROM dir_structure A, dir_structure B
WHERE A.data_id='.$this->id.' and B.lft<A.lft and B.rght>A.rght and B.level=A.level-1
ORDER BY A.lft DESC');
$res = TRUE;
while ($f = $r->fetch()) {
$parent[] = $f['data_id'];
if (!$tree->deleteAll($f['id'])) $res = FALSE;
} // while
if ($res && sizeof($ids_arr))
{
$ids = implode(',',$ids_arr);
self::getDbConnection()->executeQuery("DELETE FROM dir_data WHERE id IN ($ids)");
self::getDbConnection()->executeQuery("DELETE FROM types_fields_catalogs WHERE catalog_id IN ($ids)");
$r = self::getDbConnection()->query("SELECT name FROM server_aliases WHERE id IN ($ids)");
while ($f = $r->fetch()) {
$slot = new Cache\Slot\ServerByDomain($f['name']);
$slot->remove();
}
self::getDbConnection()->executeQuery("DELETE FROM server_aliases where id IN ($ids)");
self::getDbConnection()->executeQuery("DELETE FROM theme_config where server_id IN ($ids)");
foreach ($ids_arr as $id1) {
self::getDbConnection()->executeQuery("DELETE FROM users_groups_allow_cat where catalog_id=$id1");
$tpl = new Cache\Tag\CatalogID($id1);
$tpl->clean();
}
// удаляем разделы-ссылки, ссылающиеся на раздел
$r = self::getDbConnection()->query('SELECT id FROM dir_data WHERE type&'.Catalog::LINKED.'>0 and typ IN ('.$ids.')');
while ($f = $r->fetch()) {
$c = Catalog::getById($f['id']);
$c->delete();
}
}
$this->updateCache();
}
|
Удаляет раздел
@api
@return void
@throws Exception\CMS
|
entailment
|
public function fixMaterialTags() {
$r = self::getDbConnection()->fetchAll('SELECT count(tag) as cnt from '.$this->materialsTable.' where idcat='.$this->prototype->id.' group by tag having cnt>1');
if (!count($r)) return;
$i = 100;
$r = self::getDbConnection()->query('SELECT id FROM '.$this->materialsTable.' WHERE idcat='.$this->prototype->id.' ORDER BY tag');
while ($f = $r->fetch()) {
self::getDbConnection()->executeQuery('UPDATE '.$this->materialsTable.' SET tag='.$i.' WHERE id='.$f['id']);
$i = $i + 100;
}
}
|
Приводит в порядок порядковые номера материалов раздела: удаляет дубликаты, дыры в нумерации.
@internal
@return void
|
entailment
|
public function allowAccess($permission, $groups)
{
if ($this->isInheritsPermissions()) {
return $this->parent->allowAccess($permission, $groups);
} else {
if (!is_array($groups)) {
if (is_object($groups))
$groups = $groups->groups;
else $groups = array($groups);
}
$r = self::getDbConnection()->fetchColumn('SELECT COUNT(*) FROM users_groups_allow_cat WHERE permission='.(int)$permission.' and catalog_id='.(int)$this->id.' and group_id IN ('.implode(',',$groups).')');
if ($r > 0) return TRUE;
return FALSE;
}
}
|
Проверяет имеет ли пользователь или группа разрешение для данного раздела
@param int $permission код разрешения
@param int|array|User $groups id группы, массив id групп или пользователь
@return bool
@see PERM_CAT_OWN_MAT, PERM_CAT_ALL_MAT, PERM_CAT_ADMIN, PERM_CAT_VIEW, PERM_CAT_MAT_PUB
|
entailment
|
public function copy($dest, $subs = false, $materials = false)
{
$dest_obj = Catalog::getById($dest);
$alias = $this->alias;
$number = '';
$c = 1;
while ($c) {
try {
$c = $dest_obj->getChildByAlias($alias);
} catch (\Exception $e) {
$c = false;
}
if ($c) {
$alias = $this->alias.'_copy'.$number;
$number++;
}
}
$r = self::getDbConnection()->fetchArray("SELECT MAX(A.tag)+1, C.id
FROM dir_structure C LEFT JOIN dir_structure B ON (B.lft BETWEEN C.lft and C.rght and B.level=C.level+1) LEFT JOIN dir_data A ON (A.id=B.data_id)
WHERE C.data_id=$dest
GROUP BY C.id");
if (!$r) throw new Exception\CMS('Dest catalog is not found');
list($tag, $sid) = $r;
if (!$tag) $tag = 1;
$fields = array(
'tag' => $tag,
'tablename' => $alias
);
// Если сервер копируется внутрь другого сервера, то копия должна стать простым разделом
if ($this->isServer() && !$dest_obj->isRoot())
$fields['is_server'] = 0;
$new_id = Util::copyRecord('dir_data', 'id', $this->id, $fields);
if (!$new_id) throw new Exception\CMS('Error copying data record');
$tree = new CDBTree('dir_structure');
$new_sid = $tree->insert($sid, array('data_id'=>$new_id));
if (!$new_sid) {
self::getDbConnection()->executeQuery("DELETE FROM dir_data WHERE id=$new_id");
throw new Exception\CMS('Error while creating new tree entry');
}
$r = self::getDbConnection()->query('SELECT * FROM users_groups_allow_cat WHERE catalog_id='.$this->id);
while ($f = $r->fetch()) {
self::getDbConnection()->executeQuery('INSERT INTO users_groups_allow_cat (catalog_id,group_id,permission) VALUES ('.$new_sid.','.$f['group_id'].','.$f['permission'].')');
}
// Копирование материалов
if ($materials) {
foreach ($this->getMaterials() as $material)
$material->copy($new_id);
}
// Копирование подразделов
if ($subs)
foreach ($this->getChildren() as $child)
$child->copy($new_id, $subs, $materials);
$tpl = new Cache\Tag\CatalogID(0);
$tpl->clean();
return $new_id;
}
|
Копирует раздел
@api
@param int $dest ID раздела, куда копировать
@param bool $subs копировать подразделы
@param bool $materials копировать материалы
@return int ID копии
@throws Exception
|
entailment
|
public function move($dest)
{
$tree = new CDBTree('dir_structure');
$prntid = self::getDbConnection()->fetchColumn('select id from dir_structure where data_id=?', array($dest));
$strid = self::getDbConnection()->fetchColumn('select id from dir_structure where data_id=?', array($this->id));
$tree->moveAll($strid, $prntid);
$this->_url = false;
$this->_fullUrl = false;
$this->_treePath = false;
$this->_path = false;
$this->updateCache();
}
|
Перемещает раздел
@api
@param int $dest ID раздела, куда перемещать
@return void
|
entailment
|
public function updateCache()
{
$tpl = new Cache\Tag\CatalogID($this->id);
$tpl->clean();
$tpl = new Cache\Tag\CatalogID($this->parent->id);
$tpl->clean();
$tpl = new Cache\Tag\CatalogID(0);
$tpl->clean();
}
|
Очистить все кэши связанные с этим разделом
@return void
|
entailment
|
public function updatePermissions($permissions)
{
if ($this->isLink()) return;
self::getDbConnection()->executeQuery('DELETE FROM users_groups_allow_cat WHERE catalog_id='.$this->id);
if (is_array($permissions))
foreach ($permissions as $pid => $groups)
foreach($groups as $gid) if ($gid && $gid != GROUP_ADMIN)
self::getDbConnection()->executeQuery('INSERT INTO users_groups_allow_cat SET permission='.(int)$pid.', group_id='.(int)$gid.', catalog_id='.(int)$this->id);
}
|
Измененить права доступа к разделу
@param array $permissions новые права доступа
@return void
|
entailment
|
private function updateFields($fields)
{
if ($this->isLink()) return;
self::getDbConnection()->executeQuery('DELETE FROM types_fields_catalogs WHERE catalog_id='.$this->id);
if (is_array($fields))
foreach ($fields as $fid => $data) {
if ($data['force_show'] || $data['force_hide'])
self::getDbConnection()->executeQuery('INSERT INTO types_fields_catalogs SET catalog_id='.$this->id.', type_id='.$this->materialsType.', field_id='.$fid.', force_show='.(int)$data['force_show'].', force_hide='.(int)$data['force_hide']);
}
}
|
Измененить видимость полей материалов в данном разделе
@internal
@param array $fields инфа о полях
@return void
|
entailment
|
public function shift($up)
{
$this->parent->fixTags();
$sign = $up?'<':'>';
$order = $up?'desc':'asc';
list($parent, $tag) = self::getDbConnection()->fetchArray("select D.data_id as parentid, A.tag
FROM dir_data A, dir_structure B, dir_structure D
WHERE (A.id=".$this->id.") and B.data_id=A.id and D.lft<B.lft and D.rght>B.rght and D.level=B.level-1");
$r = self::getDbConnection()->query("SELECT A.tag, A.id FROM dir_data A, dir_structure B, dir_structure C
WHERE A.id=B.data_id and C.data_id=$parent and B.lft BETWEEN C.lft and C.rght and B.level=C.level+1 and A.tag $sign $tag and A.id <> '.$this->id.' ORDER BY A.tag $order LIMIT 1");
if ($f = $r->fetch(\PDO::FETCH_NUM)) {
self::getDbConnection()->executeQuery("update dir_data set tag=$f[0] where id=".$this->id);
self::getDbConnection()->executeQuery("update dir_data set tag=$tag where id=$f[1]");
}
$tpl = new Cache\Tag\CatalogID(0);
$tpl->clean();
}
|
Подвинуть раздел вверх или вниз на позицию
@api
@param bool $up двигать вверх, иначе вниз
@return void
|
entailment
|
public function inAppPath()
{
$app = Application::getInstance();
if (!$app->isFrontOffice()) return false;
return $app->getCatalog()->getPath()->has($this);
}
|
Проверяет, является ли раздел частью пути к текущему разделу в FO
@internal
@param Catalog $catalog раздел для проверки
@return bool
|
entailment
|
public function update($props)
{
if (isset($props['permissions'])) {
$this->updatePermissions($props['permissions']);
unset($props['permissions']);
}
if (isset($props['fields'])) {
$this->updateFields($props['fields']);
unset($props['fields']);
}
$this->fields = $props;
$this->save();
}
|
Изменение свойств раздела и сохранение
@api
@param array $props новые свойства
@return void
@throws Exception
|
entailment
|
public function createMaterial()
{
$m = Material::factory( $this->materialsType, $this->materialsTable );
$m->idcat = $this->id;
return $m;
}
|
Создать новый материал в разделе
@api
@return \Cetera\Material
|
entailment
|
public function save()
{
if ($this->isRoot()) return;
if (isset($this->fields['alias']) && $this->fields['alias'] != $this->alias) {
try {
$c = $this->parent->getChildByAlias($this->fields['alias']);
} catch (\Exception $e) {
$c = false;
}
if ($c && $c->id != $this->id) throw new Exception\Form(Exception\CMS::CAT_EXISTS, 'alias', $this->fields['alias']);
if ($this->parent->isRoot() && file_exists(DOCROOT.$this->fields['alias']))
throw new Exception\Form(Exception\CMS::CAT_PHYSICAL_EXISTS, 'alias', $this->fields['alias']);
}
$conn = self::getDbConnection();
$set = '';
if (isset($this->fields['name'])) $set .= ', name='.$conn->quote($this->fields['name']);
if (isset($this->fields['alias'])) $set .= ', tablename='.$conn->quote($this->fields['alias']);
if (isset($this->fields['template'])) $set .= ', template='.$conn->quote($this->fields['template']);
if (isset($this->fields['typ'])) $set .= ', typ='.(int)$this->fields['typ'];
if (isset($this->fields['hidden'])) $set .= ', hidden='.(int)$this->fields['hidden'];
$type = 'type';
if (!$this->isLink()) {
if (isset($this->fields['inheritFields'])) $set .= ', inheritFields='.(int)$this->fields['inheritFields'];
$set .= $this->saveDynamicFields();
$this->saveDynimicLinks();
if (isset($this->fields['autoalias'])) {
if ($this->fields['autoalias'])
$type = '('.$type.')|'.Catalog::AUTOALIAS;
else $type = '('.$type.')&'.~Catalog::AUTOALIAS;
}
if (isset($this->fields['autoalias_type'])) {
if ($this->fields['autoalias_type'] == 3) $type = '(('.$type.')|'.Catalog::AUTOALIAS_ID.')&'.~Catalog::AUTOALIAS_TRANSLIT;
if ($this->fields['autoalias_type'] == 2) $type = '(('.$type.')|'.Catalog::AUTOALIAS_TRANSLIT.')&'.~Catalog::AUTOALIAS_ID;
if ($this->fields['autoalias_type'] == 1) $type = '(('.$type.')&'.~Catalog::AUTOALIAS_TRANSLIT.')&'.~Catalog::AUTOALIAS_ID;
}
if (isset($this->fields['cat_inherit'])) {
if ($this->fields['cat_inherit'])
$type = '('.$type.')|'.Catalog::INHERIT;
else $type = '('.$type.')&'.~Catalog::INHERIT;
}
if (isset($this->fields['typ']) && $this->materialsType != $this->fields['typ']) {
$newtable = $conn->fetchColumn("SELECT alias from types where id=".$this->fields['typ']);
if ($newtable) {
$r = $conn->query("select B.alias,A.name from types_fields A, types B where B.id=A.id and A.type=".FIELD_LINKSET." and A.pseudo_type<>".PSEUDO_FIELD_CATOLOGS." and A.len=".$this->id);
while ($f = $r->fetch(\PDO::FETCH_NUM))
$conn->executeQuery("alter table ".$f[0]."_".$this->materialsTable."_".$f[1]." rename ".$f[0]."_".$newtable."_".$f[1]);
}
}
}
$conn->executeQuery("UPDATE dir_data SET type=$type $set where id=".$this->id);
$this->updateCache();
}
|
Сохранить раздел
@api
@return void
|
entailment
|
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$result = parent::save($data, $id, array(), $specificLifetime);
if ($tags) {
if (!method_exists($this->_handle, 'tag_add')) {
\Zend_Cache::throwException('Method tag_add() is not supported by the PHP memcached extension!');
}
foreach ($tags as $tag) {
$this->_handle->tag_add($tag, $id);
}
return true;
}
return $result;
}
|
Saves a data in memcached.
Supports tags.
@see \Zend_Cache_Backend_Memcached::save()
|
entailment
|
public function clean($mode = \Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if ($mode == \Zend_Cache::CLEANING_MODE_MATCHING_TAG) {
if ($tags) {
if (!method_exists($this->_handle, 'tag_delete')) {
\Zend_Cache::throwException('Method tag_delete() is not supported by the PHP memcached extension!');
}
foreach ($tags as $tag) {
$this->_handle->tag_delete($tag);
}
}
} else {
return parent::clean($mode, $tags);
}
}
|
Cleaning operation with tag support.
@see \Zend_Cache_Backend_Memcached::clean()
|
entailment
|
public static function image($src, $dst, $width = 0, $height = 0, $quality = 75, $dontenlarge = 0, $aspect = 1, $fit = 0, $face = 0)
{
$img = new self($src);
$img->setEnlarge(!$dontenlarge)
->setWidth($width)
->setHeight($height)
->setQuality($quality)
->setAspect($aspect)
->setFit($fit)
->save($dst);
}
|
/*
@deprecated
|
entailment
|
public function has($catalog)
{
if ($catalog instanceof \Cetera\Catalog)
{
$cid = $catalog->id;
}
else
{
$cid = (int)$catalog;
}
foreach($this as $c) if ($c->id == $cid) return true;
return false;
}
|
Проверяет, имеется ли раздел в итераторе
@param Catalog $catalog раздел для проверки
@return bool
|
entailment
|
public function apply()
{
if (!$this->isActive()) return;
foreach ($this->getInfo() as $f)
{
switch($f['filter_type'])
{
case self::TYPE_NUMERIC:
case self::TYPE_NUMERIC_SLIDER:
if ($this->submittedValue($f['name'].'_min') !== null)
{
$this->iterator->where( $this->generateField($f['field']).' >= '.(float)$this->submittedValue($f['name'].'_min') );
}
if ($this->submittedValue($f['name'].'_max') !== null && $this->submittedValue($f['name'].'_max'))
{
$this->iterator->where( $this->generateField($f['field']).' <= '.(float)$this->submittedValue($f['name'].'_max') );
}
break;
case self::TYPE_RADIO:
case self::TYPE_DROPDOWN:
if ($this->submittedValue($f['name']) !== null) {
$this->iterator->where( $this->generateField($f['field']).' = :'.$f['name'] )
->setParameter($f['name'], $this->submittedValue($f['name']));
}
break;
case self::TYPE_CHECKBOX:
if ($this->submittedValue($f['name']) !== null) {
if (is_array($this->submittedValue($f['name']))) {
$a = array();
foreach ($this->submittedValue($f['name']) as $value => $dummy) {
$a[] = '"'.$value.'"';
}
$this->iterator->where( $this->generateField($f['field']).' IN ('.implode(',',$a).')' );
}
else {
if ($this->submittedValue($f['name'])) {
$this->iterator->where( $this->generateField($f['field']).' > 0' );
}
}
}
break;
case self::TYPE_DROPDOWN_MULTIPLE:
if ($this->submittedValue($f['name']) !== null) {
if (is_array($this->submittedValue($f['name']))) {
$this->iterator->where( $this->generateField($f['field']).' IN ("'.implode('","',$this->submittedValue($f['name'])).'")' );
}
}
break;
case self::TYPE_DATE_INTERVAL:
if ($f['value_min']) {
$this->iterator->where( $this->generateField($f['field']).' >= STR_TO_DATE(:'.$f['name'].'_min,"%Y-%m-%d")' )
->setParameter($f['name'].'_min', $f['value_min']);
}
if ($f['value_max']) {
$this->iterator->where( $this->generateField($f['field']).' <= DATE_ADD(STR_TO_DATE(:'.$f['name'].'_max,"%Y-%m-%d"), INTERVAL 1 DAY)' )
->setParameter($f['name'].'_max', $f['value_max']);
}
break;
case self::TYPE_DATE:
if ($f['value']) {
$this->iterator->where( 'DATE_FORMAT('.$this->generateField($f['field']).',"%Y-%m-%d") = :'.$f['name'] )
->setParameter($f['name'], $f['value']);
}
break;
case self::TYPE_TEXT:
if ($f['value']) {
$this->iterator->where( $this->generateField($f['field']).' LIKE :'.$f['name'] )
->setParameter($f['name'], '%'.$f['value'].'%');
}
break;
}
}
$this->iterator->groupBy('main.id');
}
|
/*
применить фильтр к итератору
|
entailment
|
public static function configSet($key, $value)
{
self::getDbConnection()->executeQuery('REPLACE INTO config SET `class` = ?, `key` = ?, `value` = ?', array( get_called_class(), $key, serialize($value) ));
}
|
Сохраняет пару ключ/значение в БД
@api
@param string $key ключ
@param miced $value значение
@return void
|
entailment
|
public static function configGet($key)
{
$data = self::getDbConnection()->fetchAssoc('SELECT value FROM config WHERE `class` = ? and `key` = ?', array( get_called_class(), $key ));
if (!$data) return null;
return unserialize($data['value']);
}
|
Возвращает значение связанное с ключем из БД
@api
@param string $key ключ
@return mixed
|
entailment
|
public static function configGetAll()
{
$data = self::getDbConnection()->fetchAll('SELECT * FROM config WHERE `class` = ?', array( get_called_class() ));
$res = array();
foreach ($data as $id => $v)
{
$res[$v['key']] = unserialize($v['value']);
}
return $res;
}
|
Возвращает все ключи/значения из БД
@api
@return mixed
|
entailment
|
public function save($data)
{
$tags = array();
foreach ($this->_tags as $tag) {
$tags[] = $tag->getNativeId();
}
$raw = serialize($data);
$this->_getBackend()->save($raw, $this->_id, $tags, $this->_lifetime);
}
|
Saves a data for this slot.
@param mixed $data Data to be saved.
@return void
|
entailment
|
public function addTag(Dklab_Cache_Frontend_Tag $tag)
{
if ($tag->getBackend() !== $this->_getBackend()) {
\Zend_Cache::throwException("Backends for tag " . get_class($tag) . " and slot " . get_class($this) . " must be same");
}
$this->_tags[] = $tag;
}
|
Associates a tag with current slot.
@param Dklab_Cache_Tag $tag Tag object to associate.
@return void
|
entailment
|
public static function trigger($event, $params = [])
{
if ( is_array(self::$listeners[$event]) ) {
foreach (self::$listeners[$event] as $callable) {
$callable($event, $params);
}
}
if ( is_array(self::$listeners['*']) ) {
foreach (self::$listeners['*'] as $callable) {
$callable($event, $params);
}
}
}
|
Сообщить о наступлении события
|
entailment
|
public static function enum()
{
$result = array();
$r = self::getDbConnection()->executeQuery('SELECT * FROM dir_data A WHERE is_server<>0 ORDER BY tag');
while($fields = $r->fetch()) {
$result[] = self::fetch($fields);
}
return $result;
}
|
Возвращает все сервера.
@return Array
|
entailment
|
public static function getByDomain($domain)
{
$slot = new Cache\Slot\ServerByDomain($domain);
if (false === ($server = $slot->load())) {
$fields = self::getDbConnection()->fetchAssoc( 'SELECT B.* FROM server_aliases A LEFT JOIN dir_data B USING (ID) WHERE B.hidden<>1 and B.is_server<>0 and A.name = ?', array( $domain ) );
if ($fields) {
$server = self::fetch($fields);
} else {
$server = self::getDefault();
if (!$server) return FALSE;
}
$slot->addTag(new Cache\Tag\CatalogID($server->id));
$slot->save($server);
}
return $server;
}
|
Возвращает сервер по его доменному имени
@param string $domain доменное имя
@return Server
|
entailment
|
public static function getDefault()
{
$fields = self::getDbConnection()->fetchAssoc( "SELECT * FROM dir_data where hidden<>1 and is_server<>0 and type&".Server::DEFAULT_SERVER."=1" );
if ($fields) {
return self::fetch($fields);
} else {
return false;
}
}
|
Возвращает основной сервер
@return Server
|
entailment
|
public function getDefaultTemplate() {
if ($this->_defaultTemplate) return $this->_defaultTemplate;
if ($this->template)
$this->_defaultTemplate = $this->template;
else $this->_defaultTemplate = DEFAULT_TEMPLATE;
return $this->_defaultTemplate;
}
|
Возвращает php шаблон, исполняемый "по умолчанию" для сервера
@return string
|
entailment
|
public function update($props)
{
if (isset($props['server_aliases']) || isset($props['alias'])) {
self::getDbConnection()->executeQuery("DELETE FROM server_aliases WHERE id=".$this->id);
if (isset($props['server_aliases'])){
$alias = json_decode($props['server_aliases']);
unset($props['server_aliases']);
} else {
$alias = array();
}
if (isset($props['alias'])) $alias[] = $props['alias'];
foreach($alias as $al) if ($al) {
self::getDbConnection()->insert('server_aliases', array(
'id' => $this->id,
'name' => $al
));
$slot = new Cache\Slot\ServerByDomain($al);
$slot->remove();
}
}
self::getDbConnection()->update('dir_data', array('templateDir' => $props['templateDir']), array('id'=>$this->id));
parent::update($props);
}
|
Изменение свойств сервера
@param array $props новые свойства
@return void
@throws Exception
|
entailment
|
public function getTheme()
{
if ($this->_theme === null)
{
$tname = str_replace( THEME_DIR.'/', '', $this->templateDir );
if ($tname) {
$theme = Theme::find($tname);
if ($theme) $theme->loadConfig($this);
$this->_theme = $theme;
} else {
$this->_theme = false;
}
}
return $this->_theme;
}
|
Возвращает тему, активированную для сервера
@return string
|
entailment
|
public function setTheme(Theme $theme = null)
{
$theme_path = null;
if ($theme) $theme_path = THEME_DIR.'/'.$theme->name;
self::getDbConnection()->update('dir_data',array('templateDir'=>$theme_path),array('id'=>$this->id));
$this->updateCache();
return $this;
}
|
Устанавливает тему, активированную для сервера
@return string
|
entailment
|
public function getCountAll()
{
if ($this->sync && $this->countAll !== null) return $this->countAll;
$query = clone $this->query;
$query->resetQueryPart('orderBy')
->setMaxResults(null)
->setFirstResult(null)
->select('COUNT(1)');
$this->fixWhere($query);
$stmt = $query->execute();
if ($stmt->rowCount() > 1) {
$this->countAll = $stmt->rowCount();
}
else {
$this->countAll = $stmt->fetchColumn();
}
return $this->countAll;
}
|
Полное количество объектов
@return int
|
entailment
|
public static function getInstance()
{
if (null === self::$_instance) {
$app = \Cetera\Application::getInstance();
if ($app->getVar('cache_memcache')!='off' && $app->getVar('cache_memcache')!='disable' && $app->getVar('cache_memcache')!='0' && self::isMemcacheAvailable()) {
$o = [];
if ( $app->getVar('memcache_server') ) {
$o['servers'] = $app->getVar('memcache_server');
}
$backend = new \Dklab_Cache_Backend_TagEmuWrapper(new \Zend_Cache_Backend_Memcached($o));
}
elseif ($app->getVar('cache_memcached')!='off'&& $app->getVar('cache_memcached')!='disable' && $app->getVar('cache_memcached')!='0' && self::isMemcachedAvailable()) {
$o = [];
if ( $app->getVar('memcached_server') ) {
$o['servers'] = $app->getVar('memcached_server');
}
$backend = new \Dklab_Cache_Backend_TagEmuWrapper(new \Zend_Cache_Backend_Libmemcached($o));
}
elseif ($app->getVar('cache_file') && self::isFilecacheAvailable()) {
$backend = new \Zend_Cache_Backend_File(array('cache_dir'=>FILECACHE_DIR, 'hashed_directory_level'=>1));
}
else {
$backend = new BackendNull();
}
self::$_instance = new Profiler($backend);
}
return self::$_instance;
}
|
В зависимости от настроек системы используется либо Memcache, либо файловый кэш, либо вообще ничего
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.