Browse Source

Добавлен Модуль Импорт Документов

master
SVarlamov 8 years ago
commit
1e925b4b53
  1. 17
      README.md
  2. 641
      import/class.import.php
  3. 1737
      import/excel_reader.php
  4. 4
      import/index.php
  5. 4
      import/lang/index.php
  6. 63
      import/lang/ru.txt
  7. 110
      import/module.php
  8. 47
      import/sql.php
  9. 274
      import/templates/admin_edit.tpl
  10. 95
      import/templates/admin_list.tpl
  11. 4
      import/templates/index.php

17
README.md

@ -0,0 +1,17 @@
## import
# Модуль импорта v1.2.2
## Данный модуль предназначен для импорта документов в определенную рубрику.
* Первая строка в файле - название полей. Со второй строки - значения для импорта. Столбец - это значение поля. Строка - это отдельная позиция, документ.
для примера: <br>
<a href="https://vk.com/wall-38315276_4764">Здесь -> </a> и <br>
<a href="https://vk.com/topic-38315276_27935926">Здесь - ></a>
## Перед копированием модуля в папку modules, удалите файл README.md, копируйте только корневую папку import со всем ее содержимым внутри!
## Changelog:
03.07.2015 - версия 1.2.2

641
import/class.import.php

@ -0,0 +1,641 @@
<?php
/**
* Класс модуля импорта
*
* @package AVE.cms
* @subpackage module_import
* @author Realter
* @since 3.00
* @filesource
*/
class import
{
/**
* Свойства класса
*/
/**
* Парсеры
*/
var $parsers = array('CSV2Array','XML2Array','Excel2Array');
/**
* Основные поля документа, предлагаемые для импорта
*/
var $header_fields = array(
'Id',
'document_title',
'document_alias',
'document_meta_keywords',
'document_meta_description',
'document_meta_robots',
'document_published',
'document_in_search',
'document_status',
'document_linked_navi_id',
'document_breadcrum_title',
'document_parent',
'document_count_view',
);
/**
* Внутренние методы класса
*/
/**
* Удаление документа
*
* @param int $id идентификатор документа
*/
function GetDoc($id)
{
global $AVE_DB;
$AVE_DB->Query("
UPDATE " . PREFIX . "_documents
SET
document_status = '0',
document_deleted = '1'
WHERE Id = " . $id
);
}
/**
* Удаление документа
*
* @param int $id идентификатор документа
*/
function DeleteDoc($id)
{
global $AVE_DB;
$AVE_DB->Query("
UPDATE " . PREFIX . "_documents
SET
document_status = '0',
document_deleted = '1'
WHERE Id=". $id
);
}
/**
* Изменение документа
* @param int $id идентификатор документа
* @param array $array набор данных документа
*/
function UpdateDoc($rub, $id, $array)
{
require_once(BASE_DIR . '/class/class.docs.php');
$AVE_Document = new AVE_Document();
$d = $array['header'];
$d['doc_title'] = $d['document_title'];
$d['document_expire'] = date("d.m.Y H:i",strtotime('+20 year'));
$d['document_status'] = 1;
$d['feld'] = $array['body'];
return $AVE_Document->documentSave($rub,$id,$d);
}
/**
* Добавление документа
*
* @param int $rub идентификатор рубрики
* @param array $array набор данных документа
*/
function InsertDoc($rub, $array)
{
require_once(BASE_DIR.'/class/class.docs.php');
$AVE_Document=new AVE_Document();
$d = $array['header'];
$d['document_expire'] = date("d.m.Y H:i",strtotime('+20 year'));
$d['document_status'] = 1;
$d['doc_title'] = $d['document_title'];
$d['feld'] = $array['body'];
return $AVE_Document->documentSave((int)$rub, null, $d);
}
/**
* Проверка наличия документа по ключевым полям
*
* @param array $array - массив ID_поля_в_рублике=>Ключевое_значение
* @param int $rub - id рубрики
*
* @return int/false - возвращает Id документа или false
*/
function Doc_Exists($key_fields,$rub)
{
global $AVE_DB;
$sql_tables='';
$sql_header='';
$sql_body='';
$header = array();
foreach($key_fields['header'] as $k => $v)
{
$header[] = 'a.' . $k . " = '" . $v . "'";
}
if ($header) $sql_header = ' AND ' . implode(' AND ', $header);
$tables = array();
$body = array();
$x = 0;
foreach($key_fields['body'] as $k => $v)
{
$tables[] = PREFIX . "_document_fields AS t" . $x;
$body[] = "(a.Id=t" . $x . ".document_id AND(t" . $x . ".rubric_field_id=" . $k . " AND t" . $x . ".field_value='" . addslashes($v) . "'))";
$x++;
}
if ($tables) $sql_tables = ', ' . implode(', ', $tables);
if ($body) $sql_body = ' AND ' . implode(' AND ', $body);
$sql = "
SELECT a.Id FROM " . PREFIX . "_documents
AS a " . $sql_tables . "
WHERE
a.rubric_id=" . $rub . $sql_header . $sql_body;
$doc_id = $AVE_DB->Query($sql)->GetCell();
return $doc_id;
}
static function object_to_array($Class)
{
# Typecast to (array) automatically converts stdClass -> array.
$Class = (array)$Class;
$emptyarr=array();
if($emptyarr===$Class) return '';
# Iterate through the former properties looking for any stdClass properties.
# Recursively apply (array).
foreach($Class as $key => &$value)
{
if((is_object($value)||is_array($value)))
{
$Class[$key] = import::object_to_array($value);
}
//$value=addslashes($value);
}
return $Class;
}
/**
* read a csv file and return an indexed array.
* @param string $cvsfile path to csv file
* @param array $fldnames array of fields names. Leave this to null to use the first row values as fields names.
* @param string $sep string used as a field separator (default ';')
* @param string $protect char used to protect field (generally single or double quote)
* @param array $filters array of regular expression that row must match to be in the returned result.
* ie: array('fldname'=>'/pcre_regexp/')
* @return array
*/
function CSV2Array($csvfile,$fldnames=null,$sep=',',$protect='"',$filters=null)
{
if(! $csv = file($csvfile) )
return FALSE;
# use the first line as fields names
if( is_null($fldnames) ){
$fldnames = array_shift($csv);
$fldnames = explode($sep,$fldnames);
$fldnames = array_map('trim',$fldnames);
if($protect){
foreach($fldnames as $k=>$v)
$fldnames[$k] = preg_replace(array("/(?<!\\\\)$protect/","!\\\\($protect)!"),'\\1',$v);
}
}elseif( is_string($fldnames) ){
$fldnames = explode($sep,$fldnames);
$fldnames = array_map('trim',$fldnames);
}
$i=0;
foreach($csv as $row){
if($protect){
$row = preg_replace(array("/(?<!\\\\)$protect/","!\\\\($protect)!"),'\\1',$row);
}
$row = explode($sep,trim($row));
foreach($row as $fldnb=>$fldval)
$res[$i][(isset($fldnames[$fldnb])?$fldnames[$fldnb]:$fldnb)] = $fldval;
if( is_array($filters) ){
foreach($filters as $k=>$exp){
if(! preg_match($exp,$res[$i][$k]) )
unset($res[$i]);
}
}
$i++;
}
unset($csv);
return $res;
}
function Excel2Array($fname)
{
require_once(dirname(__FILE__).'/excel_reader.php');
$Excel = new Spreadsheet_Excel_Reader(); // создаем объект
$Excel->setOutputEncoding('UTF-8'); // устанавливаем кодировку
$Excel->read($fname); // открываем файл
$rowscount = $Excel->sheets[0]['numRows']; // узнаем количество строк в 1 листе $xml = import::object_to_array($xml);
$res = array();
for($rowNum=2;$rowNum<=$rowscount;$rowNum++)
{
$collscount=count($Excel->sheets[0]['cells'][$rowNum]);
for($cell=1;$cell<($collscount+1);$cell++)
{
//Чойто с екселя приходит 160 символ если пусто в ячейке
$val=(trim($Excel->val($rowNum,$cell)));
$res[$rowNum][$Excel->sheets[0]['cells'][1][$cell]]=($val===chr(160) ? '' : $val);
}
}
return $res;
}
function XML2Array($fname)
{
$xml = (simplexml_load_file($fname));
$xml = import::object_to_array($xml);
// Убираем роот элемент из Массива чтобы добраться до самих записей - может есть варианты полегче...
$a = array_values($xml);
unset($xml);
return ($a[0]);
}
// рекурсивно создаёт массив с заменами
function _replace_array($mixed,$key='',$new=true)
{
static $arr = array();
if($new) $arr = array();
if (!is_array($mixed)) return $arr['[row'.$key.']'] = $mixed;
$res = $key;
foreach ($mixed as $k=>$v)
{
if(is_array($v))
{
$arr['[row:'.$k.']'] = serialize($v);
}
$this->_replace_array($v,$res.':'.$k,false);
}
return $arr;
}
// Заменяет в массиве доков, используя массив замен, выполняя код php
function _replace(&$item, &$key, $repl_array)
{
$code = stripslashes(strtr($item,$repl_array));
$item = eval2var('?>' . $code . '<?');
}
/**
* Внешние методы класса
*/
/**
* Вывод списка импортов
*
* @param string $tpl_dir - путь к папке с шаблонами модуля
*/
function importList($tpl_dir)
{
global $AVE_DB, $AVE_Template;
$imports = array();
$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_module_import");
while ($result = $sql->FetchRow())
{
array_push($imports, $result);
}
$rubs = array();
$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_rubrics");
while ($result = $sql->FetchRow())
{
array_push($rubs, $result);
}
$AVE_Template->assign('imports', $imports);
$AVE_Template->assign('rubs', $rubs);
$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'admin_list.tpl'));
}
/**
* Редактирование импорта
*
* @param int $import_id идентификатор системного блока
* @param string $tpl_dir - путь к папке с шаблонами модуля
*
* @todo сделать отдельно методы добавления и редактирования
*/
function importEdit($import_id, $tpl_dir)
{
global $AVE_DB, $AVE_Template;
if (is_numeric($import_id))
{
$row = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_import
WHERE id = '" . $import_id . "'
")->FetchAssocArray();
$row['import_text'] = unserialize($row['import_text']);
}
else
{
$row['import_name'] = '';
$row['import_text'] = array();
$row['import_delete_docs'] = 0;
$row['import_docs_create'] = 0;
}
// рубрики
$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_rubrics");
while ($result = $sql->FetchRow())
{
$rubs[] = $result;
}
// основные поля
$fields = array();
foreach ($this->header_fields as $field)
{
$val = @$row['import_text']['fields']['header'][$field];
$fields['header'][$field] = array(0 => $val, 1 => $AVE_Template->get_config_vars('IMPORT_' . $field));
}
// поля
$s = $AVE_DB->Query("
SELECT * FROM " . PREFIX . "_rubric_fields
WHERE rubric_id = " . intval(@$row['import_rub'])
);
while ($r = $s->FetchAssocArray())
{
$val = $row['import_text']['fields']['body'][$r['Id']];
$fields['body'][$r['Id']] = array(0 => $val, 1 => $r['rubric_field_title']);
}
$row['import_text']['fields'] = $fields;
// передаём данные в смарти
$AVE_Template->assign('rubs',$rubs);
$AVE_Template->assign('parses', $this->parsers);
$AVE_Template->assign('data', $row['import_text']);
unset($row['import_text']);
$AVE_Template->assign($row);
$AVE_Template->assign('content', $AVE_Template->fetch($tpl_dir . 'admin_edit.tpl'));
}
/**
* Сохранение импорта
*
* @param int $import_id идентификатор импорта
*/
function importSave($import_id = null)
{
global $AVE_DB;
if (is_numeric($import_id))
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_import
SET
`import_name` = '" . addslashes($_POST['import_name']) . "',
".($_POST['import_rub']> '' ? "`import_rub` = '" . addslashes($_POST['import_rub']) . "'," : "" )."
`import_parser` = '" . addslashes($_POST['import_parser']) . "',
`import_delete_docs` = '" . ($_POST['import_delete_docs'] ? 1 : 0) . "',
`import_docs_create` = '" . ($_POST['import_docs_create'] ? 1 : 0) . "',
`import_default_file` = '" . addslashes($_POST['import_default_file']) . "',
`import_monitor_file` = '" . addslashes($_POST['import_monitor_file'] ? '1' : '0') . "',
`import_last_update` = '" . addslashes($_POST['import_last_update']) . "',
`import_text` = '" . addslashes(serialize($_POST['document'])) . "'
WHERE
id = '" . $import_id . "'
");
header('Location:index.php?do=modules&action=modedit&mod=import&moduleaction=1&cp=' . SESSION);
exit();
}
else
{
$AVE_DB->Query("
INSERT
INTO " . PREFIX . "_module_import
SET
`import_name` = '" . addslashes($_POST['import_name']) . "',
`import_rub` = '" . addslashes($_POST['import_rub']) . "',
`import_parser` = '" . addslashes($_POST['import_parser']) . "',
`import_delete_docs` = '" . ($_POST['import_delete_docs'] ? 1 : 0) . "',
`import_docs_create` = '" . ($_POST['import_docs_create'] ? 1 : 0) . "',
`import_default_file` = '" . addslashes($_POST['import_default_file']) . "',
`import_monitor_file` = '" . addslashes($_POST['import_monitor_file'] ? '1' : '0') . "',
`import_last_update` = '" . addslashes($_POST['import_last_update']) . "',
`import_text` = '" . addslashes(serialize($_POST['document'])) . "'
");
$import_id = $AVE_DB->Query("SELECT LAST_INSERT_ID(id) FROM " . PREFIX . "_module_import ORDER BY id DESC LIMIT 1")->GetCell();
header('Location:index.php?do=modules&action=modedit&mod=import&moduleaction=edit&id=' . $import_id . '&cp=' . SESSION);
exit();
}
}
/**
* Удаление импорта
*
* @param int $import_id идентификатор системного блока
*/
function importDelete($import_id)
{
global $AVE_DB;
if (is_numeric($import_id))
{
$AVE_DB->Query("
DELETE
FROM " . PREFIX . "_module_import
WHERE id = '" . $import_id . "'
");
}
header('Location:index.php?do=modules&action=modedit&mod=import&moduleaction=1&cp=' . SESSION);
}
/**
* Импорт
*
* @param int $import_id идентификатор системного блока
*/
function DoImport($import_id, $tags_only = false, $location = true)
{
global $AVE_DB;
$_REQUEST['import'] = 'import';
$import = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_import
WHERE id = '" . $import_id . "'
")->FetchAssocArray();
$import['import_text'] = @unserialize($import['import_text']);
if($tags_only) $import['import_text']['tags'] = array();
//Создаем массив ключевых полей
if(is_array(@$import['import_text']['key']['header'])){
foreach($import['import_text']['key']['header'] as $k=>$v)
{
$import_key_fields['header'][$k] = $import['import_text']['fields']['header'][$k];
}
}
if(is_array(@$import['import_text']['key']['body'])){
foreach($import['import_text']['key']['body'] as $k=>$v)
{
$import_key_fields['body'][$k] = $import['import_text']['fields']['body'][$k];
}
}
// Получаем массив из файла импорта
$func = $import['import_parser'];
$rows = $this->$func(BASE_DIR . $import['import_default_file']);
// Помечаем документы как удалённые, если нужно
if($import['import_delete_docs'] && !$tags_only)
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_documents
SET
document_status = '0'
WHERE rubric_id=" . $import['import_rub']
);
}
// Обрабатываем по очереди каждый объект
foreach($rows as $row)
{
// создаем массив замен
$replace_array = array();
$replace_array = $this->_replace_array($row);
$replace_array['[Y-m-d]'] = date('d.m.Y H:i');
// если нужно только обновить теги
if($tags_only)
{
$import['import_text']['tags'] = array_unique(array_merge($import['import_text']['tags'],array_keys($replace_array)));
}
else
{
// дополняем массив замен отсутствующими тегами
foreach($import['import_text']['tags'] as $v)
{
if(! $replace_array[$v]) $replace_array[$v] = '';
}
$key_fields = $import_key_fields;
$doc_fields = array();
$doc_fields['header'] = $import['import_text']['fields']['header'];
$doc_fields['body'] = $import['import_text']['fields']['body'];
// гуляем по шаблонам - заменяем теги на значения
array_walk_recursive($key_fields, array($this, '_replace'), $replace_array);
array_walk_recursive($doc_fields, array($this, '_replace'), $replace_array);
//проверяем значения по критическим полям
$critical = false;
if(isset($import['import_text']['critical']['header'])&&is_array($import['import_text']['critical']['header']))
foreach(@$import['import_text']['critical']['header'] as $k => $v)
if(trim($doc_fields['header'][$k])=='') $critical=true;
if(isset($import['import_text']['critical']['body'])&&is_array($import['import_text']['critical']['body']))
foreach(@$import['import_text']['critical']['body'] as $k => $v)
if(trim($doc_fields['body'][$k])=='') $critical=true;
if(! $critical)
{
//Если прошли проверку импортируем
// проверяем наличие документа по ключевому полю
$id = $this->Doc_Exists($key_fields, $import['import_rub']);
if ($id)
{
// удаляем из массива поля, которые не надо импортировать
foreach($import['import_text']['active']['header'] as $k => $v)
{
if(! $v)
{
$doc_fields['header'][$k] = $AVE_DB->Query("
SELECT " . $k . " FROM " . PREFIX . "_documents
WHERE Id = " . $id
)->GetCell();
}
}
foreach($import['import_text']['active']['body'] as $k => $v)
{
if(! $v)
unset($doc_fields['body'][$k]);
}
unset($doc_fields['header']['Id']);
$this->UpdateDoc($import['import_rub'], $id, $doc_fields);
}
else
{
if ($import['import_docs_create'])
$this->InsertDoc($import['import_rub'], $doc_fields);
}
}
}
}
if (! $tags_only)
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_import
SET
import_last_update = '" . time() . "',
import_text = '" . addslashes(serialize($import['import_text'])) . "'
WHERE id = " . $import_id
);
header('Location:index.php?do=modules&action=modedit&mod=import&moduleaction=1&cp=' . SESSION);
}
else
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_import
SET
import_text = '" . addslashes(serialize($import['import_text'])) . "'
WHERE id = " . $import_id
);
if ($location)
{
header('Location:index.php?do=modules&action=modedit&mod=import&moduleaction=edit&id=' . $import_id . '&cp=' . SESSION);
}
}
}
}
?>

