Initial commit

This commit is contained in:
2026-02-18 20:01:58 +05:00
parent cb8d8f8b5b
commit 2f65983180
14 changed files with 2730 additions and 2 deletions

319
LICENSE Normal file
View File

@@ -0,0 +1,319 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 , USA
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share
and change it. By contrast, the GNU General Public License is intended to
guarantee your freedom to share and change free software--to make sure the
software is free for all its users. This General Public License applies to
most of the Free Software Foundation's software and to any other program whose
authors commit to using it. (Some other Free Software Foundation software
is covered by the GNU Lesser General Public License instead.) You can apply
it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the freedom
to distribute copies of free software (and charge for this service if you
wish), that you receive source code or can get it if you want it, that you
can change the software or use pieces of it in new free programs; and that
you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to
deny you these rights or to ask you to surrender the rights. These restrictions
translate to certain responsibilities for you if you distribute copies of
the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or
for a fee, you must give the recipients all the rights that you have. You
must make sure that they, too, receive or can get the source code. And you
must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2)
offer you this license which gives you legal permission to copy, distribute
and/or modify the software.
Also, for each author's protection and ours, we want to make certain that
everyone understands that there is no warranty for this free software. If
the software is modified by someone else and passed on, we want its recipients
to know that what they have is not the original, so that any problems introduced
by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We
wish to avoid the danger that redistributors of a free program will individually
obtain patent licenses, in effect making the program proprietary. To prevent
this, we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification
follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice
placed by the copyright holder saying it may be distributed under the terms
of this General Public License. The "Program", below, refers to any such program
or work, and a "work based on the Program" means either the Program or any
derivative work under copyright law: that is to say, a work containing the
Program or a portion of it, either verbatim or with modifications and/or translated
into another language. (Hereinafter, translation is included without limitation
in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered
by this License; they are outside its scope. The act of running the Program
is not restricted, and the output from the Program is covered only if its
contents constitute a work based on the Program (independent of having been
made by running the Program). Whether that is true depends on what the Program
does.
1. You may copy and distribute verbatim copies of the Program's source code
as you receive it, in any medium, provided that you conspicuously and appropriately
publish on each copy an appropriate copyright notice and disclaimer of warranty;
keep intact all the notices that refer to this License and to the absence
of any warranty; and give any other recipients of the Program a copy of this
License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you
may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it,
thus forming a work based on the Program, and copy and distribute such modifications
or work under the terms of Section 1 above, provided that you also meet all
of these conditions:
a) You must cause the modified files to carry prominent notices stating that
you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or
in part contains or is derived from the Program or any part thereof, to be
licensed as a whole at no charge to all third parties under the terms of this
License.
c) If the modified program normally reads commands interactively when run,
you must cause it, when started running for such interactive use in the most
ordinary way, to print or display an announcement including an appropriate
copyright notice and a notice that there is no warranty (or else, saying that
you provide a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this License.
(Exception: if the Program itself is interactive but does not normally print
such an announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, and can be reasonably
considered independent and separate works in themselves, then this License,
and its terms, do not apply to those sections when you distribute them as
separate works. But when you distribute the same sections as part of a whole
which is a work based on the Program, the distribution of the whole must be
on the terms of this License, whose permissions for other licensees extend
to the entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest your
rights to work written entirely by you; rather, the intent is to exercise
the right to control the distribution of derivative or collective works based
on the Program.
In addition, mere aggregation of another work not based on the Program with
the Program (or with a work based on the Program) on a volume of a storage
or distribution medium does not bring the other work under the scope of this
License.
3. You may copy and distribute the Program (or a work based on it, under Section
2) in object code or executable form under the terms of Sections 1 and 2 above
provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code,
which must be distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give
any third party, for a charge no more than your cost of physically performing
source distribution, a complete machine-readable copy of the corresponding
source code, to be distributed under the terms of Sections 1 and 2 above on
a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute
corresponding source code. (This alternative is allowed only for noncommercial
distribution and only if you received the program in object code or executable
form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making
modifications to it. For an executable work, complete source code means all
the source code for all modules it contains, plus any associated interface
definition files, plus the scripts used to control compilation and installation
of the executable. However, as a special exception, the source code distributed
need not include anything that is normally distributed (in either source or
binary form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component itself
accompanies the executable.
If distribution of executable or object code is made by offering access to
copy from a designated place, then offering equivalent access to copy the
source code from the same place counts as distribution of the source code,
even though third parties are not compelled to copy the source along with
the object code.
4. You may not copy, modify, sublicense, or distribute the Program except
as expressly provided under this License. Any attempt otherwise to copy, modify,
sublicense or distribute the Program is void, and will automatically terminate
your rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses terminated
so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed
it. However, nothing else grants you permission to modify or distribute the
Program or its derivative works. These actions are prohibited by law if you
do not accept this License. Therefore, by modifying or distributing the Program
(or any work based on the Program), you indicate your acceptance of this License
to do so, and all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program),
the recipient automatically receives a license from the original licensor
to copy, distribute or modify the Program subject to these terms and conditions.
You may not impose any further restrictions on the recipients' exercise of
the rights granted herein. You are not responsible for enforcing compliance
by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement
or for any other reason (not limited to patent issues), conditions are imposed
on you (whether by court order, agreement or otherwise) that contradict the
conditions of this License, they do not excuse you from the conditions of
this License. If you cannot distribute so as to satisfy simultaneously your
obligations under this License and any other pertinent obligations, then as
a consequence you may not distribute the Program at all. For example, if a
patent license would not permit royalty-free redistribution of the Program
by all those who receive copies directly or indirectly through you, then the
only way you could satisfy both it and this License would be to refrain entirely
from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply and
the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents
or other property right claims or to contest validity of any such claims;
this section has the sole purpose of protecting the integrity of the free
software distribution system, which is implemented by public license practices.
Many people have made generous contributions to the wide range of software
distributed through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing to
distribute software through any other system and a licensee cannot impose
that choice.
This section is intended to make thoroughly clear what is believed to be a
consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain
countries either by patents or by copyrighted interfaces, the original copyright
holder who places the Program under this License may add an explicit geographical
distribution limitation excluding those countries, so that distribution is
permitted only in or among countries not thus excluded. In such case, this
License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of
the General Public License from time to time. Such new versions will be similar
in spirit to the present version, but may differ in detail to address new
problems or concerns.
Each version is given a distinguishing version number. If the Program specifies
a version number of this License which applies to it and "any later version",
you have the option of following the terms and conditions either of that version
or of any later version published by the Free Software Foundation. If the
Program does not specify a version number of this License, you may choose
any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs
whose distribution conditions are different, write to the author to ask for
permission. For software which is copyrighted by the Free Software Foundation,
write to the Free Software Foundation; we sometimes make exceptions for this.
Our decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing and reuse
of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR
THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE
STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM
"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE
OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE
OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA
OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible
use to the public, the best way to achieve this is to make it free software
which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach
them to the start of each source file to most effectively convey the exclusion
of warranty; and each file should have at least the "copyright" line and a
pointer to where the full notice is found.
<one line to give the program's name and an idea of what it does.>
Copyright (C) <yyyy> <name of author>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301 , USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when
it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes
with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software,
and you are welcome to redistribute it under certain conditions; type `show
c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may be
called something other than `show w' and `show c'; they could even be mouse-clicks
or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school,
if any, to sign a "copyright disclaimer" for the program, if necessary. Here
is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision'
(which makes passes at compilers) written by James Hacker.
< signature of Ty Coon > , 1 April 1989 Ty Coon, President of Vice This General
Public License does not permit incorporating your program into proprietary
programs. If your program is a subroutine library, you may consider it more
useful to permit linking proprietary applications with the library. If this
is what you want to do, use the GNU Lesser General Public License instead
of this License.

200
README.md
View File

@@ -1,3 +1,199 @@
# workdocs
# Модуль - Работа с документами
###### Массовый обход документов в пределах одной рубрики, и выполенеие действий над ними.
Модуль - Работа с документами. Только для AVE.CMS ALT
## Оглавление
* [Настройки](#настройки)
* [Внутренние функции](#внутренние-функции)
* [Примеры кода перед сохранением](#примеры-кода-перед-сохранением)
* [Пример своей SQL выборки](#пример-своей-sql-выборки)
## Настройки
1. Пересохранять документы при обходе - Включает функцию documentSave, передаются все данные из $data
2. При сохранении документа использовать Исполняемый код рубрики
3. Сохранение ревизий документа
4. Отображать действия в системных сообщениях
Пункты (2, 3, 4 работают только если вкл 1 пункт)<br/>
## Внутренние функции
Является ли файл изображением<br/>
**self::_is_image($path)**<br/>
return bool<br/>
Существует ли файл<br/>
**self::_if_exists($path)**<br/>
return bool<br/>
Есть ли в тексте ссылки (http|s)<br/>
**self::_link_exists($string)**<br/>
return int
Очищает теги от style, убирает пустые теги<br/>
**self::_clear_text($string, $span = false)**<br/>
$span - bool - удалить из текста `<span></span>` (только теги)<br/>
return string<br/>
## Примеры кода перед сохранением
```php
<?php
// Посмотреть все данные, для теста
Debug::_echo($data, true);
?>
```
```php
<?php
// Описание (Многострочное): Поле ID = 1
if (empty($data['feld'][1]))
{
$document_logs[] = 'Нет описания - Поле 1';
}
else
{
if ($num_links = self::_link_exists($data['feld'][1]))
$document_logs[] = 'В описании найдены ссылки: <strong>' . count($num_links) . '</strong>';
// Символов в исходном тексте
$count_text = strlen($data['feld'][1]);
// Очищаем текст
$string = self::_clear_text($data['feld'][1], true);
// Символов в очищенном тексте
$new_count = strlen($string);
// Разница
$diff = $count_text - $new_count;
// Если разница больше 100 символов
if ($diff > 100)
$document_logs[] = 'Текст описания можно уменьшить: <strong>с ' . $count_text . ' до ' . $new_count . '</strong>';
}
?>
```
```php
<?php
// Изображение (Одиночное): Поле ID = 2
$image = $data['feld'][2]['img'];
// Изображение
if (empty($image))
$document_logs[] = 'Нет изображения - Поле 2';
if (! empty($image))
{
// Проврека на наличие файла на сервере
if (! self::_if_exists(BASE_DIR . $image))
{
$document_logs[] = 'Файл отсутсвует на сервере: <strong>' . $image . '</strong>';
}
else
{
if (! self::_is_image(BASE_DIR . $image))
$document_logs[] = 'Неправильный формат файла: <strong>' . $image . '</strong>';
}
}
?>
```
```php
<?php
// Изображение (Мега): Поле ID = 3
$images = $data['feld'][3];
if (empty($images))
$document_logs[] = 'Нет изображений - Поле 3';
if (! empty($images))
{
foreach ($images AS $k => $v)
{
$image = $v['url'];
if (! empty($image))
{
// Проврека на наличие файла на сервере
if (! self::_if_exists(BASE_DIR . $image))
{
$document_logs[] = '('.$k.') Файл отсутсвует на сервере: <strong>' . $image . '</strong>';
}
else
{
if (! self::_is_image(BASE_DIR . $image))
$document_logs[] = '('.$k.') Неправильный файл: <strong>' . $image . '</strong>';
}
}
}
}
?>
```
```php
<?php
// Если документ не опубликован
if ($data['document_status'] == 0)
$document_logs[] = 'Документ не опубликован';
// Если документ в корзине
if ($data['document_deleted'] == 1)
$document_logs[] = 'Документ в корзине';
?>
```
```php
<?php
// Пропускаем запись логов
if ($data['document_title'] != '')
$document_logs = [];
?>
```
## Пример своей SQL выборки
<u>Важно! Перед полным запуском, не забывайете проверить, наличи тестовых данных</u>
```php
<?php
$sql = "
SELECT
Id
FROM
" . PREFIX . "_documents
WHERE
rubric_id = {$rubric_id}
AND
document_status = 1
ORDER BY document_title ASC
LIMIT {$limit}, 1;
";
?>
```
## Запросить конкретный документ для теста
<u>Важно! Перед полным запуском, не забывайете проверить, наличи тестовых данных</u>
```php
<?php
$document_id = 1;
?>
```
Если **$document_logs** пусто - то запись логов не будет производиться<br/>
Если **$data пусто** - то сохранение документа будет пропущено
## Changelog:
05.07.2020 - Дата создания
---
Copyright © 2007-2020 [Ave-Cms.Ru](https://ave-cms.ru)

310
admin/edit.tpl Normal file
View File

@@ -0,0 +1,310 @@
<div class="title">
<h5>{#mod_title#}</h5>
</div>
<div class="widget" style="margin-top: 0px;">
<div class="body">
{#mod_description#}
</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&cp={$sess}">{#MODULES_SUB_TITLE#}</a></li>
<li><a href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=1&cp={$sess}">{#mod_title#}</a></li>
<li>{#mod_edit_breadcrumb#}</li>
<li>{if $work.title}{$work.title}{else}{$smarty.request.title}{/if}</li>
</ul>
</div>
</div>
<form id="saveForm" action="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=save&cp={$sess}" method="post" class="mainForm">
<input type="hidden" id="work_id" name="work_id" value="{$work_id}">
<input type="hidden" id="rubric_id" name="rubric_id" value="{$rubric_id}">
<div class="widget first">
<div class="head">
<h5>{#mod_edit_settings#}</h5>
<div class="num hideBtn" {if ! $work_id}style="display: none"{/if}>
<a class="basicNum topDir" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=run&rubric_id={$rubric_id}&work_id={$work_id}&cp={$sess}">{#mod_edit_btn_run#}</a>
</div>
</div>
<fieldset>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<col width="400" />
<col />
<thead>
<tr>
<td colspan="2">{#mod_edit_settings_work#}</td>
</tr>
</thead>
<tr>
<td>{#mod_edit_settings_name#}</td>
<td><input class="mousetrap" name="title" type="text" id="title" value="{$work.title}" placeholder="{#mod_edit_settings_name#}" style="width: 400px" autocomplete="off"></td>
</tr>
<tr>
<td>{#mod_edit_settings_desc#}</td>
<td>
<input class="mousetrap" name="description" type="text" id="title" value="{$work.description}" placeholder="{#mod_edit_settings_desc#}" autocomplete="off">
</td>
</tr>
<tr>
<td>{#mod_edit_settings_rub#}</td>
<td>
<select id="rubric_id_select" name="rubric_id_select" class="mousetrap" disabled>
<option value="">{#mod_edit_settings_rub_sel#}</option>
{foreach from=$rubrics item=rub}
<option value="{$rub.Id}" {if $rubric_id == $rub.Id}selected{/if}>{$rub.rubric_title|escape}</option>
{/foreach}
</select>
</td>
</tr>
<thead>
<tr>
<td colspan="2">{#mod_edit_settings_doc#}</td>
</tr>
</thead>
<tr>
<td>{#mod_edit_settings_doc_1#}</td>
<td>
<div class="pr12">
<input type="radio" name="save_enable" value="1"{if $work.save_enable == 1} checked{/if} /><label style="cursor: pointer;">{#mod_yes#}</label>&nbsp;
<input type="radio" name="save_enable" value="0"{if $work.save_enable == 0} checked{/if} /><label style="cursor: pointer;">{#mod_no#}</label>
</div>
</td>
</tr>
<tr>
<td>{#mod_edit_settings_doc_2#}</td>
<td>
<div class="pr12">
<input type="radio" name="code_enable" value="1"{if $work.code_enable == 1} checked{/if} /><label style="cursor: pointer;">{#mod_yes#}</label>&nbsp;
<input type="radio" name="code_enable" value="0"{if $work.code_enable == 0} checked{/if} /><label style="cursor: pointer;">{#mod_no#}</label>
</div>
</td>
</tr>
<tr>
<td>{#mod_edit_settings_doc_3#}</td>
<td>
<div class="pr12">
<input type="radio" name="revisions_enable" value="1"{if $work.revisions_enable == 1} checked{/if} /><label style="cursor: pointer;">{#mod_yes#}</label>&nbsp;
<input type="radio" name="revisions_enable" value="0"{if $work.revisions_enable == 0} checked{/if} /><label style="cursor: pointer;">{#mod_no#}</label>
</div>
</td>
</tr>
<tr>
<td>{#mod_edit_settings_doc_4#}</td>
<td>
<div class="pr12">
<input type="radio" name="logs_enable" value="1"{if $work.logs_enable == 1} checked{/if} /><label style="cursor: pointer;">{#mod_yes#}</label>&nbsp;
<input type="radio" name="logs_enable" value="0"{if $work.logs_enable == 0} checked{/if} /><label style="cursor: pointer;">{#mod_no#}</label>
</div>
</td>
</tr>
</table>
<div class="rowElem" id="saveBtn">
<div class="saveBtn">
<input class="basicBtn" type="submit" value="Сохранить" />
ИЛИ
<input type="submit" class="blackBtn SaveWork" value="Применить (CTRL + S)" />
</div>
</div>
</fieldset>
</div>
<div class="widget first">
<div class="head">
<h5>{#mod_edit_code_header#}</h5>
<div class="num hideBtn" {if ! $work_id}style="display: none"{/if}>
<a class="basicNum topDir" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=step&rubric_id={$rubric_id}&work_id={$work_id}&cp={$sess}" target="_blank">Запустить тест</a>
</div>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<col width="50%">
<col width="50%">
<thead>
<tr>
<td>{#mod_edit_code_header_b#}</td>
<td>{#mod_edit_code_header_a#}</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="pr12">
<textarea name="code_before" type="text" id="code_before" value="" style="height:400px;" />{$work.code_before}</textarea>
</div>
</td>
<td>
<div class="pr12">
<textarea name="code_after" type="text" id="code_after" value="" style="height:400px;" />{$work.code_after}</textarea>
</div>
</td>
</tr>
<tr>
<td>
{#mod_edit_code_header_hint#}
</td>
<td>
{#mod_edit_code_header_hint#}
</td>
</tr>
</tbody>
</table>
</div>
<div class="widget first">
<div class="head closed activ">
<h5>{#mod_edit_code_sql_h#}</h5>
</div>
<div style="display: block">
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<col width="50%">
<col width="50%">
<thead>
<tr>
<td>{#mod_edit_code_sql_hint#}</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="pr12">
<textarea name="self_sql" type="text" id="self_sql" value="" style="height:400px;" />{$work.self_sql}</textarea>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="widget first">
<div class="head closed activ">
<h5>{#mod_edit_fields#}</h5>
</div>
<div style="display: block">
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<col width="30">
<col>
<col width="100">
<col width="200">
<thead>
<tr>
<td>{#mod_edit_fields_table_id#}</td>
<td>{#mod_edit_fields_table_name#}</td>
<td>{#mod_edit_fields_table_alias#}</td>
<td>{#mod_edit_fields_table_type#}</td>
</tr>
</thead>
<tbody>
{foreach from=$fields_list item=field_group}
{if $groups_count > 1}
<tr class="grey">
<td colspan="4">
<h5>{if $field_group.group_title}{$field_group.group_title}{else}{#mod_edit_fields_unknow#}{/if}</h5>
</td>
</tr>
{/if}
{foreach from=$field_group.fields item=field}
<tr>
<td align="center">
<strong class="code">{$field.Id}</strong>
</td>
<td>
<strong>{$field.rubric_field_title}</strong>
</td>
<td align="center">
{if $field.rubric_field_alias}<strong class="code">{$field.rubric_field_alias}</strong>{/if}
</td>
<td>
{section name=field_name loop=$field_array}
{if $field.rubric_field_type == $field_array[field_name].id}{$field_array[field_name].name}{/if}
{/section}
</td>
</tr>
{/foreach}
{/foreach}
</tbody>
</table>
</div>
</div>
<div class="widget first">
<div class="head closed active">
<h5>{#mod_edit_rub_code_h#}</h5>
</div>
<div style="display: block">
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<col width="50%">
<col width="50%">
<thead>
<tr>
<td>{#mod_edit_rub_code_t1#}</td>
<td>{#mod_edit_rub_code_t2#}</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="pr12">
<textarea name="rubric_code_start" type="text" id="rubric_code_start" value="" style="height:300px;" />{$rubric.rubric_code_start}</textarea>
</div>
</td>
<td>
<div class="pr12">
<textarea name="rubric_code_end" type="text" id="rubric_code_end" value="" style="height:300px;" />{$rubric.rubric_code_end}</textarea>
</div>
</td>
</tr>
<tr>
<td>
{#mod_edit_rub_code_hint1#}
</td>
<td>
{#mod_edit_rub_code_hint2#}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
<script type="text/javascript" src="{$ABS_PATH}modules/workdocs/js/workdocs.js"></script>
{literal}
<script type="text/javascript" language="JavaScript">
$(document).ready(function() {
"use strict";
ModuleWorkDocs.init();
ModuleWorkDocs.edit();
});
</script>
{/literal}
{include file="$codemirror_connect"}
{include file="$codemirror_editor" conn_id="sql" textarea_id='self_sql' ctrls='ModuleWorkDocs.saveWork();' height=300}
{include file="$codemirror_editor" conn_id="rfs" textarea_id='code_before' ctrls='ModuleWorkDocs.saveWork();' height=400}
{include file="$codemirror_editor" conn_id="rfe" textarea_id='code_after' ctrls='ModuleWorkDocs.saveWork();' height=400}
{include file="$codemirror_editor" conn_id="rcs" textarea_id='rubric_code_start' ctrls='ModuleWorkDocs.saveWork();' height=300}
{include file="$codemirror_editor" conn_id="rce" textarea_id='rubric_code_end' ctrls='ModuleWorkDocs.saveWork();' height=300}

80
admin/log.tpl Normal file
View File

@@ -0,0 +1,80 @@
<div class="widget" style="margin-top: 0px;">
<div class="title">
<h5>{#mod_title#}</h5>
<div class="num">
<a class="redNum clearLog" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=clear&work_id={$work_id}&cp={$sess}">{#mod_log_btn_clear#}</a>
</div>
</div>
</div>
<div class="widget" style="margin-top: 0px;">
<div class="body">
{#mod_description#}
</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&cp={$sess}">{#MODULES_SUB_TITLE#}</a></li>
<li><a href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=1&cp={$sess}">{#mod_title#}</a></li>
<li>{#mod_log_breadcrumbs#}</li>
<li>{$work.title}</li>
</ul>
</div>
</div>
<link rel="stylesheet" href="{$ABS_PATH}modules/workdocs/css/workdocs.css">
<div id="stepDocs" class="widget first">
<div class="head">
<h5 class="iFrames">{#mod_log_tbl_docs#}</h5>
</div>
<table cellpadding="0" cellspacing="0" width="100%" class="display" id="logsTable" data-work-id="{$work.id}">
<col width="30">
<col>
<col width="150">
<col width="500">
<thead>
<tr>
<th class="col-id">{#mod_log_tbl_docs_id#}</th>
<th class="col-title">{#mod_log_tbl_docs_name#}</th>
<th class="col-run">{#mod_log_tbl_docs_date#}</th>
<th class="col-logs">{#mod_log_tbl_docs_logs#}</th>
</tr>
</thead>
<tbody>
<tr>
<td class="col-id"></td>
<td class="col-title"></td>
<td class="col-run"></td>
<td class="col-logs"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript" src="{$ABS_PATH}modules/workdocs/js/workdocs.js"></script>
<script type="text/javascript" language="JavaScript">
var logs,
clear_confirm = '{#mod_log_clear_confirm#}',
clear_title = '{#mod_log_clear_title#}',
sLengthMenu = '{#mod_log_sLengthMenu#}',
sZeroRecords = '{#mod_log_sZeroRecords#}',
sInfo = '{#mod_log_sInfo#}',
sInfoEmpty = '{#mod_log_sInfoEmpty#}',
sInfoFiltered = '{#mod_log_sInfoFiltered#}';
{literal}
$(document).ready(function() {
"use strict";
ModuleWorkDocs.init();
ModuleWorkDocs.log();
});
{/literal}
</script>

155
admin/main.tpl Normal file
View File

@@ -0,0 +1,155 @@
<div class="title">
<h5>{#mod_title#}</h5>
</div>
<div class="widget" style="margin-top: 0px;">
<div class="body">
{#mod_description#}
</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&cp={$sess}">{#MODULES_SUB_TITLE#}</a></li>
<li>{#mod_title#}</li>
</ul>
</div>
</div>
<div class="widget first">
<ul class="tabs">
<li class="activeTab">
<a href="#tab1">{#mod_list_works#}</a>
</li>
<li class="">
<a href="#tab2">{#mod_add_work#}</a>
</li>
<div class="num">
<a class="greenNum clearLogs" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=all&cp={$sess}">{#mod_clear_all_logs#}</a>
</div>
</ul>
<div class="tab_container">
<div id="tab1" class="tab_content" style="display: block;">
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic mainForm">
{if $works}
<col width="30" />
<col />
<col width="150" />
<col width="250" />
<col width="10" />
<col width="10" />
<col width="10" />
<thead>
<tr>
<td>{#mod_main_table_th_id#}</td>
<td>{#mod_main_table_th_name#}</td>
<td>{#mod_main_table_th_run#}</td>
<td>{#mod_main_table_th_rub#}</td>
<td colspan="4">{#mod_main_table_th_actions#}</td>
</tr>
</thead>
<tbody>
{foreach from=$works item=work}
<tr>
<td align="center">
<strong class="code">{$work.id}</strong>
</td>
<td>
<a class="topDir" title="{#mod_main_table_btn_edit#}" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=edit&work_id={$work.id}&cp={$sess}"><strong>{$work.title|escape}</strong></a>
{if $work.description}<br><small>{$work.description}</small>{/if}
</td>
<td align="center" class="col-time">
{if $work.last_run}<span class="date_text dgrey">{$work.last_run|date_format:$TIME_FORMAT|pretty_date}</span>{/if}
</td>
<td align="center">
<strong class="code">
{foreach from=$rubrics item=rubric}
{if $work.rubric_id == $rubric.Id}{$rubric.rubric_title|escape}{/if}
{/foreach}
</strong>
</td>
<td width="1%" align="center">
<a class="topDir icon_sprite ico_start" title="{#mod_main_table_btn_run#}" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=run&work_id={$work.id}&cp={$sess}"></a>
</td>
<td width="1%" align="center">
<a class="topDir icon_sprite ico_navigation" title="{#mod_main_table_btn_logs#}" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=log&work_id={$work.id}&cp={$sess}"></a>
</td>
<td width="1%" align="center">
<a class="topDir icon_sprite ico_setting" title="{#mod_main_table_btn_settings#}" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=edit&work_id={$work.id}&cp={$sess}"></a>
</td>
<td width="1%" align="center">
<a class="topDir icon_sprite ico_delete Delete" title="{#mod_main_table_btn_del#}" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=del&work_id={$work.id}&cp={$sess}"></a>
</td>
</tr>
{/foreach}
{else}
<tr>
<td align="center" colspan="7">
<ul class="messages">
<li class="highlight yellow">{#mod_main_table_no_records#}</li>
</ul>
</td>
</tr>
{/if}
</tbody>
</table>
</div>
<div id="tab2" class="tab_content" style="display: none;">
<form id="addNewForm" method="post" action="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=new&cp={$sess}" class="mainForm">
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic">
<col width="300">
<col>
<tr>
<td>{#mod_main_table_th_name#}</td>
<td><input name="title" type="text" id="title" value="" placeholder="" style="width: 400px" autocomplete="off"></td>
</tr>
<tr>
<td>{#mod_main_table_th_desc#}</td>
<td><input name="description" type="text" id="description" value="" placeholder="" autocomplete="off"></td>
</tr>
<tr>
<td>{#mod_main_table_th_rubdocs#}</td>
<td>
<select id="rubric_id" name="rubric_id" class="mousetrap">
<option value="">{#mod_main_table_th_selrub#}</option>
{foreach from=$rubrics item=rubric}
<option value="{$rubric.Id}">{$rubric.rubric_title|escape}</option>
{/foreach}
</select>
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="basicBtn AddWork">{#mod_main_table_btn_add#}</button>
</td>
</tr>
</table>
</form>
</div>
</div>
<div class="fix"></div>
</div>
<script type="text/javascript" src="{$ABS_PATH}modules/workdocs/js/workdocs.js"></script>
<script type="text/javascript" language="JavaScript">
var del_confirm = '{#mess_del_confirm#}',
del_title = '{#mess_del_title#}',
clear_confirm = '{#mess_clear_confirm#}',
clear_title = '{#mess_clear_title#}',
error_mesage_rubric_id = '{#mess_error_mesage_rubric_id#}',
error_header_rubric_id = '{#mess_error_header_rubric_id#}';
{literal}
$(document).ready(function() {
"use strict";
ModuleWorkDocs.init();
ModuleWorkDocs.index();
});
{/literal}
</script>

146
admin/run.tpl Normal file
View File

@@ -0,0 +1,146 @@
<div class="title">
<h5>{#mod_title#}</h5>
</div>
<div class="widget" style="margin-top: 0px;">
<div class="body">
{#mod_description#}
</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&cp={$sess}">{#MODULES_SUB_TITLE#}</a></li>
<li><a href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=1&cp={$sess}">{#mod_title#}</a></li>
<li>{#mod_run_breadcrumbs#}</li>
<li>{$work.title}</li>
</ul>
</div>
</div>
<div id="blockContinue" class="widget first mainForm" {if $work.last_count == 0}style="display: none;"{/if}>
<div class="rowElem">
<div id="btnBlockNew" class="saveBtn" {if !$diff}style="display: none;"{/if}>
<button class="button redBtn btnStartNew" style="width: 100%; display: inline-block; line-height: 30px; height: 30px;">{#mod_run_btn_repeat#}</button>
</div>
<div id="btnBlockWork" class="saveBtn" {if $diff}style="display: none;"{/if}>
<button class="button blueBtn btnStart" style="width: 50%; display: inline-block; line-height: 30px; height: 30px;">{#mod_run_btn_continue#}</button>
<button class="button redBtn btnStartNew" style="width: 50%; display: inline-block; line-height: 30px; height: 30px;">{#mod_run_btn_repeat#}</button>
</div>
</div>
</div>
<div id="blockRun" class="widget first mainForm"{if $work.last_count > 0}style="display: none;"{/if}>
<div class="rowElem">
<div class="saveBtn">
<button class="button blueBtn btnStartNew" style="width: 100%; display: block; line-height: 30px; height: 30px;">{#mod_run_btn_start#}</button>
</div>
</div>
</div>
<div id="stepBlock" data-work="{$work_id}" data-run="{$work.type}" class="widget first">
<div class="head">
<h5 class="iFrames">{#mod_run_header_progress#}</h5>
<div class="num hideBtn" {if ! $work_id}style="display: none"{/if}>
<a class="basicNum topDir" href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=edit&rubric_id={$rubric_id}&work_id={$work_id}&cp={$sess}">{#mod_run_header_btn_sett#}</a>
</div>
</div>
<div class="body">
<h6 id="header">{#mod_run_header_search_docs#}</h6>
<div>
{#mod_run_search_finded#} <span id="allRecords">{$count}</span>
<br>
{#mod_run_search_ready#} <span id="readyRecords">{if $work.last_count}{$work.last_count - 1}{else}0{/if}</span>
</div>
<div id="progressbar" style="display: block; clear: both; margin-top: 10px;"></div>
<div id="procents" style="text-align: center; margin-top: 10px; font-weight: 600;">0%</div>
<div id="delay" class="highlight yellow" style="text-align: center; margin-top: 10px;">
{#mod_run_search_no_data#}
</div>
<div id="saveTime" style="text-align: center; margin-top: 10px;"></div>
<div id="runData" data-rubric-id="{$rubric_id}" data-work-id="{$work_id}" data-records-counts="{$count}" data-records-start="{if $work.last_count}{$work.last_count - 1}{else}0{/if}"></div>
</div>
<div class="rowElem logDiv" style="display: none;">
<div class="saveBtn">
<a href="cp={$sess}" class="button greyishBtn btnLogs" style="text-align: center; width: 100%; display: block; line-height: 20px; height: 20px;">{#mod_run_btn_see_log#}</a>
</div>
</div>
</div>
<div id="showLog" class="widget first" {if $work.last_count == 0}style="display: none"{/if}>
<div class="rowElem">
<div class="saveBtn">
<a href="index.php?do=modules&action=modedit&mod=workdocs&moduleaction=log&work_id={$work_id}&cp={$sess}" class="button greyishBtn btnLogs" style="text-align: center; width: 100%; display: block; line-height: 20px; height: 20px; padding: 5px 0;">{#mod_run_btn_see_log#}</a>
</div>
</div>
</div>
{if $work.show_logs}
<div id="stepDocs" class="widget first">
<div class="head">
<h5 class="iFrames">{#mod_run_tbl_log#}</h5>
</div>
<table id="logTable" cellpadding="0" cellspacing="0" width="100%" class="tableStatic mainForm">
<col width="30" />
<col />
<col width="450" />
<thead>
<tr>
<td>{#mod_run_tbl_log_id#}</td>
<td>{#mod_run_tbl_log_name#}</td>
<td>{#mod_run_tbl_log_log#}</td>
</tr>
</thead>
{if $work.last_count}
<tbody>
</tbody>
{else}
<tr id="noRecords">
<td align="center" colspan="3">
<ul class="messages">
<li class="highlight yellow">{#mod_run_tbl_log_log_no#}</li>
</ul>
</td>
</tr>
{/if}
</table>
</div>
{/if}
<script type="text/javascript" src="{$ABS_PATH}modules/workdocs/js/workdocs.js"></script>
{literal}
<script type="text/javascript" language="JavaScript">
var allRecords = $('#allRecords').html(), // Общее кол-во
readyRecords = $('#readyRecords'), // Выполнено записей
logTable = $('#logTable'), // Таблица с логами
saveTime = $('#saveTime'), // Время обработки
runData = $('#runData'), // Все для запуска
progressbar = $('#progressbar'), // Прогрессбар
procents = $('#procents'), // Прогрессбар
limitSql = parseInt(runData.data('records-start'));
$(document).ready(function() {
"use strict";
ModuleWorkDocs.init();
ModuleWorkDocs.run();
});
</script>
{/literal}

838
class/class.php Normal file
View File

@@ -0,0 +1,838 @@
<?php
class WorkDocs
{
//-- Templates directory
public static $tpl_dir;
/* ---------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------- */
/*
|-----------------------------------------------------------------------------------------------------------------------
| _json
|-----------------------------------------------------------------------------------------------------------------------
|
| Return array in JSON format
|
*/
public static function _json ($data, $exit = false)
{
header("Content-Type: application/json;charset=utf-8");
$json = json_encode($data);
if ($json === false)
{
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false)
$json = '{"jsonError": "unknown"}';
http_response_code(500);
}
echo $json;
if ($exit)
exit;
}
private static function _get_all_rubrics ()
{
global $AVE_DB;
$sql = "
SELECT
Id,
rubric_title
FROM
" . PREFIX . "_rubrics
ORDER BY rubric_position ASC
";
$sql = $AVE_DB->Query($sql);
$rubrics = [];
while ($rub = $sql->FetchAssocArray())
array_push($rubrics, $rub);
return $rubrics;
}
private static function _get_rubric ($rubric_id = null)
{
global $AVE_DB;
$rubric_id = (isset($_REQUEST['rubric_id']) ? (int)$_REQUEST['rubric_id'] : $rubric_id);
$sql = "
SELECT
*
FROM
" . PREFIX . "_rubrics
WHERE
Id = {$rubric_id}
LIMIT 0,1
";
$sql = $AVE_DB->Query($sql);
return $sql->FetchAssocArray();
}
private static function _get_rubric_fields ($rubric_id = null)
{
global $AVE_DB, $AVE_Template;
$rubric_id = (isset($_REQUEST['rubric_id']) ? (int)$_REQUEST['rubric_id'] : $rubric_id);
// Поля
$sql = "
SELECT
a.*,
b.group_title,
b.group_description,
b.group_position
FROM
" . PREFIX . "_rubric_fields AS a
LEFT JOIN
" . PREFIX . "_rubric_fields_group AS b
ON a.rubric_field_group = b.Id
WHERE
a.rubric_id = '" . $rubric_id . "'
ORDER BY
b.group_position ASC, a.rubric_field_position ASC
";
$sql = $AVE_DB->Query($sql);
$fields_list = [];
while ($row = $sql->FetchRow())
{
$group_id = ($row->rubric_field_group) ? $row->rubric_field_group : 0;
$fields_list[$group_id]['group_position'] = ($row->group_position) ? $row->group_position : 100;
$fields_list[$group_id]['group_title'] = $row->group_title;
$fields_list[$group_id]['group_description'] = $row->group_description;
$fields_list[$group_id]['fields'][$row->Id]['Id'] = $row->Id;
$fields_list[$group_id]['fields'][$row->Id]['rubric_id'] = $row->rubric_id;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_group'] = $row->rubric_field_group;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_alias'] = $row->rubric_field_alias;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_title'] = $row->rubric_field_title;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_type'] = $row->rubric_field_type;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_numeric'] = $row->rubric_field_numeric;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_default'] = $row->rubric_field_default;
$fields_list[$group_id]['fields'][$row->Id]['rubric_field_search'] = $row->rubric_field_search;
}
$fields_list = msort($fields_list, 'group_position');
$AVE_Template->assign('groups_count', count($fields_list));
$AVE_Template->assign('fields_list', $fields_list);
$AVE_Template->assign('field_array', get_field_type());
}
private static function _get_work ($work_id = null)
{
global $AVE_DB;
$work_id = (isset($_REQUEST['work_id']) ? (int)$_REQUEST['work_id'] : $work_id);
$sql = "
SELECT
*
FROM
" . PREFIX . "_module_workdocs
WHERE
id = {$work_id}
LIMIT 0,1
";
$sql = $AVE_DB->Query($sql);
return $sql->FetchAssocArray();
}
private static function _get_works ()
{
global $AVE_DB;
$sql = "
SELECT
*
FROM
" . PREFIX . "_module_workdocs
";
$sql = $AVE_DB->Query($sql);
$works = [];
while ($work = $sql->FetchAssocArray())
array_push($works, $work);
return $works;
}
private static function _get_num_docs ($rubric_id = null)
{
global $AVE_DB;
$rubric_id = (isset($_REQUEST['rubric_id']) ? (int)$_REQUEST['rubric_id'] : $rubric_id);
$sql = "
SELECT
count(Id)
FROM
" . PREFIX . "_documents
WHERE
rubric_id = {$rubric_id}
";
$sql = $AVE_DB->Query($sql);
return $sql->GetCell();
}
private static function _get_document ($doc_id = null)
{
if (! is_numeric($doc_id) OR $doc_id < 1)
return false;
$data = get_document($doc_id);
$fields = get_document_fields ($doc_id);
foreach ($fields AS $k => $v)
if (is_numeric($k))
$data['feld'][$k] = self::_field_type_value($v);
unset ($fields);
return $data;
}
private static function _field_type_value ($data = [])
{
if (empty($data))
return false;
$func = 'get_field_' . $data['rubric_field_type'];
if (! is_callable($func))
$func = 'get_field_default';
$field_value = $func($data['field_value'], 'api', $data['rubric_field_id'], null, null, $x, null, null, null, $data['rubric_field_default']);
return $field_value;
}
private static function _set_first_start ($work_id)
{
global $AVE_DB;
if (! $work_id)
return false;
$sql = "
DELETE FROM
" . PREFIX . "_module_workdocs_logs
WHERE
work_id = {$work_id}
";
$AVE_DB->Query($sql);
$sql = "
UPDATE
" . PREFIX . "_module_workdocs
SET
last_run = '" . time() . "',
last_count = 0
WHERE
id = {$work_id}
";
$AVE_DB->Query($sql);
return true;
}
private static function _save_logs ($work_id, $document_id, $document_title, $rubric_id, $document_logs, $limit)
{
global $AVE_DB;
$document_title = htmlspecialchars($document_title, ENT_QUOTES);
if ($document_logs)
{
$sql = "
INSERT INTO
" . PREFIX . "_module_workdocs_logs
SET
`work_id` = '{$work_id}',
`rubric_id` = '{$rubric_id}',
`document_id` = '{$document_id}',
`document_title` = '{$document_title}',
`last_run` = '" . time() . "',
`logs` = '" . serialize($document_logs) . "'
";
$AVE_DB->Query($sql);
}
$sql = "
UPDATE
" . PREFIX . "_module_workdocs
SET
last_count = '" . ($limit + 1) . "'
WHERE
id = '{$work_id}'
";
$AVE_DB->Query($sql);
return true;
}
private static function _doc_save ($document_id, $rubric_id, $data, $code, $revisions, $logs)
{
include_once BASE_DIR . '/class/class.docs.php';
$AVE_Document = new AVE_Document();
$document_id = $AVE_Document->documentSave($rubric_id, $document_id, $data, false, $code, $revisions, $logs, false);
return $document_id;
}
private static function _get_logs_json ($work_id = null)
{
global $AVE_DB;
$work = self::_get_work($work_id);
$where = '';
switch ($_REQUEST['iSortCol_0'])
{
case '0':
$order = 'ORDER BY document_id ';
break;
case '1':
$order = 'ORDER BY document_title ';
break;
case '2':
$order = 'ORDER BY last_run ';
break;
case '3':
$order = 'ORDER BY logs ';
break;
}
$order .= $_REQUEST['sSortDir_0'];
$start = $_REQUEST['iDisplayStart'] ? (int)$_REQUEST['iDisplayStart'] : 0;
$finish = $_REQUEST['iDisplayLength'] ? (int)$_REQUEST['iDisplayLength'] : 40;
if (isset($_REQUEST['sSearch']) && $_REQUEST['sSearch'] != '')
{
$where = "AND (document_id LIKE '%{$_REQUEST['sSearch']}%'";
$where .= " OR document_title LIKE '%{$_REQUEST['sSearch']}%'";
$where .= " OR last_run LIKE '%{$_REQUEST['sSearch']}%'";
$where .= " OR logs LIKE '%{$_REQUEST['sSearch']}%')";
}
$sql = "
SELECT SQL_CALC_FOUND_ROWS
*
FROM
" . PREFIX . "_module_workdocs_logs
WHERE
work_id = '{$work_id}'
{$where}
{$order}
LIMIT {$start},{$finish}
";
$sql = $AVE_DB->Query($sql);
$num = $AVE_DB->GetFoundRows();
$output = [
'sEcho' => (int)$_REQUEST['sEcho'],
'iTotalRecords' => $num,
'iTotalDisplayRecords' => $num,
'aaData' => []
];
while ($log = $sql->FetchAssocArray())
{
$output['aaData'][] = [
'<a title="Edit" href="index.php?do=docs&action=edit&rubric_id='. $work['rubric_id'] .'&Id='. $log['document_id'] .'&cp='.SESSION.'" target="_blank">'. $log['document_id'] .'</a>',
'<a title="Show" href="/index.php?id='. $log['document_id'] .'" target="_blank"><strong>' . $log['document_title'] . '</strong></a>',
'<span class="date_text dgrey">' . translate_date(strftime(TIME_FORMAT, $log['last_run'])) . '</span>',
'<small>' . implode('<br>', unserialize($log['logs'])) . '</small>'
];
}
return $output;
}
public static function _clear_text ($string = null, $span = false)
{
// Убираем пробелы начало/конец
$string = trim($string);
// Замена <br>
$replace = [
'<br />' => '<br>',
'<br/>' => '<br>'
];
$string = str_replace(array_keys($replace), array_values($replace), $string);
// RegExp
$expression = [
// Убираем пустые теги
'~<(p|span)>(?>\s+|&nbsp;|(?R))*</\1>~' => '',
// Убираем стили из тегов
'/(<[^>]+) style=".*?"/i' => '$1',
// Убираем двойные пробелы
'/\s{2,}/' => ' ',
// Убираем переходы на новую строку
'/[\t\n]/' => ' ',
// Убираем пустые теги
'/<(\w+)\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|"[^"]*"|[\w\-.:]+))?)*\s*\/?>\s*<\/\1\s*>/' => ''
];
// Очищаем текст по условиям
$string = preg_replace(array_keys($expression), array_values($expression), $string);
// Убираем span
if ($span)
{
$replace = [
'<span>' => '',
'</span>' => ''
];
$string = str_replace(array_keys($replace), array_values($replace), $string);
}
// Повторно проходимся по условиям
$string = preg_replace(array_keys($expression), array_values($expression), $string);
// Убираем пробелы начало/конец
$string = trim($string);
return $string;
}
public static function _is_image ($path = null)
{
if (@is_array(getimagesize($path)))
return true;
return false;
}
public static function _if_exists ($path = null)
{
if (file_exists($path))
return true;
return false;
}
public static function _link_exists ($string = null)
{
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $string, $match);
return $match[0];
}
/* ---------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------- */
public static function mainPage ()
{
global $AVE_Template;
$AVE_Template->assign('works', self::_get_works());
$AVE_Template->assign('rubrics', self::_get_all_rubrics());
$AVE_Template->assign('content', $AVE_Template->fetch(self::$tpl_dir . 'main.tpl'));
}
public static function editWork ()
{
global $AVE_Template;
$work_id = (isset($_REQUEST['work_id']) ? (int)$_REQUEST['work_id'] : '');
$rubric_id = (isset($_REQUEST['rubric_id']) ? (int)$_REQUEST['rubric_id'] : '');
if (! $work_id)
{
$work = [
'title' => (isset($_REQUEST['title']) ? $_REQUEST['title'] : 'Без названия'),
'description' => (isset($_REQUEST['description']) ? $_REQUEST['description'] : ''),
'rubric_id' => $rubric_id
];
$AVE_Template->assign('work', $work);
}
else
{
$work = self::_get_work();
$rubric_id = $work['rubric_id'];
}
self::_get_rubric_fields($rubric_id);
$AVE_Template->assign('work', $work);
$AVE_Template->assign('work_id', $work_id);
$AVE_Template->assign('rubric', self::_get_rubric($rubric_id));
$AVE_Template->assign('rubric_id', $rubric_id);
$AVE_Template->assign('rubrics', self::_get_all_rubrics());
$AVE_Template->assign('content', $AVE_Template->fetch(self::$tpl_dir . 'edit.tpl'));
}
public static function saveWork ()
{
global $AVE_DB, $AVE_Template;
$work_id = (int)$_REQUEST['work_id'];
if (! $work_id)
{
$sql = "
INSERT INTO
" . PREFIX . "_module_workdocs
SET
title = '" . $_REQUEST['title'] . "',
description = '" . $_REQUEST['description'] . "',
rubric_id = '" . (int)$_REQUEST['rubric_id'] . "',
save_enable = '" . ($_REQUEST['save_enable'] ? '1' : '0') . "',
code_enable = '" . ($_REQUEST['code_enable'] ? '1' : '0') . "',
revisions_enable = '" . ($_REQUEST['revisions_enable'] ? '1' : '0') . "',
logs_enable = '" . ($_REQUEST['logs_enable'] ? '1' : '0') . "',
self_sql = '" . $_REQUEST['self_sql'] . "',
code_before = '" . $_REQUEST['code_before'] . "',
code_after = '" . $_REQUEST['code_after'] . "'
";
$sql = $AVE_DB->Query($sql);
$work_id = $AVE_DB->InsertId();
}
else
{
$sql = "
UPDATE
" . PREFIX . "_module_workdocs
SET
title = '" . $_REQUEST['title'] . "',
description = '" . $_REQUEST['description'] . "',
save_enable = '" . ($_REQUEST['save_enable'] ? '1' : '0') . "',
code_enable = '" . ($_REQUEST['code_enable'] ? '1' : '0') . "',
revisions_enable = '" . ($_REQUEST['revisions_enable'] ? '1' : '0') . "',
logs_enable = '" . ($_REQUEST['logs_enable'] ? '1' : '0') . "',
self_sql = '" . $_REQUEST['self_sql'] . "',
code_before = '" . $_REQUEST['code_before'] . "',
code_after = '" . $_REQUEST['code_after'] . "'
WHERE
id = '" . $work_id . "'
";
$sql = $AVE_DB->Query($sql);
}
$return = [
'success' => $sql ? true : false,
'work_id' => $work_id,
'message' => $sql ? $AVE_Template->get_config_vars('mod_edit_save_succes_t') : $AVE_Template->get_config_vars('mod_edit_save_error_t'),
'header' => $sql ? $AVE_Template->get_config_vars('mod_edit_save_succes_h') : $AVE_Template->get_config_vars('mod_edit_save_error_h'),
'theme' => $sql ? 'accept' : 'error',
];
if (isAjax())
{
self::_json($return, true);
}
else
{
$location = $work_id
? 'index.php?do=modules&action=modedit&mod=workdocs&moduleaction=1&cp=' . SESSION
: 'index.php?do=modules&action=modedit&mod=workdocs&moduleaction=1&cp=' . SESSION;
header('Location:' . $location);
exit;
}
}
public static function runWork ()
{
global $AVE_Template;
$work_id = (int)$_REQUEST['work_id'];
$work = self::_get_work($work_id);
$rubric_id = $work['rubric_id'];
$counts = self::_get_num_docs($rubric_id);
$diff = ($counts == $work['last_count']);
$AVE_Template->assign('work_id', $work_id);
$AVE_Template->assign('work', $work);
$AVE_Template->assign('diff', $diff);
$AVE_Template->assign('rubric_id', $rubric_id);
$AVE_Template->assign('count', $counts);
$AVE_Template->assign('content', $AVE_Template->fetch(self::$tpl_dir . 'run.tpl'));
}
public static function stepOne ()
{
global $AVE_DB, $AVE_Template;
Debug::startTime('step');
// Логи
$document_logs = [];
// Лимит
$limit = (isset($_REQUEST['limit']) ? (int)$_REQUEST['limit'] : 0);
// ID Работы
$work_id = (int)$_REQUEST['work_id'];
// Если не получено, то
if (! $work_id)
{
$return = ['success' => false];
self::_json($return, true);
}
// Получаем настройки
$work = self::_get_work($work_id);
// ID рубрики
$rubric_id = (int)$work['rubric_id'];
// Если первый документ, очищаем логи и ставим время обхода
if ($limit == 0)
self::_set_first_start($work_id);
// Свой SQL, код
if ($work['self_sql'])
eval (' ?>' . $work['self_sql'] . '<?'.'php ');
// SQL запрос, на получение ID документа
if (! isset($sql))
{
$sql = "
SELECT
Id
FROM
" . PREFIX . "_documents
WHERE
rubric_id = {$work['rubric_id']}
ORDER BY Id DESC
LIMIT {$limit}, 1;
";
}
// Получаем ID документа
if (! isset($document_id))
$document_id = $AVE_DB->Query($sql)->GetCell();
// Получаем данные документа, включая данные полей
$data = self::_get_document($document_id);
// Выполняем код перед сохранением документа
if ($work['code_before'] > '')
eval (' ?>' . $work['code_before'] . '<?'.'php ');
// Сохранение документа, если стоит галочка и есть данные
if ($work['save_enable'] == 1 && $data)
$save_id = self::_doc_save($document_id, $rubric_id, $data, (bool)$work['code_enable'], (bool)$work['revisions_enable'], (bool)$work['logs_enable']);
// Выполняем код после сохранением документа
if ($work['code_after'] > '')
eval (' ?>' . $work['code_after'] . '<?'.'php ');
// Сохраняем логи
self::_save_logs($work_id, $document_id, $data['document_title'], $rubric_id, $document_logs, $limit);
// Ответ
$return = [
'success' => true,
'time' => Debug::endTime('step'),
'limit' => $limit + 1,
'document_id' => $document_id,
'rubric_id' => $rubric_id,
'document_title' => $data['document_title'],
'document_alias' => $data['document_alias'],
'document_log' => implode('<br>', $document_logs)
];
self::_json($return, true);
}
public static function logWork ()
{
global $AVE_Template;
$work_id = (int)$_REQUEST['work_id'];
$AVE_Template->assign('work_id', $work_id);
$AVE_Template->assign('work', self::_get_work($work_id));
$AVE_Template->assign('content', $AVE_Template->fetch(self::$tpl_dir . 'log.tpl'));
}
public static function logJson ()
{
$work_id = (int)$_REQUEST['work_id'];
$output = self::_get_logs_json($work_id);
self::_json($output, true);
}
public static function delWork ()
{
global $AVE_DB;
$work_id = (int)$_REQUEST['work_id'];
$location = 'index.php?do=modules&action=modedit&mod=workdocs&moduleaction=1&cp=' . SESSION;
if (! $work_id)
{
header('Location:' . $location);
exit;
}
$sql = "
DELETE FROM
" . PREFIX . "_module_workdocs
WHERE
id = '{$work_id}'
";
$AVE_DB->Query($sql);
$sql = "
DELETE FROM
" . PREFIX . "_module_workdocs_logs
WHERE
work_id = '{$work_id}'
";
$AVE_DB->Query($sql);
header('Location:' . $location);
exit;
}
public static function clearWork ()
{
global $AVE_DB;
$work_id = (int)$_REQUEST['work_id'];
$sql = "
DELETE FROM
" . PREFIX . "_module_workdocs_logs
WHERE
work_id = '{$work_id}'
";
$AVE_DB->Query($sql);
$sql = "
UPDATE
" . PREFIX . "_module_workdocs
SET
last_run = '',
last_count = '0'
WHERE
id = '{$work_id}'
";
$AVE_DB->Query($sql);
$return = [
'success' => true
];
self::_json($return, true);
}
public static function clearWorks ()
{
global $AVE_DB;
$sql = "
TRUNCATE TABLE " . PREFIX . "_module_workdocs_logs
";
$AVE_DB->Query($sql);
$sql = "
UPDATE
" . PREFIX . "_module_workdocs
SET
last_run = '',
last_count = '0'
";
$AVE_DB->Query($sql);
$return = [
'success' => true
];
self::_json($return, true);
}
}

20
css/workdocs.css Normal file
View File

@@ -0,0 +1,20 @@
small {
font-size: 11px;
color: #687282;
}
tr.odd {
background-color: #fff;
}
tr.even {
background-color: #edf2f7;
}
tr.odd td.sorting_1 {
background-color: #E3EBF2;
}
tr.even td.sorting_1 {
background-color: #EDF2F7;
}

19
info.php Normal file
View File

@@ -0,0 +1,19 @@
<?php
if (! defined('BASE_DIR'))
exit;
$module = [
'ModuleSysName' => 'workdocs',
'ModuleVersion' => '1.0',
'ModuleAutor' => 'M@d D3n (support@ave-cms.ru)',
'ModuleCopyright' => '&copy; 2007-' . date('Y') . ' AVE.cms',
'ModuleIsFunction' => false,
'ModuleTemplate' => false,
'ModuleAdminEdit' => true,
'ModuleFunction' => 'mod_workdocs',
'ModuleTag' => null,
'ModuleTagLink' => null,
'ModuleAveTag' => null,
'ModulePHPTag' => null,
'ModuleFieldFile' => null
];

360
js/workdocs.js Normal file
View File

@@ -0,0 +1,360 @@
var ModuleWorkDocs = {
initialized: false,
init: function () {
if (this.initialized)
return;
this.initialized = true;
},
index: function () {
this.addWork();
this.deleteBtn();
this.clearLogs();
},
edit: function () {
this.saveBtn();
this.MouseTrap();
},
run: function () {
this.btnStart();
this.btnStartNew();
},
log: function () {
this.clearLog();
this.ajaxTable();
},
//
MouseTrap: function () {
Mousetrap.bind(['ctrl+s', 'command+s'], function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
ModuleWorkDocs.saveWork();
return false;
});
},
//
addWork: function () {
$('#addNewForm').on('submit', function (event) {
event.preventDefault(false);
let form = this,
select = $('#rubric_id').val();
if (! select.length)
{
$.jGrowl(error_mesage_rubric_id, {
header: error_header_rubric_id,
theme: 'error'
});
return false;
}
form.submit();
return true;
});
},
//
saveWork: function () {
let form = $("#saveForm");
form.ajaxSubmit({
url: form.attr('action'),
dataType: 'JSON',
beforeSubmit: function () {
$.alerts._overlay('show');
},
success: function (data) {
$.alerts._overlay('hide');
$.jGrowl(data['message'], {
header: data['header'],
theme: data['theme']
});
if (data.work_id) {
$('#work_id').val(data.work_id);
$('.hideBtn').show();
}
}
});
},
//
saveBtn: function () {
$('.SaveWork').on('click', function (event) {
event.preventDefault();
ModuleWorkDocs.saveWork();
});
},
//
deleteBtn: function () {
$('.Delete').on('click', function (event) {
event.preventDefault();
let href = $(this).attr('href');
jConfirm(
del_confirm,
del_title,
function (succes) {
if (succes) {
$.alerts._overlay('show');
window.location = href;
}
}
);
});
},
//
clearLogs: function () {
$('.clearLogs').on('click', function (event) {
event.preventDefault();
let href = $(this).attr('href');
jConfirm(
clear_confirm,
clear_title,
function (succes) {
if (succes) {
$.alerts._overlay('show');
$.ajax({
url: href,
type: 'POST',
dataType: "json",
success: function(data) {
$.alerts._overlay('hide');
$('.col-time').html('');
}
});
}
}
);
});
},
//
clearLog: function () {
$('.clearLog').on('click', function (event) {
event.preventDefault();
let href = $(this).attr('href');
jConfirm(
clear_confirm,
clear_title,
function (succes) {
if (succes) {
$.alerts._overlay('show');
$.ajax({
url: href,
type: 'POST',
dataType: "json",
success: function(data) {
$.alerts._overlay('hide');
logs.fnClearTable();
}
});
}
}
);
});
},
//
btnStart: function () {
$('.btnStart').on('click', function(event) {
event.preventDefault(false);
$('#showLog').hide();
ModuleWorkDocs.startWork();
});
},
//
btnStartNew: function () {
$('.btnStartNew').on('click', function(event) {
event.preventDefault();
$('#showLog').hide();
$('#blockRun').hide();
$('#btnBlockNew').hide();
$('#btnBlockWork').show();
$('#blockContinue').show();
ModuleWorkDocs.startWork(true);
});
},
//
addRow: function (document) {
let doc =
'<tr>' +
'<td>' +
'<a href="index.php?do=docs&action=edit&rubric_id=' + document.rubric_id + '&Id=' + document.document_id + '&cp=' + sess + '" target="_blank">' + document.document_id + '</a>' +
'</td>' +
'<td>' +
'<a href="' + ave_path + document.document_alias + '" target="_blank">' + document.document_title + '</a>' +
'</td>' +
'<td>' +
'<small>' +
document.document_log +
'</small>' +
'</td>' +
'</tr>';
logTable.append(doc);
},
//
startWork: function (startnew = false) {
let check = $('#stepBlock').data('run');
let href = (check === 'file')
? '/modules/workdocs/stepone.php?cp=' + sess
: 'index.php?do=modules&action=modedit&mod=workdocs&cp=' + sess;
$.ajax({
url: href,
data: ({
'moduleaction':'step',
'rubric_id': runData.data('rubric-id'),
'work_id': runData.data('work-id'),
'limit': startnew ? 0 : limitSql
}),
dataType: 'JSON',
beforeSend: function() {
$('.btnStart').prop('disabled', true);
},
complete: function() {
//
},
success: function(data) {
if (data.success)
{
if (startnew) {
logTable.find('tbody').html('');
limitSql = 0;
}
limitSql = limitSql + 1;
$('#noRecords').hide();
if (allRecords > limitSql) {
$('#delay').removeClass('yellow');
if (! $('#delay').hasClass('green'))
$('#delay').addClass('green');
$('#delay').html('Doc: ' + data.document_title);
var percent = ModuleWorkDocs.getPercent(limitSql, allRecords);
readyRecords.html(limitSql);
progressbar.progressbar({value: percent});
procents.html(percent + '%');
NProgress.set(percent/100);
if (logTable)
ModuleWorkDocs.addRow(data);
ModuleWorkDocs.startWork();
}
else {
progressbar.progressbar({value: 100});
$('procents').html('100%');
readyRecords.html(allRecords);
$('#showLog').show();
$('.btnStart').prop('disabled', false);
$('#btnBlockWork').hide();
$('#btnBlockNew').show();
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
$('.btnStart').prop('disabled', false);
}
});
},
//
getPercent: function (ready, count) {
return Math.round((ready / count) * 100);
},
//
ajaxTable: function () {
let logTable = $('#logsTable'),
work_id = logTable.data('work-id');
logs = logTable.dataTable({
"bJQueryUI": true,
'bAutoWidth': false,
'bProcessing': true,
'bServerSide': true,
'sPaginationType': "full_numbers",
'aaSorting': [[1,'asc']],
//"sDom": '<""f>rt<"F"lp>',
'iDisplayLength': 25,
'sAjaxSource': 'index.php?do=modules&action=modedit&mod=workdocs&moduleaction=json&work_id='+ work_id +'&cp=' + sess,
"oLanguage": {
"sLengthMenu": sLengthMenu,
"sZeroRecords": sZeroRecords,
"sInfo": sInfo,
"sInfoEmpty": sInfoEmpty,
"sInfoFiltered": sInfoFiltered
},
"stripeClasses": ['strip'],
"aoColumnDefs": [{
"sClass": "center",
"aTargets": [ 0,-2 ]
}]
});
}
};

105
lang/ru.txt Normal file
View File

@@ -0,0 +1,105 @@
[name]
MODULE_NAME = "Работа с документами"
MODULE_DESCRIPTION = "Массовый обход документов в пределах одной рубрики, и выполенеие действий над ними."
[admin]
mod_title = "Работа с документами"
mod_description = "Массовый обход документов в пределах одной рубрики, и выполенеие действий над ними."
mod_list_works = "Список действий"
mod_yes = "Да"
mod_no = "Нет"
mod_or = "Или"
mod_add_work = "Добавить новое действие"
mod_clear_all_logs = "Очистить все логи"
mod_main_table_th_id = "ID"
mod_main_table_th_name = "Наименование"
mod_main_table_th_desc = "Описание"
mod_main_table_th_run = "Последний запуск"
mod_main_table_th_rub = "Рубрика"
mod_main_table_th_actions = "Действия"
mod_main_table_th_rubdocs = "Рубрика с документами"
mod_main_table_th_selrub = "Выберите рубрику:"
mod_main_table_btn_edit = "Редактировать"
mod_main_table_btn_run = "Запустить"
mod_main_table_btn_logs = "Лог запуска"
mod_main_table_btn_settings = "Настройки"
mod_main_table_btn_del = "Удалить"
mod_main_table_btn_add = "Добавить"
mod_main_table_no_records = "Нет записей"
mess_del_confirm = "Вы уверены, что хотите удалить данную запись?"
mess_del_title = "Удалить запись"
mess_clear_confirm = "Вы уверены, что хотите удалить все логи?"
mess_clear_title = "Удалить все логи"
mess_error_mesage_rubric_id = "Пожалуйста выберите рубрику"
mess_error_header_rubric_id = "Ошибка"
mod_edit_breadcrumb = "Редактирование"
mod_edit_settings = "Настройки"
mod_edit_btn_run = "Запустить"
mod_edit_settings_work = "Настройки обхода документов"
mod_edit_settings_name = "Наименование"
mod_edit_settings_desc = "Описание"
mod_edit_settings_rub = "Рубрика с документами"
mod_edit_settings_rub_sel = "Выберите рубрику:"
mod_edit_settings_doc = "Настройки обхода документов"
mod_edit_settings_doc_1 = "Пересохранять документы при обходе"
mod_edit_settings_doc_2 = "При сохранении документа использовать Исполняемый код рубрики"
mod_edit_settings_doc_3 = "Сохранение ревизий документа"
mod_edit_settings_doc_4 = "Отображать действия в системных сообщениях"
mod_edit_code_header = "Исполняемый код, выполняемый при обходе документов"
mod_edit_code_header_b = "Код, выполняемый при обходе документов, <strong>ПЕРЕД</strong> сохранением"
mod_edit_code_header_a = "Код, выполняемый при обходе документов, <strong>ПОСЛЕ</strong> сохранения"
mod_edit_code_header_hint = "Доступ к данным:<br><strong>$work</strong> - Настройки данного задания<br><strong>$data</strong> - Все данные документа<br><strong>$data['feld']</strong> - Данные полей документа<br><strong>$rubric_id</strong> - ID рубрики<br><strong>$document_id</strong> - ID документа - Число<br><strong>$document_logs</strong> - Массив для регистрации события"
mod_edit_code_sql_h = "Свой SQL запрос выборки"
mod_edit_code_sql_hint = "SQL Запрос"
mod_edit_fields = "Список полей рубрики"
mod_edit_fields_table_id = "ID"
mod_edit_fields_table_name = "Наименование"
mod_edit_fields_table_alias = "Алис поля"
mod_edit_fields_table_type = "Тип поля"
mod_edit_fields_unknow = "Без названия"
mod_edit_rub_code_h = "Исполняемый код для рубрик (Только просмотр)"
mod_edit_rub_code_t1 = "Код, выполняемый <strong>ПЕРЕД</strong> сохранением документа"
mod_edit_rub_code_t2 = "Код, выполняемый <strong>ПОСЛЕ</strong> сохранения документа"
mod_edit_rub_code_hint1 = "Доступ к данным:<br><strong>$data</strong> - Все данные документа<br><strong>$data['feld']</strong> - Данные полей документа<br><strong>$rubric_id</strong> - ID рубрики"
mod_edit_rub_code_hint2 = "Доступ к данным:<br><strong>$data</strong> - Все данные документа<br><strong>$rubric_id</strong> - ID рубрики<br><strong>$document_id</strong> - ID документа - Число или False"
mod_edit_save_succes_h = "Выполнено"
mod_edit_save_succes_t = "Успешно сохранено"
mod_edit_save_error_h = "Ошибка"
mod_edit_save_error_t = "Ошибка при сохранении"
mod_run_breadcrumbs = "Выполнение"
mod_run_btn_repeat = "Запустить заново"
mod_run_btn_continue = "Продолжить работу"
mod_run_btn_start = "Запустить"
mod_run_header_progress = "Прогресс"
mod_run_header_btn_sett = "Настройки"
mod_run_header_search_docs = "Поиск документов"
mod_run_search_finded = "Найдено:"
mod_run_search_ready = "Обработано:"
mod_run_search_no_data = "Нет данных"
mod_run_btn_see_log = "Посмотреть журнал"
mod_run_tbl_log = "Проверенне документы"
mod_run_tbl_log_id = "ID"
mod_run_tbl_log_name = "Наименование документа"
mod_run_tbl_log_log = "Ошибки"
mod_run_tbl_log_log_no = "Нет записей"
mod_log_breadcrumbs = "Отчет о выполнении"
mod_log_btn_clear = "Очистить лог"
mod_log_btn_clear = "Очистить лог"
mod_log_tbl_docs = "Проверенне документы"
mod_log_tbl_docs_id = "ID"
mod_log_tbl_docs_name = "Наименование"
mod_log_tbl_docs_date = "Дата"
mod_log_tbl_docs_logs = "Отчет"
mod_log_clear_confirm = "Вы уверены, что хотите удалить логи?"
mod_log_clear_title = "Отчет"
mod_log_sLengthMenu = "Показать _MENU_ записей на странице"
mod_log_sZeroRecords = "Нечего показывать - извините"
mod_log_sInfo = "Показано с _START_ по _END_ из _TOTAL_ записей"
mod_log_sInfoEmpty = "Показано с 0 по 0 из 0 записей"
mod_log_sInfoFiltered = "(отфильтровано из _MAX_ общего кол-ва записей)"

94
module.php Normal file
View File

@@ -0,0 +1,94 @@
<?php
/**
* AVE.cms - Catalog PRO
*
* @package AVE.cms
* @subpackage modules/catalog
* @filesource
*/
if(! defined('BASE_DIR'))
exit;
//=======================================================
// The control module in the admin panel
//=======================================================
if (
defined('ACP')
&& (isset($_REQUEST['moduleaction']) && ! empty($_REQUEST['moduleaction']))
&& (isset($_REQUEST['mod']) && $_REQUEST['mod'] == 'workdocs')
)
{
global $AVE_DB, $AVE_Template;
require_once(BASE_DIR . '/modules/workdocs/class/class.php');
new WorkDocs;
WorkDocs::$tpl_dir = BASE_DIR . '/modules/workdocs/admin/';
$lang_file = BASE_DIR . '/modules/workdocs/lang/' . $_SESSION['admin_language'] . '.txt';
$AVE_Template->config_load($lang_file, 'admin');
//-- Actions
switch ($_REQUEST['moduleaction'])
{
// Заглавная страница
case '1':
WorkDocs::mainPage();
break;
//
case 'new':
WorkDocs::editWork();
break;
//
case 'edit':
WorkDocs::editWork();
break;
//
case 'save':
WorkDocs::saveWork();
break;
//
case 'del':
WorkDocs::delWork();
break;
//
case 'run':
WorkDocs::runWork();
break;
//
case 'log':
WorkDocs::logWork();
break;
//
case 'json':
WorkDocs::logJson();
break;
//
case 'step':
WorkDocs::stepOne();
break;
//
case 'clear':
WorkDocs::clearWork();
break;
//
case 'all':
WorkDocs::clearWorks();
break;
}
}

65
sql.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
/**
* AVE.cms - Fix Errors
*
* @package AVE.cms
* @subpackage modules/workdocs
* @filesource
*/
$module_sql_install = [];
$module_sql_deinstall = [];
$module_sql_update = [];
//-- Deinstall module ----------------------------------------------------------------------
$module_sql_deinstall[] = "DROP TABLE IF EXISTS %%PRFX%%_module_workdocs;";
$module_sql_deinstall[] = "DROP TABLE IF EXISTS %%PRFX%%_module_workdocs_logs;";
//-- Install module ------------------------------------------------------------------------
$module_sql_install[] = "CREATE TABLE IF NOT EXISTS `%%PRFX%%_module_workdocs` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` varchar(500) DEFAULT NULL,
`rubric_id` int(3) DEFAULT NULL,
`save_enable` enum('0','1') DEFAULT '0',
`code_enable` enum('0','1') DEFAULT '0',
`revisions_enable` enum('0','1') DEFAULT '0',
`logs_enable` enum('0','1') DEFAULT '0',
`type` enum('file','system') DEFAULT 'system',
`self_sql` text,
`code_before` longtext,
`code_after` longtext,
`last_run` int(11) unsigned NOT NULL,
`last_count` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
";
$module_sql_install[] = "CREATE TABLE IF NOT EXISTS `%%PRFX%%_module_workdocs_logs` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`work_id` int(3) DEFAULT NULL,
`rubric_id` int(3) DEFAULT NULL,
`document_id` int(11) DEFAULT NULL,
`document_title` varchar(255) DEFAULT NULL,
`last_run` int(11) DEFAULT NULL,
`logs` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
";
//-- Update module -------------------------------------------------------------------------
$module_sql_update[] = "
UPDATE
`%%PRFX%%_module`
SET
ModuleAveTag = '" . $module['ModuleAveTag'] . "',
ModulePHPTag = '" . $module['ModulePHPTag'] . "',
ModuleVersion = '" . $module['ModuleVersion'] . "'
WHERE
ModuleSysName = '" . $module['ModuleSysName'] . "'
LIMIT 1;
";

21
stepone.php Normal file
View File

@@ -0,0 +1,21 @@
<?php
define ('START_MICROTIME', microtime(true));
define ('START_MEMORY', memory_get_usage());
define ('BASE_DIR', str_replace("\\", "/", rtrim($_SERVER['DOCUMENT_ROOT'], '/')));
//-- Подключаем файл инициализации
require (BASE_DIR . '/inc/init.php');
//-- Подключаем файл инициализации
require (BASE_DIR . '/modules/workdocs/class/class.php');
new WorkDocs;
$AVE_Template = new AVE_Template(BASE_DIR . '/admin/templates');
$AVE_Template->assign('tpl_dir', ABS_PATH . 'admin/templates');
if (check_permission('alle') OR check_permission('mod_workdocs'))
WorkDocs::stepOne();
return false;
?>