sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function add($thread) { if (Podium::getInstance()->user->isGuest) { return false; } $sub = new Subscription(); $sub->thread_id = $thread; $sub->user_id = User::loggedId(); $sub->post_seen = self::POST_SEEN; return $sub->save(); }
Adds subscription for thread. @param int $thread thread ID @return bool @since 0.2
entailment
public function run() { try { $next = 0; $newSort = -1; foreach ($this->query->each() as $id => $model) { if ($next == $this->order) { $newSort = $next++; } Podium::getInstance()->db->createCommand()->update( call_user_func([$this->target, 'tableName']), ['sort' => $next], ['id' => $id] )->execute(); $next++; } if ($newSort == -1) { $newSort = $next; } $this->target->sort = $newSort; if (!$this->target->save()) { throw new Exception('Order saving error'); } Log::info('Orded updated', $this->target->id, __METHOD__); return true; } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Runs sorter. @return bool
entailment
public function registerClientScript() { $view = $this->view; CodeMirrorAsset::register($view); $js = 'var CodeMirrorLabels = { bold: "' . Yii::t('podium/view', 'Bold') . '", italic: "' . Yii::t('podium/view', 'Italic') . '", header: "' . Yii::t('podium/view', 'Header') . '", inlinecode: "' . Yii::t('podium/view', 'Inline code') . '", blockcode: "' . Yii::t('podium/view', 'Block code') . '", quote: "' . Yii::t('podium/view', 'Quote') . '", bulletedlist: "' . Yii::t('podium/view', 'Bulleted list') . '", orderedlist: "' . Yii::t('podium/view', 'Ordered list') . '", link: "' . Yii::t('podium/view', 'Link') . '", image: "' . Yii::t('podium/view', 'Image') . '", help: "' . Yii::t('podium/view', 'Help') . '", };var CodeMirrorSet = "' . $this->type . '";'; $view->registerJs($js, View::POS_BEGIN); }
Registers widget assets. Note that CodeMirror works without jQuery.
entailment
public function danger($message, $removeAfterAccess = true) { Yii::$app->session->addFlash('danger', $message, $removeAfterAccess); }
Adds flash message of 'danger' type. @param string $message the flash message to be translated. @param bool $removeAfterAccess message removal after access only.
entailment
public function info($message, $removeAfterAccess = true) { Yii::$app->session->addFlash('info', $message, $removeAfterAccess); }
Adds flash message of 'info' type. @param string $message the flash message to be translated. @param bool $removeAfterAccess message removal after access only.
entailment
public function success($message, $removeAfterAccess = true) { Yii::$app->session->addFlash('success', $message, $removeAfterAccess); }
Adds flash message of 'success' type. @param string $message the flash message to be translated. @param bool $removeAfterAccess message removal after access only.
entailment
public function warning($message, $removeAfterAccess = true) { Yii::$app->session->addFlash('warning', $message, $removeAfterAccess); }
Adds flash message of 'warning' type. @param string $message the flash message to be translated. @param bool $removeAfterAccess message removal after access only.
entailment
public function init() { parent::init(); $this->denyCallback = function () { Yii::$app->session->addFlash($this->type, $this->message, true); return Yii::$app->response->redirect([Podium::getInstance()->prepareRoute('account/login')]); }; }
Sets deny callback.
entailment
public function init() { parent::init(); $this->matchCallback = function () { return !Podium::getInstance()->getInstalled(); }; $this->denyCallback = function () { return Yii::$app->response->redirect([Podium::getInstance()->prepareRoute('install/run')]); }; }
Sets match and deny callbacks.
entailment
protected function _redirect(ServerRequest $request, Response $response) { $message = $request->getSession()->consume($this->_config['flashKey']); $url = $response->getHeader('Location')[0]; $status = $response->getStatusCode(); $json = JsonEncoder::encode([ // Error and content are here to make the output the same as previously // with the component, so existing unit tests don't break. 'error' => null, 'content' => null, '_message' => $message, '_redirect' => compact('url', 'status'), ], $this->_config['jsonOptions']); $response = $response->withStatus(200) ->withoutHeader('Location') ->withHeader('Content-Type', 'application/json; charset=' . $response->getCharset()) ->withStringBody($json); return $response; }
Generate a JSON response encoding the redirect @param \Cake\Http\ServerRequest $request The request. @param \Cake\Http\Response $response The response. @return \Cake\Http\Response A response. @throws \RuntimeException
entailment
protected function _isSerializeTrue($controller) { if (!empty($controller->viewVars['_serialize']) && $controller->viewVars['_serialize'] === true) { return true; } return false; }
Checks to see if the Controller->viewVar labeled _serialize is set to boolean true. @param \Cake\Controller\Controller $controller @return bool
entailment
protected function _isActionEnabled(ServerRequest $request) { $actions = $this->getConfig('actions'); if (!$actions) { return true; } return in_array($request->getParam('action'), $actions, true); }
Checks if we are using action whitelisting and if so checks if this action is whitelisted. @param \Cake\Http\ServerRequest $request The request. @return bool
entailment
public function beforeRender(Event $event) { /** @var \Cake\Controller\Controller $controller */ $controller = $event->getSubject(); $controller->viewBuilder()->setClassName($this->_config['viewClass']); // Set flash messages to the view if ($this->_config['flashKey']) { $message = $controller->getRequest()->getSession()->consume($this->_config['flashKey']); if ($message || !array_key_exists('_message', $controller->viewVars)) { $controller->set('_message', $message); } } // If _serialize is true, *all* viewVars will be serialized; no need to add _message. if ($this->_isSerializeTrue($controller)) { return; } $serializeKeys = ['_message']; if (!empty($controller->viewVars['_serialize'])) { $serializeKeys = array_merge((array)$controller->viewVars['_serialize'], $serializeKeys); } $controller->set('_serialize', $serializeKeys); }
Called before the Controller::beforeRender(), and before the view class is loaded, and before Controller::render() @param \Cake\Event\Event $event @return void
entailment
public function render($view = null, $layout = null) { $dataToSerialize = [ 'error' => null, 'content' => null, ]; if (!empty($this->viewVars['error'])) { $view = false; } if ($view !== false && !isset($this->viewVars['_redirect']) && $this->_getViewFileName($view)) { $dataToSerialize['content'] = parent::render($view, $layout); } $this->viewVars = Hash::merge($dataToSerialize, $this->viewVars); if (isset($this->viewVars['_serialize'])) { $dataToSerialize = $this->_dataToSerialize($this->viewVars['_serialize'], $dataToSerialize); } return $this->_serialize($dataToSerialize); }
Renders an AJAX view. The rendered content will be part of the JSON response object and can be accessed via response.content in JavaScript. If an error has been set, the rendering will be skipped. @param string|null $view The view being rendered. @param string|null $layout The layout being rendered. @return string The rendered view.
entailment
protected function _dataToSerialize($serialize, $additionalData = []) { if ($serialize === true) { $data = array_diff_key( $this->viewVars, array_flip($this->_specialVars) ); return $data; } foreach ((array)$serialize as $alias => $key) { if (is_numeric($alias)) { $alias = $key; } if (array_key_exists($key, $this->viewVars)) { $additionalData[$alias] = $this->viewVars[$key]; } } return $additionalData; }
Returns data to be serialized based on the value of viewVars. @param array|string|bool $serialize The name(s) of the view variable(s) that need(s) to be serialized. If true all available view variables will be used. @param array $additionalData Data items that were defined internally in our own render method. @return mixed The data to serialize.
entailment
public static function encode(array $dataToSerialize, $options = 0) { $result = json_encode($dataToSerialize, $options); $error = null; if (json_last_error() !== JSON_ERROR_NONE) { $error = 'JSON encoding failed: ' . json_last_error_msg(); } if ($result === false || $error) { throw new RuntimeException($error ?: 'JSON encoding failed'); } return $result; }
@param array $dataToSerialize @param int $options @return string @throws \RuntimeException
entailment
public function beforeRedirect(Event $event, $url, Response $response) { if (!$this->respondAsAjax || !$this->_config['resolveRedirect']) { return null; } $url = Router::url($url, true); $status = $response->getStatusCode(); $response = $response->withStatus(200)->withoutHeader('Location'); $this->Controller->setResponse($response); $this->Controller->enableAutoRender(); $this->Controller->set('_redirect', compact('url', 'status')); $event->stopPropagation(); if ($this->_isControllerSerializeTrue()) { return null; } $serializeKeys = ['_redirect']; if (!empty($this->Controller->viewVars['_serialize'])) { $serializeKeys = array_merge($serializeKeys, (array)$this->Controller->viewVars['_serialize']); } $this->Controller->set('_serialize', $serializeKeys); // Further changes will be required here when the change to immutable response objects is completed $response = $this->Controller->render(); return $response; }
Called before Controller::redirect(). Allows you to replace the URL that will be redirected to with a new URL. @param \Cake\Event\Event $event Event @param string|array $url Either the string or URL array that is being redirected to. @param \Cake\Http\Response $response @return \Cake\Http\Response|null
entailment
protected function _isControllerSerializeTrue() { if (!empty($this->Controller->viewVars['_serialize']) && $this->Controller->viewVars['_serialize'] === true) { return true; } return false; }
Checks to see if the Controller->viewVar labeled _serialize is set to boolean true. @return bool
entailment
protected function _isActionEnabled() { $actions = $this->getConfig('actions'); if (!$actions) { return true; } return in_array($this->getController()->getRequest()->getParam('action'), $actions, true); }
Checks if we are using action whitelisting and if so checks if this action is whitelisted. @return bool
entailment
public function import(&$data) { $attributes = $this->getAttributes(); $values = $this->getValues($data); $countInserts = 0; $chunks = array_chunk($values, $this->maxItemsPerInsert); foreach ($chunks as $chunk) {//Execute multiple queries $countInserts += \Yii::$app->db->createCommand() ->batchInsert($this->tableName, $attributes, $chunk)->execute(); } return $countInserts; }
Will multiple import data into table @param array $data CSV data passed by reference to save memory. @return integer number of rows affected
entailment
private function getValues(&$data) { $values = []; foreach ($data as $i => $row) { $skipImport = isset($this->skipImport) ? call_user_func($this->skipImport, $row) : false; if (!$skipImport) { foreach ($this->configs as $config) { $value = call_user_func($config['value'], $row); $values[$i][$config['attribute']] = $value; } } } //Filter unique values by unique attributes $values = $this->filterUniqueValues($values); return $values; }
Will get value list from the config @param array $data CSV data @return array
entailment
private function filterUniqueValues($values) { //Get unique attributes $uniqueAttributes = []; foreach ($this->configs as $config) { if (isset($config['unique']) && $config['unique']) { $uniqueAttributes[] = $config['attribute']; } } if (empty($uniqueAttributes)) { return $values; //Return all values } //Filter values per unique attributes $uniqueValues = []; foreach ($values as $value) { $hash = ""; //generate hash per 1+ unique parameters foreach ($uniqueAttributes as $ua) { $hash .= $value[$ua]; } $uniqueValues[$hash] = $value; } return $uniqueValues; }
Will filter values per unique parameters. Config array can receive 1+ unique parameters. @param array $values
entailment
public function authenticate($username, $token) { if (empty($username) || empty($token)) { throw new \ErrorException('No username or token supplied.'); } $this->username = $username; $this->token = $token; }
Set API credentials @param string $username API username @param string $token API token
entailment
private function makeRequest($method, $path, $headers = array(), $params = '') { if (time() - $this->previousRequestTime < 1) { sleep(1); } $response = call_user_func_array(array($this->http, $method), array($path, $headers, $params)); $this->previousRequestTime = time(); list($status, $headers, $body) = $response; return $this->processResponse($response); }
Method for implementing request retry logic @param string $method HTTP request method @param string $path Path to resource @return array
entailment
private function processResponse($response) { list($status, $headers, $body) = $response; // if empty response just return boolean if ($status == 204) { return true; } $decoded = json_decode($body, true); if ($decoded === null) { throw new RestException('Could not decode response body as JSON.', $status); } if (200 <= $status && $status < 300) { return $decoded; } throw new RestException( $decoded['message'], $decoded['code'], (isset($decoded['errors']) ? $decoded['errors'] : null) ); }
Convert the JSON encoded response into a PHP object. @param array $response JSON encoded server response @return array
entailment
public function getErrors() { $result = array(); if (count($this->errors) > 0) { if (isset($this->errors['common'])) { $result['common'] = $this->errors['common']; } if (isset($this->errors['fields'])) { foreach ($this->errors['fields'] as $key => $value) { $result[$key] = $value; } } } return $result; }
Get errors received from Textmagic API @return array
entailment
public function import(&$data) { $importedPks = []; foreach ($data as $row) { $skipImport = isset($this->skipImport) ? call_user_func($this->skipImport, $row) : false; if (!$skipImport) { /* @var $model \yii\db\ActiveRecord */ $model = new $this->className; $uniqueAttributes = []; foreach ($this->configs as $config) { if (isset($config['attribute']) && $model->hasAttribute($config['attribute'])) { $value = call_user_func($config['value'], $row); //Create array of unique attributes if (isset($config['unique']) && $config['unique']) { $uniqueAttributes[$config['attribute']] = $value; } //Set value to the model $model->setAttribute($config['attribute'], $value); } } //Check if model is unique and saved with success if ($this->isActiveRecordUnique($uniqueAttributes) && $model->save()) { $importedPks[] = $model->primaryKey; } } } return $importedPks; }
Will multiple import data into table @param array $data CSV data passed by reference to save memory. @return array Primary keys of imported data
entailment
private function isActiveRecordUnique($attributes) { /* @var $class \yii\db\ActiveRecord */ $class = $this->className; return empty($attributes) ? true : !$class::find()->where($attributes)->exists(); }
Will check if Active Record is unique by exists query. @param array $attributes @return boolean
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('minishlink_web_push'); $rootNode ->children() ->arrayNode('api_keys') ->addDefaultsIfNotSet() ->children() ->scalarNode('GCM') ->defaultValue('') ->end() ->end() ->end() ->arrayNode('VAPID') ->children() ->scalarNode('subject') ->end() ->scalarNode('publicKey') ->end() ->scalarNode('privateKey') ->end() ->scalarNode('pemFile') ->end() ->scalarNode('pem') ->end() ->end() ->end() ->integerNode('ttl') ->defaultValue(2419200) ->end() ->scalarNode('topic') ->defaultNull() ->end() ->scalarNode('urgency') ->defaultNull() ->end() ->integerNode('timeout') ->defaultValue(30) ->end() ->booleanNode('automatic_padding') ->defaultValue(true) ->end() ->end() ; return $treeBuilder; }
Generates the configuration tree builder. @return TreeBuilder The tree builder
entailment
public function readFile() { if (!file_exists($this->filename)) { throw new Exception(__CLASS__ . ' couldn\'t find the CSV file.'); } //Prepare fgetcsv parameters $length = isset($this->fgetcsvOptions['length']) ? $this->fgetcsvOptions['length'] : 0; $delimiter = isset($this->fgetcsvOptions['delimiter']) ? $this->fgetcsvOptions['delimiter'] : ','; $enclosure = isset($this->fgetcsvOptions['enclosure']) ? $this->fgetcsvOptions['enclosure'] : '"'; $escape = isset($this->fgetcsvOptions['escape']) ? $this->fgetcsvOptions['escape'] : "\\"; $lines = []; //Clear and set rows if (($fp = fopen($this->filename, 'r')) !== FALSE) { while (($line = fgetcsv($fp, $length, $delimiter, $enclosure, $escape)) !== FALSE) { array_push($lines, $line); } } //Remove unused lines from all lines for ($i = 0; $i < $this->startFromLine; $i++) { unset($lines[$i]); } return $lines; }
Will read CSV file into array @throws Exception @return $array csv filtered data
entailment
public function getList($params = array()) { $this->checkPermissions('getList'); return $this->client->retrieveData($this->resourceName, $params); }
Retrive collection of model objects @param array $params Query params @return array
entailment
public function create($params = array()) { $this->checkPermissions('create'); return $this->client->createData($this->resourceName, $params); }
Create new model object @param array $params Object parameters @return boolean
entailment
public function get($id) { $this->checkPermissions('get'); return $this->client->retrieveData($this->resourceName . '/' . $id); }
Retrieve model object @param mixed $id Object id @return array
entailment
public function update($id, $params = array()) { $this->checkPermissions('update'); return $this->client->updateData($this->resourceName . '/' . $id, $params); }
Update model object @param mixed $id Object id @param array $params Object parameters @return array
entailment
public function delete($id) { $this->checkPermissions('delete'); return $this->client->deleteData($this->resourceName . '/' . $id); }
Delete model object @param mixed $id Object id @return boolean
entailment
public function search($params = array()) { $this->checkPermissions('search'); return $this->client->retrieveData($this->resourceName . '/search', $params); }
Search model object @param array $params Query params @return array
entailment
public function get_fix_query($tables, $error) { $query = ''; switch($error['error']){ case self::TABLE_NOT_EXISTS: $query = $this->getCreateTable($tables[$error['table']]); break; case self::TABLE_WRONG_ENGINE: $query = 'ALTER TABLE `'.$error['table'].'` ENGINE='.$tables[$error['table']]['engine']; break; case self::FIELD_NOT_FOUND: $field = $tables[$error['table']]['fields'][$error['field']]; $query = 'ALTER TABLE `'.$error['table'].'` ADD `'.$error['field'].'` '.$this->getFieldDef($field, false); if (isset($field['auto_increment']) && $field['auto_increment']) { $query .= ";\nALTER TABLE `".$error['table'].'` ADD INDEX tmp_'.$error['field'].' (`'.$error['field'].'`)'; $query .= ";\nALTER TABLE `".$error['table'].'` CHANGE `'.$error['field'].'` `'.$error['field'].'` '.$this->getFieldDef($field); //$query .= ";\nALTER TABLE `".$error['table'].'` CHANGE `'.$error['field'].'` `'.$error['field'].'` '.$this->getFieldDef($field, false); //$query .= ";\nALTER TABLE `".$error['table'].'` ADD PRIMARY KEY (`'.$error['field'].'`)'; //$query .= ";\nALTER TABLE `".$error['table'].'` DROP INDEX tmp_'.$error['field']; } break; case self::EXTRA_FIELD: $query = 'ALTER TABLE `'.$error['table'].'` DROP `'.$error['field'].'`'; break; case self::FIELD_DONT_MATCH: $query = 'ALTER TABLE `'.$error['table'].'` CHANGE `'.$error['field'].'` `'.$error['field'].'` '.$this->getFieldDef($tables[$error['table']]['fields'][$error['field']]); break; case self::EXTRA_KEY: $query = 'ALTER TABLE `'.$error['table'].'` DROP '; if ($error['found'] == 'PRIMARY') $query .= 'PRIMARY KEY'; else $query .= 'INDEX '.$error['found']; break; case self::KEY_NOT_FOUND: $query = 'ALTER TABLE `'.$error['table'].'` ADD '.$this->getIndexDef($tables[$error['table']]['keys'][$error['kid']]); break; case self::KEY_DONT_MATCH: $query = 'ALTER TABLE `'.$error['table'].'` DROP '; if ($tables[$error['table']]['keys'][$error['kid']]['name'] == 'PRIMARY') $query .= 'PRIMARY KEY'; else $query .= 'INDEX '.$tables[$error['table']]['keys'][$error['kid']]['name']; $query .= ', ADD '.$this->getIndexDef($tables[$error['table']]['keys'][$error['kid']]); break; } // switch return $query; }
/* Проверяет существует ли таблица в БД, соответствует ли она схеме БД. В случае расхождений, выполняется корректирующий SQL запрос. @param string $table имя таблицы @param string $module имя модуля @return bool
entailment
public function compare_schemas($ignore_extra_fields = TRUE, $ignore_extra_keys = FALSE) { $res = array(); foreach ($this->schemas as $id => $scheme) { $a = $this->parseSchema($id); if ($a['tables']) foreach ($a['tables'] as $table) { $r = $this->compareTable($id, $table, $ignore_extra_fields, $ignore_extra_keys); $res = array_merge($res, $r); } if ($a['types']) foreach ($a['types'] as $type) { $r = $this->compareType($id, $type); $res = array_merge($res, $r); } if ($a['widgets']) foreach ($a['widgets'] as $widget) { $r = $this->compareWidget($id, $widget); $res = array_merge($res, $r); } if ($a['menus']) foreach ($a['menus'] as $m) { $r = $this->compareMenu($id, $m); $res = array_merge($res, $r); } } return $res; }
/* Проверяет соответствие структуры таблиц реальным таблицам БД. @param bool $ignore_extra_fields игнорировать наличие лишних полей в таблице @param bool $ignore_extra_keys игнорировать наличие лишних индексов в таблице @return array результат проверки
entailment
public function readSchema($module, $drop = true) { $res = $this->parseSchema($module); if (is_array($res['tables'])) foreach ($res['tables'] as $table) { if ($drop) $this->dbConnection->executeQuery('DROP TABLE IF EXISTS `'.$table['name'].'`'); $this->dbConnection->executeQuery($this->getCreateTable($table)); } $this->fixTypes($res['types']); $this->fixWidgets($res['widgets']); $this->fixMenus($res['menus']); }
/* Создает в БД таблицы модуля. @param string $module имя модуля @param boolean $drop удалять предыдущие версии таблиц @return void
entailment
public function dropSchema($module) { $res = $this->parseSchema($module); if (is_array($res['tables'])) foreach ($res['tables'] as $table) { $this->dbConnection->executeQuery('DROP TABLE IF EXISTS `'.$table['name'].'`'); } if (is_array($res['types'])) foreach ($res['types'] as $type) { try { ObjectDefinition::findByTable($type['name'])->delete(); } catch (\Exception $e) {} } }
/* Удаляет из БД таблицы модуля. @param string $module имя модуля @return void
entailment
private function removeRemarks($sql) { $i = 0; while ($i < mb_strlen($sql)) { if (mb_substr($sql,$i,1) == '#' && ($i == 0 || mb_substr($sql,$i-1,1) == "\n")) { $j = 1; while (mb_substr($sql,$i+$j,1) != "\n") { $j++; if ($j+$i > mb_strlen($sql)) { break; } } // end while $sql = mb_substr($sql, 0, $i) . mb_substr($sql, $i+$j); } // end if $i++; } // end while return $sql; }
/* Удаляет комментарии из SQL запроса. @param string $sql запрос @return string
entailment
private function splitSqlFile($sql, $delimiter) { $sql = trim($sql); $char = ''; $last_char = ''; $ret = array(); $string_start = ''; $in_string = FALSE; $escaped_backslash = FALSE; for ($i = 0; $i < mb_strlen($sql); ++$i) { $char = mb_substr($sql, $i, 1); //$sql[$i]; // if delimiter found, add the parsed part to the returned array if ($char == $delimiter && !$in_string) { $ret[] = mb_substr($sql, 0, $i); $sql = mb_substr($sql, $i + 1); $i = 0; $last_char = ''; } if ($in_string) { // We are in a string, first check for escaped backslashes if ($char == '\\') { if ($last_char != '\\') { $escaped_backslash = FALSE; } else { $escaped_backslash = !$escaped_backslash; } } // then check for not escaped end of strings except for // backquotes than cannot be escaped if (($char == $string_start) && ($char == '`' || !(($last_char == '\\') && !$escaped_backslash))) { $in_string = FALSE; $string_start = ''; } } else { // we are not in a string, check for start of strings if (($char == '"') || ($char == '\'') || ($char == '`')) { $in_string = TRUE; $string_start = $char; } } $last_char = $char; } // end for // add any rest to the returned array if (!empty($sql)) { $ret[] = $sql; } return $ret; }
/* Разбивает SQL на отдельные запросы @param string $sql запрос @return array
entailment
private function compareWidget($module, $widget) { $res = array(); try { $w = Application::getInstance()->getWidget( $widget['widgetAlias'] ); } catch (\Exception $e) { $res[] = array( 'error' => self::WIDGET_NOT_EXISTS, 'widget' => $widget['widgetAlias'], 'module' => $module ); } return $res; }
/* Проверяет существует ли Виджет. @param string $module имя модуля @param string $widget alias виджета @return array результат проверки
entailment
private function compareType($module, $type) { $res = array(); try { $od = ObjectDefinition::findByTable($type['name']); } catch (\Exception $e) { $res[] = array( 'error' => self::TYPE_NOT_EXISTS, 'table' => $type['name'], 'module' => $module ); return $res; } if (is_array($type['fields'])) foreach ($type['fields'] as $field) { try { $f = $od->getField($field['name']); foreach ($field as $prop => $value) { if ($prop == 'description') continue; if ($prop == 'editor_user') continue; if ($prop == 'fixed') continue; if (!$f['fixed']) { if ($prop == 'editor') continue; } if ( $prop == 'length' && !(int)$value ) { $_od = ObjectDefinition::findById($f[$prop]); $f[$prop] = $_od->alias; } if ($value != $f[$prop]) { $res[] = array( 'error' => self::TYPE_FIELD_DONT_MATCH, 'field' => $field['name'], 'table' => $type['name'], 'module' => $module, 'expected' => $prop.' => '.$value, 'found' => $prop.' => '.$f[$prop], ); } } } catch (\Exception $e) { $res[] = array( 'error' => self::TYPE_FIELD_NOT_FOUND, 'field' => $field['name'], 'table' => $type['name'], 'module' => $module ); } } return $res; }
/* Проверяет существует ли тип материалов в БД, соответствует ли он схеме. @param string $module имя модуля @param string $type alias типа материалов @return array результат проверки
entailment
private function compareTable($module, $table, $ignore_extra_fields = TRUE, $ignore_extra_keys = FALSE) { $res = array(); $dbtable = $this->describeTable($table['name']); if (!$dbtable) { $res[] = array( 'error' => self::TABLE_NOT_EXISTS, 'table' => $table['name'], 'module' => $module ); return $res; } if ($table['engine'] && $dbtable['engine'] != $table['engine']) { $res[] = array( 'error' => self::TABLE_WRONG_ENGINE, 'table' => $table['name'], 'module' => $module, 'expected' => $table['engine'], 'found' => $dbtable['engine'] ); } if (is_array($table['fields'])) foreach ($table['fields'] as $fname => $field) { if (!isset($dbtable['fields'][$fname])) { $res[] = array( 'error' => self::FIELD_NOT_FOUND, 'field' => $fname, 'table' => $table['name'], 'module' => $module ); continue; } $def = $this->getFieldDef($field); $dbdef = $this->getFieldDef($dbtable['fields'][$fname]); if ($def != $dbdef) $res[] = array( 'error' => self::FIELD_DONT_MATCH, 'field' => $fname, 'table' => $table['name'], 'module' => $module, 'expected' => $def, 'found' => $dbdef ); unset($dbtable['fields'][$fname]); } if (!$ignore_extra_fields && $table['name'] != 'dir_data') if (is_array($dbtable['fields'])) foreach ($dbtable['fields'] as $fname => $field) $res[] = array( 'error' => self::EXTRA_FIELD, 'field' => $fname, 'table' => $table['name'], 'module' => $module ); if (is_array($table['keys'])) foreach ($table['keys'] as $kid => $key) { if (!isset($dbtable['keys'][$kid])) { $res[] = array( 'error' => self::KEY_NOT_FOUND, 'field' => $this->getIndexDef($key),//$key['name'].' ('.implode(',', $key['columns']).')', 'table' => $table['name'], 'module' => $module, 'kid' => $kid, ); continue; } if (($dbtable['keys'][$kid]['columns'] != $key['columns'])||($dbtable['keys'][$kid]['unique'] != $key['unique'])) { $res[] = array( 'error' => self::KEY_DONT_MATCH, 'field' => $key['name'], 'table' => $table['name'], 'module' => $module, 'kid' => $kid, 'expected' => $this->getIndexDef($key),//'('.implode(',', $key['columns']).')'.($key['unique']?' UNIQUE':''), 'found' => $this->getIndexDef($dbtable['keys'][$kid]),//'('.implode(',', $dbtable['keys'][$kid]['columns']).')'.($dbtable['keys'][$kid]['unique']?' UNIQUE':'') ); } unset($dbtable['keys'][$kid]); } if (!$ignore_extra_keys) if (is_array($dbtable['keys'])) foreach ($dbtable['keys'] as $kid => $key) $res[] = array( 'error' => self::EXTRA_KEY, 'field' => $key['name'].' ('.implode(',', $key['columns']).')', 'table' => $table['name'], 'module' => $module, 'found' => $key['name'], 'kid' => $kid ); return $res; }
/* Проверяет существует ли таблица в БД, соответствует ли она схеме БД. @param string $module имя модуля @param string $table информация о таблице @param bool $ignore_extra_fields игнорировать наличие лишних полей в таблице @param bool $ignore_extra_keys игнорировать наличие лишних индексов в таблице @return array результат проверки
entailment
private function getCreateTable($data, $charset = 'utf8') { $sql = "CREATE TABLE `".$data['name']."` (\n"; if (is_array($data['fields'])) foreach ($data['fields'] as $field) { $sql .= " `".$field['name']."` ".$this->getFieldDef($field).",\n"; } if (is_array($data['keys'])) foreach ($data['keys'] as $key) $sql .= ' '.$this->getIndexDef($key).",\n"; $sql = substr($sql, 0, -2)."\n)"; if (isset($data['engine'])) $sql .= ' ENGINE='.$data['engine']; if ($charset) $sql .= ' DEFAULT CHARSET '.$charset; $sql .= ";\n"; return $sql; }
/* Формирует SQL запрос на создание таблицы @param array $table информация о таблице @param string $charset default charset таблицы @return string
entailment
private function getFieldDef($field, $auto_increment = true) { $sql = $field['type']; if ($field['null'] == 0) $sql .= ' NOT NULL'; else $sql .= ' NULL'; if (isset($field['default'])) $sql .= " default '".$field['default']."'"; elseif ((!isset($field['auto_increment']) || !$field['auto_increment'])&&(substr_count(strtolower($field['type']),'int')>0 || substr_count(strtolower($field['type']),'double'))>0) $sql .= " default '0'"; if ($auto_increment && isset($field['auto_increment']) && $field['auto_increment']) $sql .= " auto_increment"; return $sql; }
/* Формирует часть SQL запроса с описанием поля таблицы @param array $field информация о поле @return string
entailment
private function getIndexDef($key) { $sql = ''; if ($key['name'] == 'PRIMARY') $sql .= "PRIMARY KEY ("; else { if ($key['unique']) $sql .= "UNIQUE "; $sql .= "INDEX `".$key['name']."` ("; } foreach ($key['columns'] as $i => $col) { if ($i) $sql .= ','; $sql .= '`'.$col['name'].'`'; if ($col['length']) { $sql .= '('.$col['length'].')'; } } $sql .= ")"; return $sql; }
/* Формирует часть SQL запроса с описанием индекса таблицы @param array $key информация об индексе @return string
entailment
private function describeTable($tname) { $tdescr = $this->dbConnection->fetchAssoc('SHOW TABLE STATUS LIKE "'.$tname.'"'); if (!$tdescr) return FALSE; if ($tdescr['Engine'] == 'HEAP') $tdescr['Engine'] = 'MEMORY'; $table = array('name' => $tname, 'engine' => $tdescr['Engine']); $r = $this->dbConnection->executeQuery('DESCRIBE `'.$tname.'`'); while($f = $r->fetch()) { $nulls = ($f['Null'] && $f['Null'] != 'NO')?1:0; $field = array( 'name' => $f['Field'], 'type' => $f['Type'], 'null' => $nulls ); if (isset($f['Default']) && strlen($f['Default'])) $field['default'] = $f['Default']; if ($f['Extra'] == 'auto_increment') $field['auto_increment'] = 1; if (!isset($table['fields'])) $table['fields'] = array(); $table['fields'][$field['name']] = $field; } // while $r = $this->dbConnection->executeQuery('SHOW KEYS FROM `'.$tname.'`'); $prevkey = FALSE; while($f = $r->fetch()) { if ($prevkey != $f['Key_name']) { if ($prevkey) { if (!isset($table['keys'])) $table['keys'] = array(); $table['keys'][$key['name']] = $key; } $key = array( 'name' => $f['Key_name'], 'unique' => 1-$f['Non_unique'], 'columns' => array() ); } $col = array( 'name' => $f['Column_name'] ); if ($f['Sub_part']) { $col['length'] = $f['Sub_part']; } $key['columns'][] = $col; $prevkey = $f['Key_name']; } if ($prevkey) { if (!isset($table['keys'])) $table['keys'] = array(); $table['keys'][$key['name']] = $key; } return $table; }
/* Считывает из БД информацию о таблице @param string $tname имя таблицы @return array
entailment
public function parseSchema($module) { if (!isset($this->schemas[$module])) return false; if (!isset($this->schemas[$module]['schema'])) return false; $file = $this->schemas[$module]['schema']; if (!file_exists($file) || !is_file($file)) throw new Exception\CMS(Exception\CMS::FILE_NOT_FOUND, $file); $data = implode("",file($file)); $parser = xml_parser_create(); xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1); xml_parse_into_struct($parser,$data,$values,$tags); xml_parser_free($parser); $res = [ 'tables' => [], 'types' => [], 'widgets' => [], 'menus' => [], ]; foreach ($values as $value) { if ($value['tag'] == 'menu') { if ($value['type'] == 'open') { $value['attributes']['data'] = []; $res['menus'][] = $value['attributes']; } } if ($value['tag'] == 'menuitem') { if ($value['type'] != 'close') { $res['menus'][count($res['menus'])-1]['data'][] = $value['attributes']; } } if ($value['tag'] == 'table') { if ($value['type'] == 'open') $table = $value['attributes']; if ($value['type'] == 'close') { if (isset($table['engine']) && $table['engine'] == 'HEAP') $table['engine'] = 'MEMORY'; $res['tables'][$table['name']] = $table; } } if ($value['tag'] == 'widgetcontainer') { if ($value['type'] == 'open') { $widget = $value['attributes']; $widget['widgets'] = array(); } if ($value['type'] == 'close') $res['widgets'][$widget['widgetAlias']] = $widget; } if ($value['tag'] == 'widget') { $value['attributes']['params'] = trim($value['value']); $widget['widgets'][] = $value['attributes']; } if ($value['tag'] == 'object') { if ($value['type'] == 'open') $table = $value['attributes']; if ($value['type'] == 'close') $res['types'][$table['name']] = $table; } if ($value['tag'] == 'field' && isset($value['attributes']['name'])) { if (!isset($table['fields'])) $table['fields'] = array(); $table['fields'][$value['attributes']['name']] = $value['attributes']; } if ($value['tag'] == 'key') { if ($value['type'] == 'open') $key = $value['attributes']; if ($value['type'] == 'close') { if ($key['name']) { if (!isset($table['keys'])) $table['keys'] = array(); $table['keys'][$key['name']] = $key; } } } if ($value['tag'] == 'column' && isset($value['attributes']['name'])) { if (!isset($key['columns'])) $key['columns'] = array(); $key['columns'][] = $value['attributes']; } } if ($module == 'core') { try { foreach (ObjectDefinition::enum() as $od) { foreach ($od->getFields() as $f) { if (is_a($f, '\\Cetera\\ObjectFieldLinkSet2')) { $res['tables'][$f->getLinkTable()] = [ 'name' => $f->getLinkTable(), 'fields' => [ 'id' => [ 'name' => 'id', 'type' => 'int(11)', 'null' => 0 ], 'dest_type' => [ 'name' => 'dest_type', 'type' => 'int(11)', 'null' => 0 ], 'dest_id' => [ 'name' => 'dest_id', 'type' => 'int(11)', 'null' => 0 ], 'tag' => [ 'name' => 'tag', 'type' => 'int(11)', 'default' => 0, 'null' => 0 ], ], 'keys' => [ 'PRIMARY' => [ 'name' => 'PRIMARY', 'unique' => 1, 'columns' => [ ['name' => 'id'], ['name' => 'dest_type'], ['name' => 'dest_id'], ] ], 'dest' => [ 'name' => 'dest', 'unique' => 0, 'columns' => [ ['name' => 'dest_type'], ['name' => 'dest_id'], ] ], ] ]; } if (is_subclass_of($f, '\\Cetera\\ObjectFieldLinkSetAbstract')) { $res['tables'][$f->getLinkTable()] = [ 'name' => $f->getLinkTable(), 'fields' => [ 'id' => [ 'name' => 'id', 'type' => 'int(11)', 'null' => 0 ], 'dest' => [ 'name' => 'dest', 'type' => 'int(11)', 'null' => 0 ], 'tag' => [ 'name' => 'tag', 'type' => 'int(11)', 'default' => 0, 'null' => 0 ], ], 'keys' => [ 'PRIMARY' => [ 'name' => 'PRIMARY', 'unique' => 1, 'columns' => [ ['name' => 'id'], ['name' => 'dest'], ] ], 'dest' => [ 'name' => 'dest', 'unique' => 0, 'columns' => [ ['name' => 'dest'], ] ], ] ]; } } } } catch (\Exception $e) {} } return $res; }
/* Разбирает XML файл со структурой таблиц @param string $module имя модуля @return array список таблиц
entailment
public function xmlTable($tname) { $table = $this->describeTable($tname); if (!$table) return ''; $xml = '<table name="'.$table['name'].'" engine="'.$table['engine'].'">'."\n"; if (is_array($table['fields'])) foreach ($table['fields'] as $field) { $xml .= ' <field'; foreach ($field as $name => $value) $xml .= ' '.$name.'="'.$value.'"'; $xml .= " />\n"; } if (is_array($table['keys'])) foreach ($table['keys'] as $key) { $xml .= ' <key'; foreach ($key as $name => $value) if (!is_array($value)) $xml .= ' '.$name.'="'.$value.'"'; $xml .= ">\n"; foreach ($key['columns'] as $column) $xml .= ' <column name="'.$column.'" />'."\n"; $xml .= " </key>\n"; } $xml .= "</table>\n"; return $xml; }
/* Формирует XML с информацией о таблице @param string $tname имя таблицы @return string
entailment
public static function getById($id, $type = 0, $table = null) { if ($type instanceof ObjectDefinition) $od = $type; else $od = new ObjectDefinition($type, $table); return parent::getByIdType($id, $od); }
Возвращает материал по ID и типу (или таблице) @param int $id ID материала @param int $type тип материала @param string $table Таблица БД, в которой хранятся поля материала @return Material
entailment
public function getCatalog() { if ($this->idcat < 0) return false; try { return Catalog::getById($this->idcat); } catch (\Exception $e) { return false; } }
Возвращает раздел, которому принадлежит материал или false, если материал не принадлежит разделу @return Catalog
entailment
public function getUrl() { if ($this->idcat < 0) return false; $url = '/'.$this->_alias; if ( $this->getCatalog()->isServer() ) return $url; return rtrim($this->getCatalog()->getUrl(),'/').$url; }
Возвращает абсолютный URL материала @return string
entailment
public function getFullUrl($prefix = TRUE) { if ($this->idcat < 0) return false; if (!$this->getCatalog()) return false; return $this->getCatalog()->getFullUrl($prefix).$this->_alias; }
Возвращает полный URL материала @return string
entailment
public function delete() { Event::trigger(EVENT_CORE_MATH_DELETE, ['material' => $this , 'message' => $this->getBoUrl()]); parent::delete(); $this->updateCache(); }
Удаляет материал @return void
entailment
public function copy($dst) { if ((int)$dst && $dst != -1) { $dst = Catalog::getById($dst); } elseif (!is_object($dst) && !is_int($dst)) { throw new Exception\CMS( '$dst must be a Catalog instance or catalog_id.'); } if (is_object($dst)) { if ($dst->materialsType != $this->type) throw new Exception\CMS( 'Materials types of SRC and DST catalogs must be the same.' ); $dst = $dst->id; } $table = $this->table; $r = $this->getDbConnection()->query('SELECT name, type, len, pseudo_type FROM types_fields WHERE id='.$this->type); $fields = array(); $flds = array(); $hlinks = array(); $fld_types = array(); while($f = $r->fetch()) { $fld_types[$f['name']] = $f['type']; if (($f['type'] != FIELD_LINKSET)&&($f['type'] != FIELD_MATSET)) { $flds[] = $f['name']; //if ($f['type'] == FIELD_HLINK) $hlinks[] = $f['name']; } else { $fields[] = $f; } } // while $values = $this->getDbConnection()->fetchAssoc('SELECT `'.implode('`,`', $flds).'` FROM '.$table.' WHERE id='.$this->id); if (!$values) return FALSE; $values['idcat'] = $dst; $values['tag'] = $this->getDbConnection()->fetchColumn("SELECT MAX(tag) FROM $table WHERE idcat=".$dst) + 1; if ($dst >= 0) { $r = $this->getDbConnection()->fetchColumn('SELECT COUNT(*) FROM '.$table.' WHERE idcat=? and alias=?', array($dst, $values['alias'])); if ($r) { $values['alias'] .= '_copy'; $alias = $values['alias']; $alias_exists = 1; $i = 1; while($alias_exists) { if ($i > 1) $values['alias'] = $alias.'_'.$i; $alias_exists = $this->getDbConnection()->fetchColumn('SELECT COUNT(*) FROM '.$table.' WHERE idcat=? and alias=?', array($dst, $values['alias'])); $i++; } } } foreach ($hlinks as $hlink) { $f = $this->getDbConnection()->fetchAssoc('SELECT * FROM field_link WHERE link_id='.(int)$values[$hlink]); if ($f) { unset($f['link_id']); $this->getDbConnection()->executeQuery('INSERT INTO field_link ('.implode(',', array_keys($f)).') VALUES ("'.implode('","', array_values($f)).'")'); $values[$hlink] = $this->getDbConnection()->lastInsertId(); } } foreach($values as $no => $value) { if ($fld_types[$no] == FIELD_DATETIME && !$value) $values[$no] = "'0000-00-00 00:00:00'"; else $values[$no] = $this->getDbConnection()->quote($value); } reset($values); $this->getDbConnection()->executeQuery('INSERT INTO '.$table.' (`'.implode('`,`', $flds).'`) VALUES ('.implode(',', $values).')'); $newid = $this->getDbConnection()->lastInsertId(); foreach ($fields as $field) { if ($field['type'] == FIELD_LINKSET) { if ($field['len'] == CATALOG_VIRTUAL_USERS) { $tablel = User::TABLE; } elseif ($field['pseudo_type'] == PSEUDO_FIELD_CATOLOGS) { $tablel = Catalog::TABLE; } elseif (!$field['len']) { $tablel = $this->table; } else { $c = Catalog::getById($field['len']); if (!$c) continue; $tablel = $c->materialsTable; } $r = $this->getDbConnection()->query('SELECT dest, tag FROM '.$table.'_'.$tablel.'_'.$field['name'].' WHERE id='.$this->id); while($f = $r->fetch()){ $this->getDbConnection()->executeQuery('INSERT INTO '.$table.'_'.$tablel.'_'.$field['name'].' (id, dest, tag) VALUES ('.$newid.','.$f['dest'].','.$f['tag'].')'); } // while } else { $tablel = $this->getDbConnection()->fetchColumn('SELECT alias FROM types WHERE id='.(int)$field['len']); if (!$tablel) continue; $r = $this->getDbConnection()->query('SELECT dest, tag FROM '.$table.'_'.$tablel.'_'.$field['name'].' WHERE id='.$this->id); while($f = $r->fetch()) { $m = Material::getById($f['dest'], $field['len'], $tablel); if ($m) { $newdest = $m->copy(-1); if ($newdest) { $this->getDbConnection()->executeQuery('INSERT INTO '.$table.'_'.$tablel.'_'.$field['name'].' (id, dest, tag) VALUES ('.$newid.','.$newdest.','.$f['tag'].')'); } } } // while } } Event::trigger(EVENT_CORE_MATERIAL_COPY, ['src' => $this, 'dst' => self::getById($newid, $this->objectDefinition)]); return $newid; }
Копирует материал в другой раздел @param Catalog|int $dst раздел, куда копировать материал @return int ID нового материала @throws Exception
entailment
protected function updateCache() { $tpl = new Cache\Tag\Material($this->table,$this->id); $tpl->clean(); $tpl = new Cache\Tag\Material($this->table,0); $tpl->clean(); }
Очистить все кэши связанные с этим материалом @return void
entailment
public static function getExternal($network, $id) { if (!(int)$network) { if (!isset(self::$social[$network])) return null; $network = self::$social[$network]; } $data = self::getDbConnection()->fetchAssoc( 'SELECT A.* FROM '.User::TABLE.' A LEFT JOIN users_external B ON (A.id = B.user_id) WHERE B.external_id = ? and B.external_type = ?', array( $id, $network ) ); if (!$data) { // пробуем найти по старой схеме try { $data = self::getDbConnection()->fetchAssoc( 'SELECT * FROM '.User::TABLE.' WHERE external_id=? and external=?', array( $id, $network ) ); if ($data) { $u = User::fetch($data); $u->addExternal( $network, $id ); } else { return null; } } catch (\Exception $e) { return null; } } $data['external_id'] = $id; switch ( $network ) { case USER_OPENID: return User\OpenId::fetch($data); case USER_FACEBOOK: return User\Facebook::fetch($data); case USER_TWITTER: return User\Twitter::fetch($data); case USER_VK: return User\VK::fetch($data); case USER_LJ: return User::fetch($data); case USER_GOOGLE: return User\Google::fetch($data); case USER_ODNOKLASSNIKI: return User::fetch($data); } return self::fetch($data); }
Возвращает пользователя по ID внешней сети @param mixed $network код внешней сети @param string $id идентификатор пользователя во внешней сети @return User
entailment
public static function getById($uid) { if ($uid == USER_ANONYMOUS) return new User\Anonymous(); $fields = self::getDbConnection()->fetchAssoc( 'SELECT * FROM '.User::TABLE.' WHERE id = ?', array( $uid ) ); if (!$fields) throw new \Exception('User:'.$uid.' is not found'); return self::fetch($fields); }
Возвращает пользователя по ID @param string $username логин @return User
entailment
public static function getByLogin($username) { $fields = self::getDbConnection()->fetchAssoc( 'SELECT * FROM '.User::TABLE.' WHERE login = ?', array( $username ) ); if (!$fields) return false; return self::fetch($fields); }
Возвращает пользователя по его логину @param string $username логин @return User
entailment
public static function getByEmail($email) { $fields = self::getDbConnection()->fetchAssoc('SELECT * FROM '.User::TABLE.' WHERE email = ?', array($email)); if (!$fields) return false; return self::fetch($fields); }
Возвращает пользователя по его e-mail @param string $email логин @return User
entailment
public static function getAuthorized($identity) { $conn = self::getDbConnection(); $conn->executeUpdate('UPDATE users_auth SET time=? WHERE user_id=? and uniq=? and ip=?', array( time(), (int)$identity['user_id'], $identity['uniq'], $_SERVER['REMOTE_ADDR'] )); $fields = $conn->fetchAssoc('SELECT A.* FROM users A LEFT JOIN users_auth B ON (A.id=B.user_id) WHERE B.user_id=? and B.uniq=?', array( (int)$identity['user_id'], $identity['uniq'] )); if ($fields) { return self::fetch($fields); } else { return false; } }
Возвращает авторизованного в данный момент пользователя. Или false, если нет авторизации @return User
entailment
public function addExternal($network, $id) { if (!(int)$network) { if (!isset(self::$social[$network])) return $this; $network = self::$social[$network]; } $this->getDbConnection()->delete('users_external', array( 'external_type' => $network, 'external_id' => $id, )); $this->getDbConnection()->insert('users_external', array( 'user_id' => $this->id, 'external_type' => $network, 'external_id' => $id, )); $this->_external = null; return $this; }
Привязывает пользователя к аккаунту внешней сети @param mixed $network код внешней сети @param string $id идентификатор пользователя во внешней сети @return User
entailment
public function getExternalId($network) { $this->fetchExternal(); if (!(int)$network) { if (!isset(self::$social[$network])) return null; $network = self::$social[$network]; } if (isset( $this->_external[$network] )) return $this->_external[$network]['external_id']; return null; }
Возвращает ID пользователя, если он привязан к внешней сети @param mixed $network код внешней сети @return string $id
entailment
public function allowBackOffice() { if (!$this->isEnabled()) return FALSE; return $this->isInGroup(GROUP_BACKOFFICE) || $this->isInGroup(GROUP_ADMIN); }
Имеет ли право пользователь на доступ в back office @return bool
entailment
public function allowCat($permission, $catalog) { if ($this->allowAdmin()) return TRUE; if (!$this->allowBackOffice()) return FALSE; if (!is_object($catalog)) { if ($catalog == CATALOG_VIRTUAL_HIDDEN) return TRUE; if ($catalog == CATALOG_VIRTUAL_USERS) return FALSE; try { $catalog = Catalog::getById($catalog); } catch (Exception $e) { return FALSE; } } return $catalog->allowAccess($permission, $this->groups); }
Имеет ли пользователь разрешение на раздел @param int $permission код разрешения @param int|Catalog $catalog раздел или ID раздела @return bool
entailment
public function allowFilesystem($path) { if (!$this->allowBackOffice()) return FALSE; $r = self::getDbConnection()->fetchColumn('SELECT COUNT(*) FROM users_groups_deny_filesystem WHERE path=? and group_id IN ('.implode(',',$this->getGroups()).')', array($path), 0); if ($r > 0) return FALSE; return TRUE; }
Имеет ли пользователь право на доступ к физическому каталогу @param string $path путь к каталогу отновительно корня сервера @return bool
entailment
public function getGroups() { if (!is_array($this->fields['groups'])) { $this->fields['groups'] = [GROUP_ALL]; if ($this->id == ADMIN_ID) $this->fields['groups'][] = GROUP_ADMIN; $r = self::getDbConnection()->fetchAll('SELECT group_id FROM users_groups_membership WHERE user_id='.$this->id); foreach ($r as $f) $this->fields['groups'][] = $f['group_id']; } return $this->fields['groups']; }
Список групп, в которых состоит пользователь @return array
entailment
public static function logout($id = null) { if (!$id) $id = \Zend_Auth::getInstance()->getIdentity(); if (!$id) return; self::getDbConnection()->executeQuery("DELETE FROM users_auth WHERE user_id=".$id['user_id']." and uniq='".$id['uniq']."'"); \Zend_Auth::getInstance()->clearIdentity(); \Zend_Session::forgetMe(); }
Снимает авторизацию пользователя @return void
entailment
public function authorize($remember) { $uniq = md5 (uniqid (rand())); $conn = self::getDbConnection(); $conn->executeQuery('UPDATE '.User::TABLE.' SET last_login=NOW() WHERE id='.$this->id); $s = Application::getInstance()->getVar('auth_inactivity_seconds'); if (!$s) $s = AUTH_INACTIVITY_SECONDS; $conn->executeQuery('DELETE FROM users_auth WHERE remember = 0 and time < ?', [time()-$s]); $conn->executeQuery('INSERT INTO users_auth SET user_id='.$this->id.', remember='.(int)$remember.',uniq="'.$uniq.'", ip="'.$_SERVER['REMOTE_ADDR'].'", time='.time()); return $uniq; }
Авторизует пользователя @param bool $remember долговременная авторизация @return void
entailment
public function delete() { if ($this->id == 0 || $this->id == ADMIN_ID) return FALSE; $conn = self::getDbConnection(); $str = 'DELETE [LOGIN='.$this->login.'][ID='.$this->id.']'; $conn->executeQuery('DELETE FROM users_groups_membership WHERE user_id='.$this->id); $conn->executeQuery('DELETE FROM users_auth WHERE user_id='.$this->id); parent::delete(); Event::trigger(EVENT_CORE_USER_PROP,['message' => $str]); }
Удаляет пользователя @return void
entailment
public function compile(\Twig_Compiler $compiler) { $compiler->addDebugInfo($this); $compiler->write("try {\n")->indent(); $compiler ->write("\Cetera\Application::getInstance()->getWidget(") ->subcompile($this->getNode('expr')); if ($this->getNode('variables')) { $compiler ->raw(', ') ->subcompile($this->getNode('variables')); } $compiler->raw(")->display();\n"); $compiler ->outdent() ->write("} catch (\\Exception \$e) {\n") ->indent() //->write("echo '<div class=\"callout alert\">'.\$e->getMessage().'</div>';\n") ->write("echo '<!-- '.\$e->getMessage().' -->';\n") ->outdent() ->write("}\n\n") ; }
Compiles the node to PHP. @param Twig_Compiler $compiler A Twig_Compiler instance
entailment
public function getExtMessage() { if ($this->_noext) return false; $str = 'In file <b>'.$this->getFile().'</b> on line: '.$this->getLine()."<br /><br /><b>Stack trace:</b><br />".nl2br($this->getTraceAsString()); return $str; }
Формирует расширенное сообщение об ошибке @return string
entailment
protected function getMessageByCode($code) { $t = \Cetera\Application::getInstance()->getTranslator(); switch ($code) { case self::SERVER_LIMIT: return $t->_('Исчерпан лимит на количество серверов в системе'); case self::INVALID_PARAMS: return $t->_('Неверный параметр'); case self::CAT_EXISTS: return $t->_('Раздел уже существует "%s"'); case self::CAT_PHYSICAL_EXISTS: return $t->_('Существует файл или каталог с таким именем'); case self::MATERIAL_NOT_FOUND: return $t->_('Материал не найден'); case self::USER_NOT_FOUND: return $t->_('Пользователь не найден'); case self::INVALID_PASSWORD: return $t->_('Неправильный пароль'); case self::AUTHORIZATION_FAILED: return $t->_('Вы не опознаны'); case self::INVALID_EMAIL: return $t->_('Неправильный E-mail'); case self::SQL: return $t->_('Ошибка SQL: %s'); case self::USER_EXISTS: return $t->_('Такой пользователь уже существует'); case self::PASSWORDS_DOESNT_MATCH: return $t->_('-'); case self::SERVER_NOT_FOUND: return $t->_('-'); case self::TYPE_EXISTS: return $t->_('-'); case self::EMAIL_EXISTS: return $t->_('Такой E-mail уже существует'); case self::CANT_CREATE: return $t->_('Невозможно содать тему обсуждения'); case self::MESSAGE_EXISTS: return $t->_('Сообщение уже существует'); case self::NO_RIGHTS: return $t->_('Недостаточно полномочий для совершения этого действия'); case self::TYPE_RESERVED: return $t->_('-'); case self::TYPE_FIXED: return $t->_('-'); case self::FIELD_EXISTS: return $t->_('Поле c таким Alias уже существует'); case self::FIELD_NOT_FOUND: return $t->_('Поле "%s" обязательно для заполнения'); case self::CAT_NOT_FOUND: return $t->_('Раздел не найден'); case self::ALIAS_EXISTS: return $t->_('Материал с таким alias уже существует'); case self::ADD_FIELD: return $t->_('-'); case self::EDIT_FIELD: return $t->_('-'); case self::ENUM_FIELD: return $t->_('-'); case self::FIELD_REQUIRED: return $t->_('-'); case self::CHOOSE_CATALOG: return $t->_('-'); case self::FILE_NOT_FOUND: return $t->_('Файл не найден: %s'); case self::MATERIALS_LIMIT: return $t->_('Вы превысили лимит на количество материалов'); case self::UNKNOWN: default: return $t->_('Неизвестная ошибка (%s)'); } }
Выдает сообщение об ошибке по коду @param int $code код ошибки @return string
entailment
public function fetchElements() { parent::fetchElements(); if ( $this->elements[0]->id > 0 ) array_unshift ( $this->elements , \Cetera\Catalog::getRoot() ); }
/* @internal
entailment
public function parse(\Twig_Token $token) { $expr = $this->parser->getExpressionParser()->parseExpression(); $variables = $this->parseArguments(); return new \Cetera\Twig\Node\Widget($expr, $variables, $token->getLine(), $this->getTag()); }
Parses a token and returns a node. @param Twig_Token $token A Twig_Token instance @return Twig_NodeInterface A Twig_NodeInterface instance
entailment
public static function enum() { $plugins = array(); if (file_exists(DOCROOT.PLUGIN_DIR) && is_dir(DOCROOT.PLUGIN_DIR) && $__dir = opendir(DOCROOT.PLUGIN_DIR)) { while (($__item = readdir($__dir)) !== false) { if($__item=="." or $__item==".." or !is_dir(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$__item)) continue; if (!file_exists(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$__item.DIRECTORY_SEPARATOR.PLUGIN_INFO)) continue; $plugins[$__item] = new self($__item); } closedir($__dir); } ksort($plugins); return $plugins; }
Возвращает все установленные модули @return array
entailment
public static function find($name) { if (!is_dir(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$name)) return false; if (!file_exists(DOCROOT.PLUGIN_DIR.DIRECTORY_SEPARATOR.$name.DIRECTORY_SEPARATOR.PLUGIN_INFO)) return false; return new self($name); }
Возвращает модуль с указанным именем @return Plugin
entailment
public function isEnabled () { try { // Если не хватает требуемых модулей, то отключаем $this->checkRequirements(); // Проверяем соответствует ли версия CMS $this->checkVersion(); } catch(\Exception $e) { return false; } if (self::$disabled === null) { self::$disabled = Application::getInstance()->getVar('module_disable'); if (!is_array(self::$disabled)) self::$disabled = array(); } return !(boolean)(self::$disabled && self::$disabled[$this->name]); }
Включен ли модуль @return boolean
entailment
public function delete($data = false) { if ($this->name == 'partner') return; if ($data) { $schema = new Schema(); $schema->dropSchema($this->name); } Util::delTree(WWWROOT.PLUGIN_DIR.'/'.$this->name); }
Удаляет модуль @param boolean $data удалить из БД все данные модуля @return void
entailment
public function enable() { try { $this->checkRequirements(); $this->checkVersion(); } catch(\Exception $e) { $translator = Application::getInstance()->getTranslator(); throw new \Exception($translator->_('Невозможно включить модуль:').' '.$e->getMessage()); } $a = Application::getInstance(); $md = $a->getVar('module_disable'); unset($md[$this->name]); $a->setVar('module_disable', $md); }
Включить модуль
entailment
public function disable() { $a = Application::getInstance(); $md = $a->getVar('module_disable'); $md[$this->name] = 1; $a->setVar('module_disable', $md); }
Отключить модуль
entailment
public static function install($plugin, $status = null, $translator = null) { if (!$translator) $translator = Application::getInstance()->getTranslator(); $pluginPath = WWWROOT . PLUGIN_DIR . '/' . $plugin; $archiveFile = WWWROOT . PLUGIN_DIR . '/' . $plugin . '.zip'; if ($status) $status($translator->_('Загрузка плагина'), true); if (!file_exists(WWWROOT . PLUGIN_DIR)) mkdir(WWWROOT . PLUGIN_DIR); if (!is_writable(WWWROOT . PLUGIN_DIR)) throw new \Exception($translator->_('Каталог') . ' ' . DOCROOT . PLUGIN_DIR . ' ' . $translator->_('недоступен для записи')); $d = false; try { $client = new \GuzzleHttp\Client(); $res = $client->request('GET', PLUGINS_INFO . '?download=' . $plugin, ['verify'=>false]); $d = $res->getBody(); if (!$d) throw new \Exception($translator->_('Не удалось скачать плагин')); } catch (\Exception $e) { if ($status) { $status($translator->_('Не удалось скачать плагин.'), false); $status($translator->_('Переустановка ранее загруженного плагина'), true, true); } } if ($d) { file_put_contents($archiveFile, $d); if ($status) $status('OK', false); if (file_exists($pluginPath)) { if ($status) $status($translator->_('Удаление предыдущей версии'), true); Util::delTree($pluginPath); if ($status) $status('OK', false); } if ($status) $status($translator->_('Распаковка архива'), true); $zip = new \ZipArchive; if ($zip->open($archiveFile) === TRUE) { if (!$zip->extractTo(WWWROOT . PLUGIN_DIR)) throw new Exception($translator->_('Не удалось распаковать архив'). ' ' . $archiveFile); $zip->close(); unlink($archiveFile); } else throw new \Exception($translator->_('Не удалось открыть архив'). ' ' . $archiveFile); if ($status) $status('OK', false); } if ($status) $status($translator->_('Модификация БД'), true); $schema = new Schema(); $schema->fixSchema('plugin_' . $plugin); $schema->readDump('plugin_' . $plugin); if ($status) $status('OK', false); if (file_exists($pluginPath . '/' . PLUGIN_INSTALL)) include $pluginPath . '/' . PLUGIN_INSTALL; $p = new self($plugin); self::installRequirements($p->requires, $status, $translator); }
Установить модуль из Marketplace @param string $plugin название модуля @param Callable $status метод или функция для приема сообщений @param Zend_Translate $translator класс-переводчик
entailment
public static function installRequirements($req, $status = null, $translator = null) { if (!is_array($req)) return; if (!$translator) $translator = Application::getInstance()->getTranslator(); if ($status) $status($translator->_('Проверка зависимостей:'), true, true); foreach ($req as $r) { $instal = false; if ($status) $status($translator->_('Плагин').' "'.$r['plugin'].'" ('.$r['version'].')', true); $pl = self::find( $r['plugin'] ); if (!$pl) { $instal = true; if ($status) $status($translator->_('отсутствует'), false); } else { if (version_compare($r['version'], $pl['version']) > 0) { $instal = true; if ($status) $status($translator->_('установлен').' '.$pl['version'], false); } } if ($instal) { if ($status) $status($translator->_('Установка/обновление').' "'.$r['plugin'].'"', true, true); self::install($r['plugin'], $status, $translator); } else { if ($status) $status('OK', false); } } }
Устанавливает модули, требующиеся для работы модуля или темы @param array $req список модулей @param Callable $status метод или функция для приема сообщений @param Zend_Translate $translator класс-переводчик
entailment
public static function folderToZip($folder, &$zipFile, $exclusiveLength, $exclude = array('.git'), $prefix = '') { if (!file_exists($folder)) return; $handle = opendir($folder); while (false !== $f = readdir($handle)) { if ($f != '.' && $f != '..') { if (in_array($f, $exclude)) continue; $filePath = "$folder/$f"; // Remove prefix from file path before add to zip. $localPath = $prefix.substr($filePath, $exclusiveLength); if (is_file($filePath)) { $zipFile->addFile($filePath, $localPath); } elseif (is_dir($filePath)) { // Add sub-directory. $zipFile->addEmptyDir($localPath); self::folderToZip($filePath, $zipFile, $exclusiveLength, $exclude, $prefix); } } } closedir($handle); }
Add files and sub-directories in a folder to zip file. @param string $folder @param \ZipArchive $zipFile @param int $exclusiveLength Number of text to be exclusived from the file path.
entailment
public static function zipDir($sourcePath, $outZipPath, $exclude = array('.git') ) { $pathInfo = pathInfo($sourcePath); $parentPath = $pathInfo['dirname']; $dirName = $pathInfo['basename']; $z = new \ZipArchive(); $z->open($outZipPath, \ZipArchive::CREATE); $z->addEmptyDir($dirName); self::folderToZip($sourcePath, $z, strlen("$parentPath/"), $exclude); $z->close(); }
Zip a folder (include itself). Usage: HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip'); @param string $sourcePath Path of directory to be zip. @param string $outZipPath Path of output zip file.
entailment
public static function getByOpenId($openid) { $u = self::getByResult(fssql_query('SELECT * FROM '.User::TABLE.' WHERE external='.USER_OPENID.' and external_id="'.$openid.'"')); if (!$u) { if (!$user['fullname']) $user['fullname'] = parse_url($openid, PHP_URL_HOST); fssql_query('INSERT INTO users (date_reg, email,login,name,disabled,external,external_id) VALUES (NOW(), "'.$user['email'].'","'.parse_url($openid, PHP_URL_HOST).'","'.$user['fullname'].'",0,'.USER_OPENID.',"'.$openid.'")'); $u = self::getByResult(fssql_query('SELECT * FROM '.User::TABLE.' WHERE external='.USER_OPENID.' and external_id="'.$openid.'"')); $u->addExternal(USER_OPENID,$openid); } return $u; }
Возвращает пользователя по его OpenId идентификатору @param string OpenId идентификатор @return User\OpenId
entailment
protected function setWidgets($widgets) { $this->widgets = []; foreach ($widgets as $w) { if (is_subclass_of($w, 'Cetera\Widget\Widget')) $this->widgets[] = $w; elseif ($w) $this->widgets[] = $this->application->getWidget( (int)$w ); } }
Устанавливает в контейнер виджеты @param array $widgets массив виджетов
entailment
public function addWidget($id) { if (!(int)$id) return $this; $this->widgets[] = $this->application->getWidget( (int)$id ); return $this; }
Добавляет в контейнер виджет @param int $id ID добавляемого виджета
entailment
public function removeWidget($id) { if (!(int)$id) return $this; foreach($this->widgets as $key => $w) { if ($w->getId() == $id) { unset($this->widgets[$key]); return $this; } } return $this; }
Удаляет виджет из контейнера @param int $id ID удаляемого виджета
entailment
public function save() { $widgets = $this->getParam('widgets'); if (is_array($widgets)) $this->widgets = $widgets; unset( $this->_params['widgets'] ); parent::save(); $this->getDbConnection()->delete('widgets_containers', array( 'container_id' => $this->getId() )); foreach($this->widgets as $i => $w) $this->getDbConnection()->insert('widgets_containers', array( 'container_id' => $this->getId(), 'widget_id' => $w->getId(), 'position' => $i )); }
Сохраняет виджет в БД
entailment
public function getXml() { $res = '<widgetcontainer widgetAlias="'.htmlspecialchars($this->widgetAlias).'" widgetTitle="'.htmlspecialchars($this->widgetTitle).'" widgetDisabled="'.(int)$this->widgetDisabled.'" widgetProtected="'.(int)$this->widgetProtected.'">'."\n\n"; foreach ($this->getChildren() as $w) { $res .= $w->getXml()."\n"; } $res .= '</widgetcontainer>'."\n"; return $res; }
Экспорт виджета в XML
entailment
public function setCatalog( $catalog ) { if (is_a($catalog,'Cetera\\Catalog') || is_a($catalog,'Cetera\\Server')) { $this->_catalog = $catalog; return; } if (is_int($catalog)) { $this->_catalog = Catalog::getById($catalog); return; } }
Установливает текущий раздел. @param int|Catalog $catalog раздел @return void
entailment
public function setLocale($locale = null, $remember = false) { $this->_locale->setLocale($locale); $t = $this->getTranslator(); if ($t->isAvailable($this->_locale)) $t->setLocale($this->_locale); if ($remember) $this->_session->locale = $this->_locale->toString(); }
Установливает новую локаль приложения и запоминает её в сессии. @param string|\Zend_Locale $locale новая локаль @return void
entailment
public function getTranslator() { if (!$this->_translator) { $this->_translator = new \Zend_Translate( 'gettext', CMSROOT . 'lang', $this->_locale, array('scan'=>\Zend_Translate::LOCALE_FILENAME) ); } return $this->_translator; }
Получить переводчик @internal @return \Zend_Translate
entailment
public function getVar($name) { $this->loadVars(); if (isset($this->_config[$name])) { return $this->_config[$name]; } else { return false; } }
Получить переменную конфигурации @param string $name имя переменной @return mixed
entailment
public function setVar($name, $value) { $this->loadVars(); if ($value === null) { unset($this->_config[$name]); } else { $this->_config[$name] = $value; } $f = fopen(PREFS_FILE,'w'); foreach($this->_config as $name => $value) { if (is_array($value)) continue; fwrite($f,$name."=".$value."\n"); } foreach($this->_config as $name => $value) { if (!is_array($value)) continue; fwrite($f,"\n[".$name."]\n"); foreach ($value as $key => $val) { fwrite($f,$key."=".$val."\n"); } } fclose($f); }
Сохранить переменную конфигурации @param string $name имя переменной @return mixed
entailment
public function getUser() { if ($this->_user) return $this->_user; try { $za = $this->getAuth(); $id = $za->getIdentity(); if (!$id) return FALSE; } catch (\Exception $e) { return FALSE; } if (isset($id['user_id'])) { if (!$this->_connected) return false; $this->_user = User::getAuthorized($id); } return $this->_user; }
Получить авторизованного пользователя @return User
entailment
public function connectDb() { if ($this->_connected) return; if (function_exists('mysql_connect')) { try { mysql_connect($this->getVar('dbhost'),$this->getVar('dbuser'),$this->getVar('dbpass')); mysql_select_db($this->getVar('dbname')); mysql_query('SET NAMES utf8'); } catch (\Exception $e) { throw new \Exception($e->getMessage()); } } $connectionParams = array( 'dbname' => $this->getVar('dbname'), 'user' => $this->getVar('dbuser'), 'password' => $this->getVar('dbpass'), 'host' => $this->getVar('dbhost'), 'driver' => $this->getVar('dbdriver')?$this->getVar('dbdriver'):'pdo_mysql', 'wrapperClass' => 'Cetera\Database\Connection', ); $this->_dbConnection = \Doctrine\DBAL\DriverManager::getConnection( $connectionParams, new \Doctrine\DBAL\Configuration() ); $charset = $this->getVar('dbcharset'); if (!$charset) $charset = 'utf8'; $this->_dbConnection->executeQuery('SET CHARACTER SET '.$charset); $this->_dbConnection->executeQuery('SET names '.$charset); $this->_connected = true; }
Установить соединение с БД @return void
entailment