1737
import/excel_reader.php

File diff suppressed because it is too large Load Diff

4
import/index.php

@ -0,0 +1,4 @@
<?php
header('Location:/');
exit;
?>

4
import/lang/index.php

@ -0,0 +1,4 @@
<?php
header('Location:/');
exit;
?>

63
import/lang/ru.txt

@ -0,0 +1,63 @@
IMPORT_MODULE_NAME = "Импорт"
IMPORT_MODULE = "Управление модулем"
IMPORT_EDIT = "Редактирование модуля <span style="color: #000;">&nbsp;&gt;&nbsp;Импорт</span>"
IMPORT_EDIT_TIP = "В данном разделе предоставлены все импорты."
IMPORT_ID = "Id"
IMPORT_NAME = "Имя импорта"
IMPORT_LAST_UPDATE = "Последнее изменение"
IMPORT_ACTIONS = "Действия"
IMPORT_DO_HINT = "Запустить импорт"
IMPORT_NO_ITEMS = "В настоящий момент нет данных"
IMPORT_BUTTON_SAVE = "Сохранить изменения"
IMPORT_CTRLS = "Сохранить и продолжить (CTRL+S)"
IMPORT_BUTTON_ADD = "Добавить импорт"
IMPORT_H_ADD = "Добавление нового импорта"
IMPORT_H_EDIT = "Редактирование импорта"
IMPORT_MAIN_FIELDS = "Основные поля документа"
IMPORT_RUB_FIELDS = "Поля рубрики"
IMPORT_F = "Поле"
IMPORT_TPL = "Шаблон импорта из файла"
IMPORT_TAGS = "Теги:"
IMPORT_KEYS_INFO = "Ключевое поле. Например, Вы сделали импорт и после изменения файла хотите повторить операцию. Если у какого-либо документа ключевое поле совпало, то он будет изменён, в противном случае - создан заново."
IMPORT_ACTIVE_INFO = "Импортировать поле?"
IMPORT_CRITICAL_INFO = "Обязательное поле - если не будет значения запись не импортируется"
IMPORT_INNAME = "Введите название импорт"
IMPORT_ENTER_NAME = "Пожалуйста, укажите название импорта"
IMPORT_INFO_ADD = "Здесь вы можете добавить новый импорт"
IMPORT_INFO_EDIT = "Здесь вы можете изменить выбранный вами импорт"
IMPORT_SAVE = "Сохранить"
IMPORT_CREATE = "Создать и продолжить"
IMPORT_INTEXT = "Системный блок"
IMPORT_ADD = "Добавить новый импорт"
IMPORT_EDIT_HINT = "Редактировать импорт"
IMPORT_DELETE_HINT = "Удалить импорт"
IMPORT_DEL_HINT = "Вы уверены, что хотите удалить импорт ?"
IMPORT_LIST_LINK = "Список импортов"
IMPORT_FILE = "Файл импорта по умолчанию"
IMPORT_DELETE_DOCS = "Перед импортом пометить все документы рубрики как неактивные"
IMPORT_DOCS_CREATE = "Создавать новый документ, если не удаётся найти совпадение по ключевому полю"
IMPORT_CHECK_FILE = "Отслеживать изменения файла и автоматически делать импорт"
IMPORT_PARSER = "Используемый парсер"
IMPORT_RUBRICS = "Рубрика"
IMPORT_Id = "Id документа"
IMPORT_document_title = "Название документа"
IMPORT_document_alias = "Псевдоним документа (alias)"
IMPORT_document_meta_keywords = "Ключевые слова (meta keywords)"
IMPORT_document_meta_description = "Описание страницы (meta description)"
IMPORT_document_meta_robots = "Тип индексирования страницы (meta robots)"
IMPORT_document_published = "Начало публикации"
IMPORT_document_in_search = "Разрешить поиск по документу (0 или 1)"
IMPORT_document_status = "Статус документа (неактивен = 0 или<br>активен = 1)"
IMPORT_document_linked_navi_id = "Связать с пунктом меню (navi_id)"
IMPORT_document_breadcrum_title = "Название ссылки для хлебных крошек"
IMPORT_document_parent = "Связать с документом (doc_id)"
IMPORT_document_count_view = "Количество просмотров"
IMPORT_TAG_DATE = "Тег текущей даты. Формат вывода: yyyy-mm-dd"
IMPORT_TAG_1 = "Значение из элемента массива, где XXX - имя ключа"
IMPORT_TAG_2 = "Значение из многомерного массива; уровень вложенности через :"
IMPORT_SAVED = "Импорт успешно сохранён"
IMPORT_FAILED = "Запрос не выполнен"
IMPORT_TAGS_TITLE = "Теги файла:"
IMPORT_REFRESH_TAGS = "Обновить список тегов"

110
import/module.php

@ -0,0 +1,110 @@
<?php
/**
* AVE.cms - Модуль импорта
*
* @package AVE.cms
* @subpackage module_Import
* @filesource
*/
if(!defined('BASE_DIR')) exit;
if (defined('ACP'))
{
$modul['ModuleName'] = "Модуль импорта";
$modul['ModuleSysName'] = "import";
$modul['ModuleVersion'] = "1.2.2";
$modul['ModuleDescription'] = "Данный модуль предназначен для импорта документов в определенную рубрику";
$modul['ModuleAutor'] = "Realter, val005, M@dD3n";
$modul['ModuleCopyright'] = "&copy; AVE.cms Team - " . date('Y');
$modul['ModuleStatus'] = 1;
$modul['ModuleIsFunction'] = 0;
$modul['ModuleTemplate'] = 0;
$modul['ModuleAdminEdit'] = 1;
$modul['ModuleFunction'] = null;
$modul['ModuleTag'] = null;
$modul['ModuleTagLink'] = null;
$modul['ModuleAveTag'] = null;
$modul['ModulePHPTag'] = null;
}
/**
* Администрирование
*/
function module_import_autoupdate()
{
global $AVE_DB;
$sql="
SELECT
Id,
import_default_file,
import_last_update
FROM " . PREFIX . "_module_import
WHERE import_monitor_file != 0
";
$res = $AVE_DB->Query($sql);
$rows = array();
while ($row = $res->FetchAssocArray())
{
$rows[] = $row;
if(file_exists(BASE_DIR . $row["import_default_file"]))
{
if(filemtime(BASE_DIR . $row["import_default_file"]) > $row['import_last_update'])
{
if (!(is_file(BASE_DIR . '/modules/import/class.import.php') &&
include_once(BASE_DIR . '/modules/import/class.import.php'))) module_error();
$import = new import;
$import -> DoImport($row['Id']);
}
}
}
}
if (defined('ACP') && $_REQUEST['moduleaction'])
{
if (! (is_file(BASE_DIR . '/modules/import/class.import.php')))
module_error();
include_once(BASE_DIR . '/modules/import/class.import.php');
$import = new import;
$tpl_dir = BASE_DIR . '/modules/import/templates/';
$lang_file = BASE_DIR . '/modules/import/lang/' . $_SESSION['user_language'] . '.txt';
$AVE_Template->config_load($lang_file);
switch ($_REQUEST['moduleaction'])
{
case '1':
$import->importList($tpl_dir);
break;
case 'del':
$import->importDelete($_REQUEST['id']);
break;
case 'edit':
$import->importEdit(isset($_REQUEST['id']) ? $_REQUEST['id'] : null, $tpl_dir);
break;
case 'saveedit':
$import->importSave(isset($_REQUEST['id']) ? $_REQUEST['id'] : null);
break;
case 'do':
$import->DoImport($_REQUEST['id'], false);
break;
case 'tags':
$import->DoImport(isset($_REQUEST['id']) ? $_REQUEST['id'] : null, true);
break;
}
}
?>

47
import/sql.php

@ -0,0 +1,47 @@
<?php
/**
* AVE.cms - Модуль импорта
*
* @package AVE.cms
* @subpackage module_Import
* @filesource
*/
/**
* mySQL-запросы для установки, обновления и удаления модуля
*/
$module_sql_install = array();
$module_sql_deinstall = array();
$module_sql_update = array();
$module_sql_deinstall[] = "DROP TABLE IF EXISTS CPPREFIX_module_import;";
$module_sql_install[] = "CREATE TABLE CPPREFIX_module_import (
`id` mediumint(5) unsigned NOT NULL auto_increment,
`import_name` varchar(255) NOT NULL,
`import_rub` int(10) unsigned default NULL,
`import_parser` varchar(255) NOT NULL,
`import_delete_docs` enum('0','1') NOT NULL default '0',
`import_docs_create` enum('0','1') NOT NULL default '0',
`import_default_file` varchar(255) NOT NULL,
`import_monitor_file` enum('0','1') NOT NULL,
`import_last_update` int(10) unsigned default NULL,
`import_text` longtext NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
// Обновление модуля
$module_sql_update[] = "
UPDATE
`CPPREFIX_module`
SET
ModuleAveTag = '" . $modul['ModuleAveTag'] . "',
ModulePHPTag = '" . $modul['ModulePHPTag'] . "',
ModuleVersion = '" . $modul['ModuleVersion'] . "'
WHERE
ModuleSysName = '" . $modul['ModuleSysName'] . "'
LIMIT 1;
";
?>

274
import/templates/admin_edit.tpl

@ -0,0 +1,274 @@
<div class="title">
<h5>{if $smarty.request.id == ''}{#IMPORT_H_ADD#}{else}{#IMPORT_H_EDIT#}{/if}</h5>
</div>
<div class="widget" style="margin-top: 0px;">
<div class="body">
{#IMPORT_INFO_EDIT#}
</div>
</div>
<div class="breadCrumbHolder module">
<div class="breadCrumb module">
<ul>
<li class="firstB"><a href="index.php" title="{#MAIN_PAGE#}">{#MAIN_PAGE#}</a></li>
<li><a href="index.php?do=modules&amp;cp={$sess}">{#MODULES_SUB_TITLE#}</a></li>
<li><a href="index.php?do=modules&action=modedit&mod=import&moduleaction=1&cp={$sess}">{#IMPORT_MODULE_NAME#}</a></li>
<li>{if $smarty.request.id == ''}{#IMPORT_H_ADD#}{else}{#IMPORT_H_EDIT#}{/if}</li>
<li><strong class="code">{if $smarty.request.id == ''}{#IMPORT_H_ADD#}{else}{$import_name|escape}{/if}</strong></li>
</ul>
</div>
</div>
<form method="post" id="import_edit_form" action="index.php?do=modules&action=modedit&mod=import&moduleaction=saveedit&cp={$sess}" class="mainForm">
<div class="widget first">
<div class="head{if $smarty.request.id != ''} closed{/if}">
<h5 class="iFrames">{#IMPORT_H_EDIT#}</h5>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<tr class="noborder">
<td width="250">{#IMPORT_NAME#}</td>
<td>
<div class="pr12">
<input name="import_name" type="text" value="{$import_name|escape}" placeholder="{#CONTACT_FORM_NAME#}" size="50" />
</div>
</td>
</tr>
<tr>
<td>{#IMPORT_RUBRICS#}</td>
<td>
<select class="mousetrap" style="width: 250px" name="import_rub" {if $smarty.request.id != ''}disabled="disabled"{/if}>
{foreach from=$rubs item=rub}
{if $rub->Id==$import_rub}
<option value="{$rub->Id}" selected>{$rub->rubric_title}</option>
{else}
<option value="{$rub->Id}">{$rub->rubric_title}</option>
{/if}
{/foreach}
</select>
</td>
</tr>
<tr>
<td>{#IMPORT_PARSER#}</td>
<td>
<select class="mousetrap" name="import_parser" style="width: 250px">
{foreach from=$parses item=parse}
{if $parse==$import_parser}
<option value="{$parse}" selected>{$parse}</option>
{else}
<option value="{$parse}">{$parse}</option>
{/if}
{/foreach}
</select>
</td>
</tr>
<tr>
<td>{#IMPORT_DELETE_DOCS#}</td>
<td><input class="mousetrap" name="import_delete_docs" type="checkbox" value="1" {if $import_delete_docs==1}checked="checked"{/if}/></td>
</tr>
<tr>
<td>{#IMPORT_DOCS_CREATE#}</td>
<td><input class="mousetrap" name="import_docs_create" type="checkbox" value="1" {if $import_docs_create==1}checked="checked"{/if}/></td>
</tr>
<tr>
<td>{#IMPORT_FILE#}</td>
<td><div class="pr12">
<input class="mousetrap" name="import_default_file" type="text" value="{$import_default_file|escape}" size="50" placeholder="{#IMPORT_FILE#}" />
</div></td>
</tr>
<tr>
<td>{#IMPORT_CHECK_FILE#}</td>
<td><input class="mousetrap" name="import_monitor_file" id="import_monitor_file" type="checkbox" value="1" {if $import_monitor_file==1}checked="checked"{/if}/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" class="basicBtn" value="{if $smarty.request.id != ''}{#IMPORT_SAVE#}{else}{#IMPORT_CREATE#}{/if}"/>
{if $smarty.request.id != ''}
<input type="submit" class="blackBtn SaveEdit" value="{#IMPORT_CTRLS#}" />
<input type="submit" class="greenBtn" value="{#IMPORT_REFRESH_TAGS#}" onclick="window.location ='index.php?do=modules&action=modedit&mod=import&moduleaction=tags&id={$id}&cp={$sess}';return false;" />
<input type="submit" class="redBtn" onclick="location.href='index.php?do=modules&action=modedit&mod=import&moduleaction=do&id={$id}&cp={$sess}'; return false;" value="{#IMPORT_DO_HINT#}" style="float: right;">
{/if}
</td>
</tr>
</table>
</div>
{if $smarty.request.id != ''}
<div style="position:relative;width:73%;float:left">
<div class="widget first">
<div class="head closed">
<h5 class="iFrames">{#IMPORT_MAIN_FIELDS#}</h5>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<thead>
<tr>
<td width="35" align="center">
<div align="center">
<a href="javascript:void(0);" class="topDir icon_sprite ico_info" title="{#IMPORT_ACTIVE_INFO#}"></a>
</div>
</td>
<td width="35" align="center">
<div align="center">
<a href="javascript:void(0);" class="topDir icon_sprite ico_info" title="{#IMPORT_KEYS_INFO#}"></a>
</div>
</td>
<td width="35" align="center">
<div align="center">
<a href="javascript:void(0);" class="topDir icon_sprite ico_info" title="{#IMPORT_CRITICAL_INFO#}"></a>
</div>
</td>
<td width="300">{#IMPORT_F#}</td>
<td>{#IMPORT_TPL#}</td>
</tr>
</thead>
<tbody>
{foreach from=$data.fields.header key=k item=v}
<tr>
<td>
<input class="mousetrap" name="document[active][header][{$k}]" type="hidden" value="0" />
<input class="mousetrap" name="document[active][header][{$k}]" type="checkbox" value="1" {if !$data.active.header.$k==0}checked="checked"{/if} {if $k=='Id'}disabled="disabled"{/if} />
</td>
<td><input class="mousetrap" name="document[key][header][{$k}]" type="checkbox" value="1" {if $data.key.header.$k==1}checked="checked"{/if}/></td>
<td><input class="mousetrap" name="document[critical][header][{$k}]" type="checkbox" value="1" {if $data.critical.header.$k==1}checked="checked"{/if}/></td>
<td>{$v[1]}</td>
<td><div class="pr12"><input class="mousetrap" type="text" name="document[fields][header][{$k}]" value="{$v[0]|escape|stripslashes}" size="50" /></div></td>
</tr>
{/foreach}
</tbody>
</table>
</div>
<div class="widget first">
<div class="head">
<h5 class="iFrames">{#IMPORT_RUB_FIELDS#}</h5>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<thead>
<tr>
<td width="35" align="center">
<div align="center">
<a href="javascript:void(0);" class="topDir icon_sprite ico_info" title="{#IMPORT_ACTIVE_INFO#}"></a>
</div>
</td>
<td width="35" align="center">
<div align="center">
<a href="javascript:void(0);" class="topDir icon_sprite ico_info" title="{#IMPORT_KEYS_INFO#}"></a>
</div>
</td>
<td width="35" align="center">
<div align="center">
<a href="javascript:void(0);" class="topDir icon_sprite ico_info" title="{#IMPORT_CRITICAL_INFO#}"></a>
</div>
</td>
<td width="300">{#IMPORT_F#}</td>
<td>{#IMPORT_TPL#}</td>
</tr>
</thead>
<tbody>
{foreach from=$data.fields.body key=k item=v}
<tr>
<td>
<input class="mousetrap" name="document[active][body][{$k}]" type="hidden" value="0" />
<input class="mousetrap" name="document[active][body][{$k}]" type="checkbox" value="1" {if !$data.active.body.$k==0}checked="checked"{/if}/>
</td>
<td><input class="mousetrap" name="document[key][body][{$k}]" type="checkbox" value="1" {if $data.key.body.$k==1}checked="checked"{/if}/></td>
<td><input class="mousetrap" name="document[critical][body][{$k}]" type="checkbox" value="1" {if $data.critical.body.$k==1}checked="checked"{/if}/></td>
<td>{$v[1]}</td>
<td><div class="pr12"><input class="mousetrap" type="text" name="document[fields][body][{$k}]" value="{$v[0]|escape|stripslashes}" size="50" /></div></td>
</tr>
{/foreach}
<tr>
<td colspan="5">
<input type="hidden" name="id" value="{$id}">
<input type="submit" class="basicBtn" value="{#IMPORT_SAVE#}"/>
<input type="submit" class="blackBtn SaveEdit" value="{#IMPORT_CTRLS#}" />
<input type="submit" class="greenBtn" value="{#IMPORT_REFRESH_TAGS#}" onclick="window.location ='index.php?do=modules&action=modedit&mod=import&moduleaction=tags&id={$id}&cp={$sess}';return false;" />
<input type="submit" class="redBtn" onclick="location.href='index.php?do=modules&action=modedit&mod=import&moduleaction=do&id={$id}&cp={$sess}'; return false;" value="{#IMPORT_DO_HINT#}" style="float: right;">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="widget first" style="position:relative;display:block;float:right;clear:none;width:25%">
<div class="head">
<h5 class="iFrames">{#IMPORT_TAGS#}</h5>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<tr>
<td align="center">
<div class="pr12">
<input class="mousetrap" readonly type="text" value="[Y-m-d]" style="margin-top:5px;" title="{#IMPORT_TAG_DATE#}">
<input class="mousetrap" readonly type="text" value="[row:XXX]" style="margin-top:5px;" title="{#IMPORT_TAG_1#}">
<input class="mousetrap" readonly type="text" value="[row:XXX:YYY:...]" style="margin-top:5px;" title="{#IMPORT_TAG_2#}">
</div>
</td>
</tr>
{if $data.tags}
<tr>
<td align="center">
{#IMPORT_TAGS_TITLE#}
</td>
</tr>
{foreach from=$data.tags key=k item=v}
<tr>
<td align="center">
<div class="pr12"><input class="mousetrap" readonly type="text" value="{$v}"></div>
</td>
</tr>
{/foreach}
{/if}
</table>
</div>
{/if}
</form>
<script language="javascript">
var sett_options = {ldelim}
url: 'index.php?do=modules&action=modedit&mod=import&moduleaction=saveedit&cp={$sess}',
beforeSubmit: Request,
success: Response,
error: Error
{rdelim}
function Request(){ldelim}
$.alerts._overlay('show');
{rdelim}
function Response(){ldelim}
$.alerts._overlay('hide');
$.jGrowl('{#IMPORT_SAVED#}', {ldelim}theme: 'accept'{rdelim});
{rdelim}
function Error(){ldelim}
$.alerts._overlay('hide');
$.jGrowl('{#IMPORT_FAILED#}', {ldelim}theme: 'error'{rdelim});
{rdelim}
$(document).ready(function(){ldelim}
Mousetrap.bind(['ctrl+s', 'meta+s'], function(e) {ldelim}
if (e.preventDefault) {ldelim}
e.preventDefault();
{rdelim} else {ldelim}
// internet explorer
e.returnValue = false;
{rdelim}
$("#import_edit_form").ajaxSubmit(sett_options);
return false;
{rdelim});
$(".SaveEdit").click(function(e){ldelim}
if (e.preventDefault) {ldelim}
e.preventDefault();
{rdelim} else {ldelim}
// internet explorer
e.returnValue = false;
{rdelim}
$("#import_edit_form").ajaxSubmit(sett_options);
return false;
{rdelim});
{rdelim});
</script>

95
import/templates/admin_list.tpl

@ -0,0 +1,95 @@
<script type="text/javascript" language="JavaScript">
$(document).ready(function(){ldelim}
$(".ConfirmDelete").click(function(e){ldelim}
e.preventDefault();
var href = $(this).attr('href');
var title = $(this).attr('name');
var confirm = $(this).attr('dir');
jConfirm(
confirm,
title,
function(b){ldelim}
if (b){ldelim}
$.alerts._overlay('show');
window.location = href;
{rdelim}
{rdelim}
);
{rdelim});
{rdelim});
</script>
<div class="title">
<h5>{#IMPORT_MODULE_NAME#}</h5>
</div>
<div class="widget" style="margin-top: 0px;">
<div class="body">
{#IMPORT_EDIT_TIP#}
</div>
</div>
<div class="breadCrumbHolder module">
<div class="breadCrumb module">
<ul>
<li class="firstB"><a href="index.php" title="{#MAIN_PAGE#}">{#MAIN_PAGE#}</a></li>
<li><a href="index.php?do=modules&amp;cp={$sess}">{#MODULES_SUB_TITLE#}</a></li>
<li>{#IMPORT_MODULE#}</li>
<li><strong class="code">{#IMPORT_MODULE_NAME#}</strong></li>
</ul>
</div>
</div>
<div class="widget first">
<div class="head">
<h5 class="iFrames">{#IMPORT_MODULE_NAME#}</h5>
<div class="num">
<a class="basicNum" href="index.php?do=modules&action=modedit&mod=import&moduleaction=edit&cp={$sess}">{#IMPORT_ADD#}</a>
</div>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic mainForm">
<thead>
<tr>
<td width="10">{#IMPORT_ID#}</td>
<td width="">{#IMPORT_NAME#}</td>
<td width="200">{#IMPORT_RUBRICS#}</td>
<td width="200">{#IMPORT_PARSER#}</td>
<td width="140">{#IMPORT_LAST_UPDATE#}</td>
<td colspan="3">{#IMPORT_ACTIONS#}</td>
</tr>
</thead>
<tbody>
{foreach from=$imports item=import}
<tr>
<td align="center"><strong>{$import->id}</strong></td>
<td><a class="topDir" title="{#IMPORT_EDIT_HINT#}" href="index.php?do=modules&action=modedit&mod=import&moduleaction=edit&cp={$sess}&id={$import->id}"><strong> {$import->import_name|escape}</strong></a></td>
<td align="center">
{foreach from=$rubs item=rub}
{if $rub->Id==$import->import_rub}
<strong class="code">{$rub->rubric_title}</strong>
{/if}
{/foreach}
</td>
<td align="center" class="dgrey nowrap">{$import->import_parser}</td>
<td align="center" class="dgrey nowrap">{$import->import_last_update|date_format:"%Y-%m-%d %H:%M"}</td>
<td width="1%" align="center"><a class="topleftDir icon_sprite ico_start" title="{#IMPORT_DO_HINT#}" href="index.php?do=modules&action=modedit&mod=import&moduleaction=do&cp={$sess}&id={$import->id}"></a></td>
<td width="1%" align="center"><a class="topleftDir icon_sprite ico_edit" title="{#IMPORT_EDIT_HINT#}" href="index.php?do=modules&action=modedit&mod=import&moduleaction=edit&cp={$sess}&id={$import->id}"></a></td>
<td width="1%" align="center"><a class="topleftDir ConfirmDelete icon_sprite ico_delete" dir="{#IMPORT_DEL_HINT#}" name="{#IMPORT_DELETE_HINT#}" title="{#IMPORT_DELETE_HINT#}" href="index.php?do=modules&action=modedit&mod=import&moduleaction=del&cp={$sess}&id={$import->id}"></a></td>
</tr>
{/foreach}
{if ! $imports}
<tr>
<td colspan="8"><ul class="messages">
<li class="highlight yellow">{#IMPORT_NO_ITEMS#}</li>
</ul></td>
</tr>
{/if}
</tbody>
</table>
</div>
{if $page_nav}
<div class="pagination">
<ul class="pages">
{$page_nav}
</ul>
</div>
{/if}

4
import/templates/index.php

@ -0,0 +1,4 @@
<?php
header('Location:/');
exit;
?>
Loading…
Cancel
Save