Browse Source

Fixes

pull/3/head
M@d D3n 7 years ago
parent
commit
e510c55b7c
  1. 1
      .htaccess
  2. 8
      README.md
  3. 2
      admin/admin.php
  4. 2
      admin/dbsettings.php
  5. 25
      admin/functions/func.admin.common.php
  6. 4
      admin/index.php
  7. 33
      admin/rubs.php
  8. 35
      admin/start.php
  9. 2
      admin/templates/browser/browser_upload.tpl
  10. 6
      admin/templates/modules/modules.tpl
  11. 2
      admin/templates/rubs/_field_code.tpl
  12. 35
      admin/templates/rubs/fields_list.tpl
  13. 34
      class/class.blocks.php
  14. 141
      class/class.core.php
  15. 116
      class/class.database.php
  16. 18
      class/class.dbdump.php
  17. 167
      class/class.debug.php
  18. 34
      class/class.docs.php
  19. 15
      class/class.hooks.php
  20. 25
      class/class.logs.php
  21. 108
      class/class.modules.php
  22. 46
      class/class.navigation.php
  23. 68
      class/class.rubs.php
  24. 26
      class/class.session.files.php
  25. 2
      class/class.session.php
  26. 12
      class/class.settings.php
  27. 28
      class/class.sysblocks.php
  28. 19
      class/class.template.php
  29. 37
      class/class.templates.php
  30. 1
      config/.htaccess
  31. 0
      config/config.inc.php
  32. 0
      config/db.config.php
  33. 2
      fields/checkbox/field.php
  34. 2
      fields/date/field.php
  35. 2
      fields/doc_from_rub/field.php
  36. 2
      fields/doc_from_rub_check/field.php
  37. 2
      fields/drop_down/field.php
  38. 2
      fields/drop_down_key/field.php
  39. 11
      fields/image_mega/field.php
  40. 4
      fields/image_single/field.php
  41. 4
      fields/image_single/js/field.js
  42. 2
      fields/single_line/field.php
  43. 2
      functions/func.block.php
  44. 19
      functions/func.common.php
  45. 2
      functions/func.custom.php
  46. 13
      functions/func.hidden.php
  47. 2
      functions/func.locale.php
  48. 75
      functions/func.logs.php
  49. 2
      functions/func.mail.php
  50. 6
      functions/func.navigation.php
  51. 15
      functions/func.parserequest.php
  52. 2
      functions/func.sysblock.php
  53. 84
      inc/antispam.php
  54. 6
      inc/config.php
  55. 136
      inc/init.php
  56. 2
      inc/thumb.php
  57. 70
      index.php
  58. 26
      install/data_base.sql
  59. 219
      install/index.php
  60. 19
      install/structure_base.sql
  61. 48
      lib/debug/debug.css
  62. 30
      lib/debug/debug.js
  63. 1077
      lib/debug/sql.php
  64. 4
      lib/redactor/codemirror/addon/comment/comment.js
  65. 1
      lib/redactor/codemirror/addon/display/placeholder.js
  66. 26
      lib/redactor/codemirror/addon/edit/closebrackets.js
  67. 10
      lib/redactor/codemirror/addon/edit/closetag.js
  68. 45
      lib/redactor/codemirror/addon/edit/continuelist.js
  69. 13
      lib/redactor/codemirror/addon/edit/matchbrackets.js
  70. 2
      lib/redactor/codemirror/addon/fold/xml-fold.js
  71. 8
      lib/redactor/codemirror/addon/hint/javascript-hint.js
  72. 17
      lib/redactor/codemirror/addon/hint/show-hint.js
  73. 4
      lib/redactor/codemirror/addon/hint/sql-hint.js
  74. 106
      lib/redactor/codemirror/addon/lint/javascript-lint.js
  75. 6
      lib/redactor/codemirror/addon/lint/lint.js
  76. 6
      lib/redactor/codemirror/addon/merge/merge.css
  77. 5
      lib/redactor/codemirror/addon/merge/merge.js
  78. 10
      lib/redactor/codemirror/addon/mode/multiplex.js
  79. 2
      lib/redactor/codemirror/addon/search/match-highlighter.js
  80. 20
      lib/redactor/codemirror/addon/search/searchcursor.js
  81. 3
      lib/redactor/codemirror/addon/tern/tern.js
  82. 1
      lib/redactor/codemirror/codemirror_connect.tpl
  83. 3
      lib/redactor/codemirror/codemirror_editor.tpl
  84. 6
      lib/redactor/codemirror/lib/codemirror.css
  85. 84
      lib/redactor/codemirror/lib/codemirror.js
  86. 45
      lib/redactor/codemirror/mode/clike/clike.js
  87. 360
      lib/redactor/codemirror/mode/clike/index.html
  88. 767
      lib/redactor/codemirror/mode/clike/scala.html
  89. 59
      lib/redactor/codemirror/mode/clike/test.js
  90. 18
      lib/redactor/codemirror/mode/css/css.js
  91. 103
      lib/redactor/codemirror/mode/css/gss.html
  92. 17
      lib/redactor/codemirror/mode/css/gss_test.js
  93. 75
      lib/redactor/codemirror/mode/css/index.html
  94. 152
      lib/redactor/codemirror/mode/css/less.html
  95. 54
      lib/redactor/codemirror/mode/css/less_test.js
  96. 157
      lib/redactor/codemirror/mode/css/scss.html
  97. 110
      lib/redactor/codemirror/mode/css/scss_test.js
  98. 206
      lib/redactor/codemirror/mode/css/test.js
  99. 9
      lib/redactor/codemirror/mode/htmlembedded/htmlembedded.js
  100. 60
      lib/redactor/codemirror/mode/htmlembedded/index.html
  101. Some files were not shown because too many files have changed in this diff Show More

1
.htaccess

@ -319,6 +319,7 @@ AddDefaultCharset utf-8
# Файл sitemap.xml # Файл sitemap.xml
RewriteRule ^sitemap.xml$ inc/sitemap.php [QSA,L] RewriteRule ^sitemap.xml$ inc/sitemap.php [QSA,L]
RewriteRule ^sitemap-([0-9]+).xml$ inc/sitemap.php?id=$1 [QSA,L]
#--start-ave-editor--# #--start-ave-editor--#

8
README.md

@ -21,10 +21,8 @@
* ПО WEB сервера: * ПО WEB сервера:
* Apache >= 1.3 * Apache >= 1.3
* Nginx >= 1.6.2 * Nginx >= 1.6.2
* IIS >= 5 * PHP >= 5.6.x разрешить использовать короткие теги short_open_tag = On (zlib, cURL, mbString, JSON)
* PHP >= 5.5 * PHP >= 7.x ... <= 7.2.x
* PHP >= 5.5.x ... <= 5.6.x разрешить использовать короткие теги short_open_tag = On (zlib, cURL, mbString, JSON)
* PHP >= 7.x ... <= 7.1.x
## Модули ## Модули
@ -55,7 +53,7 @@
1. Распакуйте содержимое архива в новую папку на вашем локальном компьютере. 1. Распакуйте содержимое архива в новую папку на вашем локальном компьютере.
2. Загрузить эту папку целиком через FTP-клиент на ваш хост. 2. Загрузить эту папку целиком через FTP-клиент на ваш хост.
3. Вам также может потребоваться установить права доступа (CHMOD 777) рекурсивно, на папки /cache/, /session/ и /uploads/, если ваш хостинг не установливает это по умолчанию. 3. Вам также может потребоваться установить права доступа (CHMOD 777) рекурсивно, на папки /tmp/cache/, /tmp/session/ и /uploads/, если ваш хостинг не установливает это по умолчанию.
4. Также вам может потребоваться установить права доступа (CHMOD 777) рекурсивно, на файлы inc/db.config.php и inc/config.inc.php, если ваш хостинг не установливает это по умолчанию. 4. Также вам может потребоваться установить права доступа (CHMOD 777) рекурсивно, на файлы inc/db.config.php и inc/config.inc.php, если ваш хостинг не установливает это по умолчанию.
5. Наберите http://адрес вашего сайта/ в браузере. 5. Наберите http://адрес вашего сайта/ в браузере.
6. Следуйте инструкциям. 6. Следуйте инструкциям.

2
admin/admin.php

@ -15,7 +15,7 @@
define('ACPL', 1); define('ACPL', 1);
define('BASE_DIR', str_replace("\\", "/", dirname(dirname(__FILE__)))); define('BASE_DIR', str_replace("\\", "/", dirname(dirname(__FILE__))));
if (! @filesize(BASE_DIR . '/inc/db.config.php')) if (! @filesize(BASE_DIR . '/config/db.config.php'))
{ {
header('Location:/install/index.php'); header('Location:/install/index.php');
exit; exit;

2
admin/dbsettings.php

@ -46,7 +46,7 @@
exit; exit;
case 'restore': case 'restore':
$AVE_DB_Service->databaseDumpImport(BASE_DIR . "/" . ATTACH_DIR . "/"); $AVE_DB_Service->databaseDumpImport(BASE_DIR . "/tmp/" . ATTACH_DIR . "/");
break; break;
case 'download': case 'download':

25
admin/functions/func.admin.common.php

@ -48,22 +48,22 @@
$log404 = array(); $log404 = array();
$logsql = array(); $logsql = array();
$_404dir = BASE_DIR . '/cache/404.php'; $_404dir = BASE_DIR . '/tmp/logs/404.php';
$_logdir = BASE_DIR . '/cache/log.php'; $_logdir = BASE_DIR . '/tmp/logs/log.php';
$_sqldir = BASE_DIR . '/cache/sql.php'; $_sqldir = BASE_DIR . '/tmp/logs/sql.php';
if(file_exists($_logdir)) if (file_exists($_logdir))
@eval('?>' . file_get_contents($_logdir) . '<?'); @eval(' ?>' . file_get_contents($_logdir) . '<?php ');
$logs['logs'] = count($logdata); $logs['logs'] = count($logdata);
if(file_exists($_404dir)) if (file_exists($_404dir))
@eval('?>' . file_get_contents($_404dir) . '<?'); @eval(' ?>' . file_get_contents($_404dir) . '<?php ');
$logs['404'] = count($log404); $logs['404'] = count($log404);
if(file_exists($_sqldir)) if (file_exists($_sqldir))
@eval('?>' . file_get_contents($_sqldir) . '<?'); @eval(' ?>' . file_get_contents($_sqldir) . '<?php ');
$logs['sql'] = count($logsql); $logs['sql'] = count($logsql);
@ -81,7 +81,8 @@
* @param int $onlinetime количество секунд * @param int $onlinetime количество секунд
* @return Array массив из пользователей отсортированный по последней активности * @return Array массив из пользователей отсортированный по последней активности
*/ */
function get_online_users($onlinetime=USERS_TIME_SHOW){ function get_online_users($onlinetime=USERS_TIME_SHOW)
{
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$time=(time()-intval($onlinetime)); $time=(time()-intval($onlinetime));
$sql=@$AVE_DB->Query("SELECT * FROM ".PREFIX."_users WHERE last_visit>".$time." ORDER BY last_visit DESC"); $sql=@$AVE_DB->Query("SELECT * FROM ".PREFIX."_users WHERE last_visit>".$time." ORDER BY last_visit DESC");
@ -283,7 +284,7 @@
foreach ($modules AS $module) foreach ($modules AS $module)
{ {
if ($module['ModuleAdminEdit'] == 1 && $module['status']) if ($module['ModuleAdminEdit'] == 1 && $module['ModuleStatus'])
$modules_instaled[] = array( $modules_instaled[] = array(
'ModuleName' => $module['ModuleName'], 'ModuleName' => $module['ModuleName'],
'ModuleSysName' => $module['ModuleSysName'] 'ModuleSysName' => $module['ModuleSysName']
@ -503,7 +504,7 @@
$row->canDelete = 0; $row->canDelete = 0;
$row->canEndDel = 0; $row->canEndDel = 0;
$row->canOpenClose = 0; $row->canOpenClose = 0;
$row->rubric_admin_teaser_template=@eval2var('?>'.($row->rubric_admin_teaser_template>'' ? @showrequestelement($row,$row->rubric_admin_teaser_template) : '').'<?'); $row->rubric_admin_teaser_template=@eval2var(' ?>'.($row->rubric_admin_teaser_template>'' ? @showrequestelement($row,$row->rubric_admin_teaser_template) : '').'<?php ');
// разрешаем редактирование и удаление // разрешаем редактирование и удаление
// если автор имеет право изменять свои документы в рубрике // если автор имеет право изменять свои документы в рубрике

4
admin/index.php

@ -19,7 +19,7 @@
define('BASE_DIR', str_replace("\\", "/", dirname(dirname(__FILE__)))); define('BASE_DIR', str_replace("\\", "/", dirname(dirname(__FILE__))));
if (! @filesize(BASE_DIR . '/inc/db.config.php')) if (! @filesize(BASE_DIR . '/config/db.config.php'))
{ {
header('Location: ../install/index.php'); header('Location: ../install/index.php');
exit; exit;
@ -116,7 +116,7 @@
header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: no-store, no-cache, must-revalidate");
header("Expires: " . date("r")); header("Expires: " . date("r"));
include (BASE_DIR . '/admin/' . $do . '.php'); include_once (BASE_DIR . '/admin/' . $do . '.php');
if (defined('NOPERM')) if (defined('NOPERM'))
$AVE_Template->assign('content', $config_vars['MAIN_NO_PERMISSION']); $AVE_Template->assign('content', $config_vars['MAIN_NO_PERMISSION']);

33
admin/rubs.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -11,19 +11,19 @@
* @license GPL v.2 * @license GPL v.2
*/ */
if (!defined('ACP')) if (!defined('ACP'))
{ {
header('Location:index.php'); header('Location:index.php');
exit; exit;
} }
require(BASE_DIR . '/class/class.rubs.php'); require(BASE_DIR . '/class/class.rubs.php');
$AVE_Rubric = new AVE_Rubric; $AVE_Rubric = new AVE_Rubric;
$AVE_Template->config_load(BASE_DIR . '/admin/lang/' . $_SESSION['admin_language'] . '/rubs.txt', 'rubs'); $AVE_Template->config_load(BASE_DIR . '/admin/lang/' . $_SESSION['admin_language'] . '/rubs.txt', 'rubs');
switch($_REQUEST['action']) switch($_REQUEST['action'])
{ {
case '' : case '' :
if(check_permission('rubric_view')) if(check_permission('rubric_view'))
{ {
@ -630,6 +630,18 @@ switch($_REQUEST['action'])
} }
break; break;
case 'ftempledit':
if (check_permission('rubric_edit'))
{
$AVE_Rubric->EditFieldTpl('', $_REQUEST['fld'], $_REQUEST['type']);
}
else
{
$AVE_Template->assign('erorr', $AVE_Template->get_config_vars('RUBRIK_NO_PERMISSION'));
$AVE_Template->assign('content', $AVE_Template->fetch('error.tpl'));
}
break;
case 'ftsave': case 'ftsave':
if (check_permission('rubric_edit')) if (check_permission('rubric_edit'))
{ {
@ -654,6 +666,5 @@ switch($_REQUEST['action'])
$AVE_Template->assign('content', $AVE_Template->fetch('error.tpl')); $AVE_Template->assign('content', $AVE_Template->fetch('error.tpl'));
} }
break; break;
} }
?> ?>

35
admin/start.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -11,25 +11,24 @@
* @license GPL v.2 * @license GPL v.2
*/ */
if (!defined('ACP')) if (! defined('ACP'))
{ {
header('Location:index.php'); header('Location:index.php');
exit; exit;
} }
get_ave_info(); get_ave_info();
getInstaledModules(); getInstaledModules();
DisplayMainDocuments(); DisplayMainDocuments();
get_online_users(); get_online_users();
getLogRecords(); getLogRecords();
//$AVE_Template->config_load(BASE_DIR . '/admin/lang/' . $_SESSION['admin_language'] . '/main.txt', 'index');
$AVE_Template->assign('php_version', (@PHP_VERSION != '') ? @PHP_VERSION : 'unknow');
$AVE_Template->assign('domain', $_SERVER["HTTP_HOST"]);
$AVE_Template->assign('mysql_version', $GLOBALS['AVE_DB']->mysql_version());
$AVE_Template->assign('mysql_size', get_mysql_size());
$AVE_Template->assign('navi', $AVE_Template->fetch('navi/navi.tpl'));
$AVE_Template->assign('navi_top', $AVE_Template->fetch('navi/navi_top.tpl'));
$AVE_Template->assign('content', $AVE_Template->fetch('start.tpl'));
//$AVE_Template->config_load(BASE_DIR . '/admin/lang/' . $_SESSION['admin_language'] . '/main.txt', 'index');
$AVE_Template->assign('php_version', (@PHP_VERSION != '') ? @PHP_VERSION : 'unknow');
$AVE_Template->assign('domain', $_SERVER["HTTP_HOST"]);
$AVE_Template->assign('mysql_version', $GLOBALS['AVE_DB']->mysql_version());
$AVE_Template->assign('mysql_size', get_mysql_size());
$AVE_Template->assign('navi', $AVE_Template->fetch('navi/navi.tpl'));
$AVE_Template->assign('navi_top', $AVE_Template->fetch('navi/navi_top.tpl'));
$AVE_Template->assign('content', $AVE_Template->fetch('start.tpl'));
?> ?>

2
admin/templates/browser/browser_upload.tpl

@ -39,7 +39,7 @@ $(function() {
{title : "Image files", extensions : "jpg,jpeg,jpe,gif,png"}, {title : "Image files", extensions : "jpg,jpeg,jpe,gif,png"},
{title : "Video files", extensions : "mp4,avi,mov,wmv,wmf"}, {title : "Video files", extensions : "mp4,avi,mov,wmv,wmf"},
{title : "Music files", extensions : "mp3"}, {title : "Music files", extensions : "mp3"},
{title : "Documents", extensions : "doc,xls,pdf"}, {title : "Documents", extensions : "doc,docx,xls,xlsx,pdf"},
{title : "Zip files", extensions : "zip,rar"} {title : "Zip files", extensions : "zip,rar"}
], ],
// Flash settings // Flash settings

6
admin/templates/modules/modules.tpl

@ -88,7 +88,7 @@ $(document).ready(function(){ldelim}
<td nowrap="nowrap"> <td nowrap="nowrap">
{if check_permission('modules_admin')} {if check_permission('modules_admin')}
{if $module.ModuleAdminEdit && $module.status && $module.permission} {if $module.ModuleAdminEdit && $module.ModuleStatus && $module.permission}
<strong><a href="index.php?do=modules&action=modedit&mod={$module.ModuleSysName}&moduleaction=1&cp={$sess}" title="{#MODULES_SETUP#}" class="toprightDir link">{$module.ModuleName}</a></strong> <strong><a href="index.php?do=modules&action=modedit&mod={$module.ModuleSysName}&moduleaction=1&cp={$sess}" title="{#MODULES_SETUP#}" class="toprightDir link">{$module.ModuleName}</a></strong>
{if (isset($module.ModuleTagLink) && $module.ModuleTagLink != "")} {if (isset($module.ModuleTagLink) && $module.ModuleTagLink != "")}
<br /><span class="dgrey doclink">{$module.ModuleTagLink}</span> <br /><span class="dgrey doclink">{$module.ModuleTagLink}</span>
@ -104,7 +104,7 @@ $(document).ready(function(){ldelim}
<td> <td>
{if $module.template} {if $module.template}
{assign var=module_id value=$module.id} {assign var=module_id value=$module.id}
{if $module.status && $module.permission} {if $module.ModuleStatus && $module.permission}
{html_options name=Template[$module_id] options=$all_templates selected=$module.template style="width: 200px"} {html_options name=Template[$module_id] options=$all_templates selected=$module.template style="width: 200px"}
{else} {else}
{html_options name=Template[$module_id] options=$all_templates selected=$module.template style="width: 200px" disabled="disabled"} {html_options name=Template[$module_id] options=$all_templates selected=$module.template style="width: 200px" disabled="disabled"}
@ -120,7 +120,7 @@ $(document).ready(function(){ldelim}
{if check_permission('modules_system')} {if check_permission('modules_system')}
<td align="center" width="20"> <td align="center" width="20">
{if $module.status} {if $module.ModuleStatus}
<a title="{#MODULES_STOP#}" href="index.php?do=modules&action=onoff&module={$module.ModuleSysName}&cp={$sess}" class="topDir icon_sprite ico_stop"></a> <a title="{#MODULES_STOP#}" href="index.php?do=modules&action=onoff&module={$module.ModuleSysName}&cp={$sess}" class="topDir icon_sprite ico_stop"></a>
{else} {else}
<a title="{#MODULES_START#}" href="index.php?do=modules&action=onoff&module={$module.ModuleSysName}&cp={$sess}" class="topDir icon_sprite ico_start"></a> <a title="{#MODULES_START#}" href="index.php?do=modules&action=onoff&module={$module.ModuleSysName}&cp={$sess}" class="topDir icon_sprite ico_start"></a>

2
admin/templates/rubs/_field_code.tpl

@ -59,7 +59,7 @@
</form> </form>
{include file="$codemirror_editor" conn_id="ftpl" textarea_id='code_text' ctrls='$("#code_templ").ajaxSubmit(sett_options);' height=400} {include file="$codemirror_editor" conn_id="ftpl" textarea_id='code_text' ctrls='$("#code_templ").ajaxSubmit(sett_options);' height=400 mode='smartymixed'}
<script language="javascript"> <script language="javascript">
$(document).ready(function(){ldelim} $(document).ready(function(){ldelim}

35
admin/templates/rubs/fields_list.tpl

@ -221,51 +221,20 @@ function openAliasWindow(fieldId, rubId, width, height, target) {ldelim}
</div> </div>
</div> </div>
</form> </form>
{else} {else}
<form action="index.php?do=rubs&action=edit&Id={$smarty.request.Id|escape}&cp={$sess}" method="post" class="mainForm" id="Rubric"> <form action="index.php?do=rubs&action=edit&Id={$smarty.request.Id|escape}&cp={$sess}" method="post" class="mainForm" id="Rubric">
<div class="widget first"> <div class="widget first">
<div class="head"> <div class="head">
<h5 class="iFrames">{#RUBRIK_FIELDS_TITLE#}</h5> <h5 class="iFrames">{#RUBRIK_FIELDS_TITLE#}</h5>
<div class="num"> <div class="num">
<a class="basicNum" href="index.php?do=rubs&action=template&Id={$smarty.request.Id|escape}&cp={$sess}">{#RUBRIK_EDIT_TEMPLATE#}</a> <a class="basicNum greenNum" href="index.php?do=rubs&action=template&Id={$smarty.request.Id|escape}&cp={$sess}">{#RUBRIK_EDIT_TEMPLATE#}</a>
</div> </div>
</div> </div>
<div id="fields_list"> <div id="fields_list">
<table cellpadding="0" cellspacing="0" width="100%" class="tableStatic" id="FieldsList"> <table cellpadding="0" cellspacing="0" width="100%" class="tableStatic" id="FieldsList">
<col width="10">
<col width="10">
<col width="10">
<col width="10">
<col width="10">
<col width="100">
<col>
<col width="280">
<col width="280">
<col width="10">
<thead>
<tr>
<td align="center" title="{#RUBRIK_MARK_DEL_ALL#}" class="topDir">
<div align="center">
<input type="checkbox" id="selall" value="1" />
</div>
</td>
<td align="center"><a href="javascript:void(0);" class="topDir link" style="cursor: help;" title="{#RUBRIK_F_SORT_TIP#}">[?]</a></td>
<td align="center"><a href="javascript:void(0);" class="topDir link" style="cursor: help;" title="{#RUBRIK_NUMERIC_TIP#}">[?]</a></td>
<td align="center"><a href="javascript:void(0);" class="topDir link" style="cursor: help;" title="{#RUBRIK_SEARCH_TIP#}">[?]</a></td>
<td>{#RUBRIK_ID#}</td>
<td>{#RUBRIK_FIELD_ALIAS#}</td>
<td>{#RUBRIK_FIELD_NAME#}</td>
<td>{#RUBRIK_FIELD_TYPE#}</td>
<td>{#RUBRIK_FIELD_GROUP#}</td>
<td align="center"></td>
</tr>
</thead>
<tbody class="field_tbody"> <tbody class="field_tbody">
<tr> <tr>
<td align="center" colspan="10"> <td align="center">
<ul class="messages"> <ul class="messages">
<li class="highlight red">{#RUBRIK_NO_FIELDS#}</li> <li class="highlight red">{#RUBRIK_NO_FIELDS#}</li>
</ul> </ul>

34
class/class.blocks.php

@ -78,7 +78,9 @@
{ {
$_REQUEST['block_visual'] = (isset($_REQUEST['block_visual'])) ? $_REQUEST['block_visual'] : 0; $_REQUEST['block_visual'] = (isset($_REQUEST['block_visual'])) ? $_REQUEST['block_visual'] : 0;
$block_alias = isset($_REQUEST['block_alias']) ? $_REQUEST['block_alias'] : ''; $block_alias = isset($_REQUEST['block_alias'])
? $_REQUEST['block_alias']
: '';
$sql = $AVE_DB->Query(" $sql = $AVE_DB->Query("
UPDATE UPDATE
@ -105,11 +107,7 @@
$theme = 'accept'; $theme = 'accept';
//-- Стираем кеш блока //-- Стираем кеш блока
if (file_exists(BASE_DIR . '/cache/sql/block/' . $block_id . '.cache')) $this->clearCache($block_id, $block_alias);
unlink(BASE_DIR . '/cache/sql/block/' . $block_id . '.cache');
if ($block_alias != '' && file_exists(BASE_DIR . '/cache/sql/block/' . $block_alias . '.cache'))
unlink(BASE_DIR . '/cache/sql/block/' . $block_alias . '.cache');
//-- Сохраняем системное сообщение в журнал //-- Сохраняем системное сообщение в журнал
reportLog($AVE_Template->get_config_vars('BLOCK_SQLUPDATE') . " (" . stripslashes($_REQUEST['block_name']) . ") (id: $block_id)"); reportLog($AVE_Template->get_config_vars('BLOCK_SQLUPDATE') . " (" . stripslashes($_REQUEST['block_name']) . ") (id: $block_id)");
@ -249,12 +247,8 @@
id = '" . $block_id . "' id = '" . $block_id . "'
"); ");
//-- Стираем кеш сисблока //-- Стираем кеш блока
if (file_exists(BASE_DIR . '/cache/sql/block-' . $block_id . '.cache')) $this->clearCache($block_id, $row->block_alias);
unlink(BASE_DIR . '/cache/sql/block/' . $block_id . '.cache');
if ($row->block_alias != '')
unlink(BASE_DIR . '/cache/sql/block/' . $row->block_alias . '.cache');
//-- Сохраняем системное сообщение в журнал //-- Сохраняем системное сообщение в журнал
reportLog($AVE_Template->get_config_vars('BLOCK_SQLDEL') . " (" . stripslashes($row->block_name) . ") (id: $block_id)"); reportLog($AVE_Template->get_config_vars('BLOCK_SQLDEL') . " (" . stripslashes($row->block_name) . ") (id: $block_id)");
@ -262,5 +256,21 @@
header('Location:index.php?do=blocks&cp=' . SESSION); header('Location:index.php?do=blocks&cp=' . SESSION);
} }
function clearCache ($id, $alias = null)
{
$cache_id = md5('block' . $id);
$cache_alias = md5('block' . $alias);
$cache_id_file = BASE_DIR . '/tmp/cache/sql/block/' . $cache_id . '.cache';
$cache_alias_file = BASE_DIR . '/tmp/cache/sql/block/' . $cache_alias . '.cache';
if (file_exists($cache_id_file))
unlink($cache_id_file);
if (file_exists($cache_alias_file))
unlink($cache_alias_file);
}
} }
?> ?>

141
class/class.core.php

@ -100,13 +100,58 @@
} }
function _getMainTemplate($rubric_id, $template_id)
{
global $AVE_DB;
$return = null;
if (is_numeric($template_id))
{
$cache = 'template_' . $template_id;
$cache_file = BASE_DIR . '/tmp/cache/templates/' . $cache . '.inc';
// Если включен DEV MODE, то отключаем кеширование
if (defined('DEV_MODE') AND DEV_MODE)
$cache_file = null;
if (! file_exists(dirname($cache_file)))
mkdir(dirname($cache_file), 0766, true);
if (file_exists($cache_file))
{
$return = file_get_contents($cache_file);
}
else
{
$return = $AVE_DB->Query("
SELECT
template_text
FROM
" . PREFIX . "_templates
WHERE
Id = '" . $template_id . "'
LIMIT 1
")->GetCell();
$return = stripslashes($return);
if ($cache_file)
file_put_contents($cache_file, $return);
}
}
return $return;
}
/** /**
* Получение основных настроек сисблока * Получение основных настроек сисблока
* *
* @param string $param параметр настройки, если не указан - все параметры * @param string $param параметр настройки, если не указан - все параметры
* @return mixed * @return mixed
*/ */
function _requestGet($id, $param = '') function _requestGet($id, $param = '')
{ {
global $AVE_DB; global $AVE_DB;
@ -141,7 +186,7 @@
* @param string $fetched шаблон модуля * @param string $fetched шаблон модуля
* @return string * @return string
*/ */
function _coreDocumentTemplateGet($rubric_id = '', $template = '', $fetched = '') function _coreDocumentTemplateGet($rubric_id = null, $template = null, $fetched = null, $template_id = null)
{ {
global $AVE_DB; global $AVE_DB;
@ -200,18 +245,7 @@
} }
// Выполняем запрос к БД на получение основного шаблона, а также шаблона рубрики // Выполняем запрос к БД на получение основного шаблона, а также шаблона рубрики
$tpl = $AVE_DB->Query(" $tpl = $this->_getMainTemplate($rubric_id, $template_id);
SELECT
template_text
FROM
" . PREFIX . "_templates AS tpl
LEFT JOIN
" . PREFIX . "_rubrics AS rub
ON tpl.Id = rubric_template_id
WHERE
rub.Id = '" . $rubric_id . "'
LIMIT 1
")->GetCell();
// Если запрос выполнился с нулевым результатом, возвращаем пустую строку // Если запрос выполнился с нулевым результатом, возвращаем пустую строку
$out = $tpl $out = $tpl
@ -742,7 +776,7 @@
$cache_file = $this->_get_cache_hash(); $cache_file = $this->_get_cache_hash();
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/'); : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
@ -800,41 +834,53 @@
// Циклически обрабатываем каждый модуль // Циклически обрабатываем каждый модуль
foreach ($this->install_modules as $row) foreach ($this->install_modules as $row)
{ {
if ($row['ModuleStatus'] != 1)
continue;
// Если в запросе пришел вызов модуля или у модуля есть функция вызываемая тегом, // Если в запросе пришел вызов модуля или у модуля есть функция вызываемая тегом,
// который присутствует в шаблоне // который присутствует в шаблоне
if ((isset($_REQUEST['module']) && $_REQUEST['module'] == $row->ModuleSysName) || if (
(1 == $row->ModuleIsFunction && !empty($row->ModuleAveTag) && 1 == preg_match($row->ModuleAveTag, $template))) (isset($_REQUEST['module']) && $_REQUEST['module'] == $row['ModuleSysName'])
||
(
1 == $row['ModuleIsFunction']
&&
(isset($row['ModuleAveTag']) && !empty($row['ModuleAveTag']))
&&
1 == @preg_match($row['ModuleAveTag'], $template)
)
)
{ {
// Проверяем, существует ли для данного модуля функция. Если да, // Проверяем, существует ли для данного модуля функция. Если да,
// получаем php код функции. // получаем php код функции.
if (function_exists($row->ModuleStatus)) if (function_exists($row['ModuleFunction']))
{ {
$pattern[] = $row->ModuleAveTag; $pattern[] = $row['ModuleAveTag'];
$replace[] = $row->ModulePHPTag; $replace[] = $row['ModulePHPTag'];
} }
else // В противном случае else // В противном случае
{ {
// Проверяем, существует ли для данного модуля файл module.php в его персональной директории // Проверяем, существует ли для данного модуля файл module.php в его персональной директории
$mod_file = BASE_DIR . '/modules/' . $row->ModuleSysName . '/module.php'; $mod_file = BASE_DIR . '/modules/' . $row['ModuleSysName'] . '/module.php';
if (is_file($mod_file) && include_once($mod_file)) if (is_file($mod_file) && include_once($mod_file))
{ {
// Если файл модуля найден, тогда // Если файл модуля найден, тогда
if ($row->ModuleAveTag) if ($row['ModuleAveTag'])
{ {
$pattern[] = $row->ModuleAveTag; // Получаем его системный тег $pattern[] = $row['ModuleAveTag']; // Получаем его системный тег
// Проверяем, существует ли для данного модуля функция. Если да, // Проверяем, существует ли для данного модуля функция. Если да,
// получаем php код функции, в противном случае формируем сообщение с ошибкой // получаем php код функции, в противном случае формируем сообщение с ошибкой
$replace[] = function_exists($row->ModuleFunction) $replace[] = function_exists($row['ModuleFunction'])
? $row->ModulePHPTag ? $row['ModulePHPTag']
: ($this->_module_error . ' &quot;' . $row->ModuleName . '&quot;'); : ($this->_module_error . ' &quot;' . $row['ModuleName'] . '&quot;');
} }
} }
// Если файла module.php не существует, формируем сообщение с ошибкой // Если файла module.php не существует, формируем сообщение с ошибкой
elseif ($row->ModuleAveTag) elseif ($row['ModuleAveTag'])
{ $pattern[] = $row->ModuleAveTag; { $pattern[] = $row['ModuleAveTag'];
$replace[] = $this->_module_error . ' &quot;' . $row->ModuleName . '&quot;'; $replace[] = $this->_module_error . ' &quot;' . $row['ModuleName'] . '&quot;';
} }
} }
} }
@ -998,11 +1044,11 @@
// Выполняем Код рубрики До загрузки документа // Выполняем Код рубрики До загрузки документа
ob_start(); ob_start();
eval('?>' . $this->curentdoc->rubric_start_code . '<?'); eval(' ?>' . $this->curentdoc->rubric_start_code . '<?php ');
ob_end_clean(); ob_end_clean();
// Получаем шаблон // Получаем шаблон
$out = $this->_coreDocumentTemplateGet(RUB_ID); $out = $this->_coreDocumentTemplateGet(RUB_ID, null, null, $this->curentdoc->rubric_template_id);
if (! ((isset ($_SESSION[RUB_ID . '_docread']) && $_SESSION[RUB_ID . '_docread'] == 1) if (! ((isset ($_SESSION[RUB_ID . '_docread']) && $_SESSION[RUB_ID . '_docread'] == 1)
|| (isset ($_SESSION[RUB_ID . '_alles']) && $_SESSION[RUB_ID . '_alles'] == 1)) ) || (isset ($_SESSION[RUB_ID . '_alles']) && $_SESSION[RUB_ID . '_alles'] == 1)) )
@ -1084,7 +1130,7 @@
$cache_file = $this->_get_cache_hash(); $cache_file = $this->_get_cache_hash();
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/'); : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
@ -1245,7 +1291,7 @@
// проверяем установлен и активен ли модуль // проверяем установлен и активен ли модуль
if (isset($_REQUEST['module']) if (isset($_REQUEST['module'])
&& ! (isset($this->install_modules[$_REQUEST['module']]) && ! (isset($this->install_modules[$_REQUEST['module']])
&& '1' == $this->install_modules[$_REQUEST['module']]->ModuleStatus) ) && '1' == $this->install_modules[$_REQUEST['module']]['ModuleStatus']) )
{ {
// Выводим сообщение о том что такого модуля нет // Выводим сообщение о том что такого модуля нет
display_notice($this->_module_error); display_notice($this->_module_error);
@ -1596,26 +1642,27 @@
// Выполняем запрос к БД на получение всей необходимой // Выполняем запрос к БД на получение всей необходимой
// информации о документе // информации о документе
$document_id = (! empty($_REQUEST['id'])
? intval($_REQUEST['id'])
: 1);
// Забираем нужные данные // Забираем нужные данные
$sql = $AVE_DB->Query(" $sql = "
SELECT SELECT
doc.*, doc.*,
rubric_permission, rubric_permission,
rubric_template, rubric_template,
rubric_meta_gen, rubric_meta_gen,
rubric_template_id,
rub.rubric_header_template, rub.rubric_header_template,
rub.rubric_footer_template, rub.rubric_footer_template,
rub.rubric_start_code, rub.rubric_start_code,
template_text,
other.template other.template
FROM FROM
" . PREFIX . "_documents AS doc " . PREFIX . "_documents AS doc
JOIN JOIN
" . PREFIX . "_rubrics AS rub " . PREFIX . "_rubrics AS rub
ON rub.Id = doc.rubric_id ON rub.Id = doc.rubric_id
JOIN
" . PREFIX . "_templates AS tpl
ON tpl.Id = rubric_template_id
JOIN JOIN
" . PREFIX . "_rubric_permissions AS prm " . PREFIX . "_rubric_permissions AS prm
ON doc.rubric_id = prm.rubric_id ON doc.rubric_id = prm.rubric_id
@ -1625,15 +1672,19 @@
WHERE WHERE
user_group_id = '" . UGROUP . "' user_group_id = '" . UGROUP . "'
AND AND
" . (! empty ($get_url) " . (! empty ($get_url) && ! isset($_REQUEST['module'])
? "document_alias = '" . str_ireplace("'", "\'", $get_url) . "'" ? "document_alias = '" . str_ireplace("'", "\'", $get_url) . "'"
: (! empty($_REQUEST['id']) : (! empty($_REQUEST['id'])
? "doc.Id =" . intval($_REQUEST['id']) ? "doc.Id =" . intval($_REQUEST['id'])
: "doc.Id = 1")) . " : "doc.Id = 1")) . "
LIMIT 1 LIMIT 1
"); ";
$hash_url = md5($get_url);
$query = $AVE_DB->Query($sql, CACHE_DOC_SQL, 'url_' . $hash_url);
if ($this->curentdoc = $sql->FetchRow()) if ($this->curentdoc = $query->FetchRow())
{ {
if ($this->curentdoc->rubric_tmpl_id != 0) if ($this->curentdoc->rubric_tmpl_id != 0)
{ {
@ -1692,16 +1743,22 @@
$redirect_alias = $AVE_DB->Query($sql)->GetCell(); $redirect_alias = $AVE_DB->Query($sql)->GetCell();
$redirect_alias = ABS_PATH . $redirect_alias . URL_SUFF;
$redirect_alias = str_replace('//', '/', $redirect_alias);
if (! empty($redirect_alias)) if (! empty($redirect_alias))
{ {
header('HTTP/1.1 301 Moved Permanently'); header('HTTP/1.1 301 Moved Permanently');
header('Location:' . ABS_PATH . $redirect_alias . URL_SUFF); header('Location:' . $redirect_alias);
exit(); exit();
} }
if (! (! empty($_REQUEST['sysblock']) || ! empty($_REQUEST['module']) || ! empty($_REQUEST['request']))) if (! (! empty($_REQUEST['sysblock']) || ! empty($_REQUEST['module']) || ! empty($_REQUEST['request'])))
$_GET['id'] = $_REQUEST['id'] = PAGE_NOT_FOUND_ID; $_GET['id'] = $_REQUEST['id'] = PAGE_NOT_FOUND_ID;
} }
unset ($sql, $query);
} }
} }
?> ?>

116
class/class.database.php

@ -616,6 +616,12 @@
if (! is_array($this->_query_list)) if (! is_array($this->_query_list))
return false; return false;
$div = '';
include_once BASE_DIR . '/lib/debug/sql.php';
$SqlFormatter = new SqlFormatter();
foreach ($this->_query_list AS $k => $v) foreach ($this->_query_list AS $k => $v)
{ {
$_caller = ''; $_caller = '';
@ -633,15 +639,15 @@
$_ttl = $v['ttl'] > 0 ? $v['ttl'] : 'None'; $_ttl = $v['ttl'] > 0 ? $v['ttl'] : 'None';
if ($v['cache']) if (isset($v['cache']))
$_ttl .= PHP_EOL . $v['cache']; $_ttl .= PHP_EOL . $v['cache'];
$_query = $this->prepareQuery($v['query']); $_query = SqlFormatter::format($v['query']);
$div = ' $div .= '
<div style="border: 1px solid #aaa; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;">' . <div style="border: 1px solid #f0f0f0; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;">' .
'<div style="background:#aaa; color: #fff; margin: 0; padding: 5px;">' . '<div style="background:#aaa; color: #fff; margin: 0; padding: 5px;">' .
'<strong>' . $k . '</strong>' . '<strong>' . ($k+1) . '</strong>' .
'</div>' . '</div>' .
'<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' . '<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' .
'<strong>Trace:</strong>' . PHP_EOL . '<strong>Trace:</strong>' . PHP_EOL .
@ -656,9 +662,9 @@
'</pre>' . '</pre>' .
'</div> '</div>
'; ';
echo($div);
} }
return $div;
} }
/** /**
@ -702,7 +708,7 @@
foreach ((array)$stack as $call) foreach ((array)$stack as $call)
{ {
if (@$call['class'] == __CLASS__) if (isset($call['class']) && $call['class'] == __CLASS__)
continue; continue;
$function = $call['function']; $function = $call['function'];
@ -711,6 +717,7 @@
{ {
$function = $call['class'] . "->$function"; $function = $call['class'] . "->$function";
} }
$caller[] = $caller[] =
(array ( (array (
'call_file' => (isset($call['file']) ? $call['file'] : 'Unknown'), 'call_file' => (isset($call['file']) ? $call['file'] : 'Unknown'),
@ -760,6 +767,33 @@
} }
public function cacheFile($cache_id)
{
// Если это документ, то меняем расположение
if (substr($cache_id, 0, 3) == 'doc')
{
$cache_id = (int)str_replace('doc_', '', $cache_id);
$cache_id = 'doc/' . (floor($cache_id / 1000)) . '/' . $cache_id;
}
// Если это
if (substr($cache_id, 0, 3) == 'url')
{
$cache_id = str_replace('url_', '', $cache_id);
$cache_id = 'url/' . substr($cache_id, 0, 3);
}
// Если это
if (substr($cache_id, 0, 3) == 'nav')
{
$cache_id = str_replace('nav_', '', $cache_id);
$cache_id = 'nav/' . substr($cache_id, 0, 3);
}
return $cache_id;
}
/** /**
* Метод, предназначенный для выполнения запроса к MySQL и возвращение результата в виде асоциативного массива с поддержкой кеша * Метод, предназначенный для выполнения запроса к MySQL и возвращение результата в виде асоциативного массива с поддержкой кеша
* *
@ -771,12 +805,7 @@
*/ */
public function Query($query, $TTL = null, $cache_id = '', $log = true) public function Query($query, $TTL = null, $cache_id = '', $log = true)
{ {
// Если это документ, то меняем расположение $cache_id = $this->cacheFile($cache_id);
if (substr($cache_id, 0, 3) == 'doc')
{
$cache_id = (int)str_replace('doc_', '', $cache_id);
$cache_id = 'doc/' . (floor($cache_id / 1000)) . '/' . $cache_id;
}
// Принудительная фильтрация запроса // Принудительная фильтрация запроса
if (defined(SQL_QUERY_SANITIZE) && SQL_QUERY_SANITIZE) if (defined(SQL_QUERY_SANITIZE) && SQL_QUERY_SANITIZE)
@ -793,17 +822,16 @@
if (defined('DEV_MODE') AND DEV_MODE) if (defined('DEV_MODE') AND DEV_MODE)
$TTL = null; $TTL = null;
if ($TTL && ($TTL != 'nocache' AND $TTL != null)) if ($TTL && ($TTL != 'nocache' AND $TTL != null))
{ {
$cache_file = md5($query); $cache_file = md5($query);
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/'); : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
if (! file_exists($cache_dir)) if (! file_exists($cache_dir))
mkdir($cache_dir, 0777, true); mkdir($cache_dir, 0766, true);
// Если стоит в настройках, запоминать все запросы // Если стоит в настройках, запоминать все запросы
if (defined('SQL_PROFILING') && SQL_PROFILING) if (defined('SQL_PROFILING') && SQL_PROFILING)
@ -1005,7 +1033,7 @@
// Кол-во // Кол-во
$cache_file = md5($query) . '.count'; $cache_file = md5($query) . '.count';
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: substr($cache_file, 0, 2) . '/'. substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/'); : substr($cache_file, 0, 2) . '/'. substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
@ -1020,7 +1048,7 @@
} }
else else
{ {
$res = (int)$this->Query("SELECT FOUND_ROWS();")->GetCell(); $res = (int)$this->Query('SELECT FOUND_ROWS();')->GetCell();
file_put_contents($cache_dir . $cache_file, $res); file_put_contents($cache_dir . $cache_file, $res);
} }
@ -1033,7 +1061,7 @@
} }
} }
return (int)$this->Query("SELECT FOUND_ROWS();")->GetCell(); return (int)$this->Query('SELECT FOUND_ROWS();')->GetCell();
} }
@ -1294,7 +1322,45 @@
? 'doc/' . intval(floor((int)substr($cache_id, 4)) / 1000) . '/' . (int)substr($cache_id, 4) ? 'doc/' . intval(floor((int)substr($cache_id, 4)) / 1000) . '/' . (int)substr($cache_id, 4)
: $cache_id); : $cache_id);
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/'
: '');
return rrmdir($cache_dir);
}
/**
* Метод, предназначенный для очищения кеша документов
*
* @param $cache_id
* @return bool
*/
public function clearCacheUrl($cache_id)
{
$cache_id = str_replace('url_', '', $cache_id);
$cache_id = 'url/' . substr($cache_id, 0, 3);
$cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/'
: '');
return rrmdir($cache_dir);
}
/**
* Метод, предназначенный для очищения кеша документов
*
* @param $cache_id
* @return bool
*/
public function clearCacheNav($cache_id)
{
$cache_id = str_replace('nav_', '', $cache_id);
$cache_id = 'nav/' . substr($cache_id, 0, 3);
$cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: ''); : '');
@ -1314,7 +1380,7 @@
? 'request/' . (int)substr($cache_id, 4) ? 'request/' . (int)substr($cache_id, 4)
: $cache_id); : $cache_id);
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: ''); : '');
@ -1334,7 +1400,7 @@
? 'compiled/' . intval(floor((int)substr($cache_id, 4)) / 1000) . '/' . (int)substr($cache_id, 4) ? 'compiled/' . intval(floor((int)substr($cache_id, 4)) / 1000) . '/' . (int)substr($cache_id, 4)
: $cache_id); : $cache_id);
$cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' $cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/' ? trim($cache_id) . '/'
: ''); : '');
@ -1352,11 +1418,11 @@
{ {
$request = request_get_settings($cache_id); $request = request_get_settings($cache_id);
$cache_from_id = BASE_DIR . '/cache/sql/request/settings/' . (trim($request->Id) > '' $cache_from_id = BASE_DIR . '/tmp/cache/sql/request/settings/' . (trim($request->Id) > ''
? trim($request->Id) . '/' ? trim($request->Id) . '/'
: ''); : '');
$cache_from_alias = BASE_DIR . '/cache/sql/request/settings/' . (trim($request->request_alias) > '' $cache_from_alias = BASE_DIR . '/tmp/cache/sql/request/settings/' . (trim($request->request_alias) > ''
? trim($request->request_alias) . '/' ? trim($request->request_alias) . '/'
: ''); : '');

18
class/class.dbdump.php

@ -243,20 +243,20 @@
if (isset($_REQUEST['server']) && $_REQUEST['server'] == 1) if (isset($_REQUEST['server']) && $_REQUEST['server'] == 1)
{ {
if(! is_dir(BASE_DIR . '/backup/')) if (! is_dir(BASE_DIR . '/tmp/backup/'))
{ {
@mkdir(BASE_DIR . '/backup/', 0777); @mkdir(BASE_DIR . '/tmp/backup/', 0777, true);
write_htaccess_deny(BASE_DIR . '/backup/'); write_htaccess_deny(BASE_DIR . '/tmp/backup/');
} }
@file_put_contents(BASE_DIR . '/backup/'. $file_name . '.sql'. (defined('DB_EXPORT_GZ') && DB_EXPORT_GZ ? '.gz' : ''), $dump); @file_put_contents(BASE_DIR . '/tmp/backup/'. $file_name . '.sql'. (defined('DB_EXPORT_GZ') && DB_EXPORT_GZ ? '.gz' : ''), $dump);
@chmod(BASE_DIR . '/backup/'. $file_name . '.sql', 0777); @chmod(BASE_DIR . '/tmp/backup/'. $file_name . '.sql', 0777);
if (! $exit) if (! $exit)
header('Location:index.php?do=dbsettings&cp=' . SESSION); header('Location:index.php?do=dbsettings&cp=' . SESSION);
else else
return BASE_DIR . '/backup/'. $file_name . '.sql'. (defined('DB_EXPORT_GZ') && DB_EXPORT_GZ ? '.gz' : ''); return BASE_DIR . '/tmp/backup/'. $file_name . '.sql'. (defined('DB_EXPORT_GZ') && DB_EXPORT_GZ ? '.gz' : '');
} }
else else
{ {
@ -288,7 +288,7 @@
{ {
global $AVE_Template; global $AVE_Template;
$file = BASE_DIR . '/backup/'. $file; $file = BASE_DIR . '/tmp/backup/'. $file;
// Если дамп не удалось создать, тогда завершаем работу // Если дамп не удалось создать, тогда завершаем работу
if (! is_file($file)) if (! is_file($file))
@ -454,7 +454,7 @@
$insert = false; $insert = false;
$file = BASE_DIR . '/backup/'. $file; $file = BASE_DIR . '/tmp/backup/'. $file;
// Если дамп не удалось создать, тогда завершаем работу // Если дамп не удалось создать, тогда завершаем работу
if (! is_file($file)) $insert = false; if (! is_file($file)) $insert = false;
@ -611,7 +611,7 @@
*/ */
function databaseFilesGet() function databaseFilesGet()
{ {
$dir = BASE_DIR . '/backup/'; $dir = BASE_DIR . '/tmp/backup/';
if($handle = opendir($dir)) if($handle = opendir($dir))
{ {

167
class/class.debug.php

@ -539,5 +539,172 @@
return ''; return '';
} }
/**
* Вывод статистики
*/
public static function getStatistic ($type = null)
{
global $AVE_DB;
$stat = null;
switch ($type)
{
case 'time':
$stat = number_format(microtime_diff(START_MICROTIME, microtime()), 3, ',', ' ');
break;
case 'memory':
$stat = Debug::formatSize(memory_get_usage() - START_MEMORY);
break;
case 'peak':
$stat = Debug::formatSize(memory_get_peak_usage());
break;
case 'sqlcount':
$stat = $AVE_DB->DBProfilesGet('count');
break;
case 'sqltrace':
$stat = count($AVE_DB->_query_list);
break;
case 'sqltime':
$stat = $AVE_DB->DBProfilesGet('time');
break;
case 'get':
$stat = self::_stat_get('get');
break;
case 'post':
$stat = self::_stat_get('post');
break;
case 'request':
$stat = self::_stat_get('request');
break;
case 'session':
$stat = self::_stat_get('session');
break;
case 'server':
$stat = self::_stat_get('server');
break;
case 'globals':
$stat = self::_stat_get('globals');
break;
}
return $stat;
}
public static function _stat_get($type = 'get')
{
$var = '123123';
ob_start();
if ($type == 'get')
var_dump($_GET);
else if ($type == 'post')
var_dump($_POST);
else if ($type == 'request')
var_dump($_REQUEST);
else if ($type == 'session')
var_dump($_SESSION);
else if ($type == 'server')
var_dump($_SERVER);
else if ($type == 'globals')
var_dump($GLOBALS);
$stat = ob_get_contents();
$stat = preg_replace('/=>(\s+|\s$)/', ' => ', $stat);
$stat = htmlspecialchars($stat);
$stat = preg_replace('/(=&gt;)/', '<span style="color: #FF8C00;">$1</span>', $stat);
$stat = '<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">'. $stat .'</pre>';
ob_end_clean();
return $stat;
}
//
public static function displayInfo ()
{
global $AVE_DB;
$out = PHP_EOL;
$out .= '<link rel="stylesheet" href="/lib/debug/debug.css" />';
$out .= PHP_EOL;
$out .= '<script src="/lib/debug/debug.js"></script>';
$out .= PHP_EOL;
$out .= '
<div id="debug-panel">
<div class="debug-wrapper">
<div id="debug-panel-legend" class="legend">
<span>Debug console</span>
<a id="debugArrowMinimize" class="debugArrow" href="javascript:void(0)" title="Minimize" onclick="javascript:appTabsHide()">&times;</a>
<span>
<a id="tabGeneral" href="javascript:void(\'General\')" onclick="javascript:appExpandTabs(\'auto\', \'General\')">General</a>
<a id="tabParams" href="javascript:void(\'Params\')" onclick="javascript:appExpandTabs(\'auto\', \'Params\')">Params</a>
<a id="tabGlobals" href="javascript:void(\'Globals\')" onclick="javascript:appExpandTabs(\'auto\', \'Globals\')">Globals</a>
<a id="tabQueries" href="javascript:void(\'Queries\')" onclick="javascript:appExpandTabs(\'auto\', \'Queries\')">SQL Queries (' . self::getStatistic('sqlcount') . ')</a>
<a id="tabSqlTrace" href="javascript:void(\'SqlTrace\')" onclick="javascript:appExpandTabs(\'auto\', \'SqlTrace\')">SQL Trace (' . self::getStatistic('sqltrace') . ')</a>
</span>
</div>
';
$out .= PHP_EOL;
$out .= '<div id="contentGeneral" class="items" style="display: none">' . PHP_EOL;
$out .= 'Time generation: ' . self::getStatistic('time') . ' sec';
$out .= '<br>';
$out .= 'Memory usage: ' . self::getStatistic('memory');
$out .= '<br>';
$out .= 'Memory peak usage: ' . self::getStatistic('peak');
$out .= '<br>';
$out .= 'SQL Queries: ' . $AVE_DB->DBProfilesGet('count') . ' for ' . $AVE_DB->DBProfilesGet('time') . ' sec';
$out .= '</div>';
$out .= PHP_EOL;
$out .= '<div id="contentParams" class="items" style="display: none">' . PHP_EOL;
$out .= 'GET:';
$out .= self::getStatistic('get');
$out .= '<br>';
$out .= 'POST:';
$out .= self::getStatistic('post');
$out .= '<br>';
$out .= 'REQUEST:';
$out .= self::getStatistic('request');
$out .= '<br>';
$out .= 'SESSION:';
$out .= self::getStatistic('session');
$out .= '<br>';
$out .= 'SERVER:';
$out .= self::getStatistic('server');
$out .= '</div>';
$out .= PHP_EOL;
$out .= '<div id="contentGlobals" class="items" style="display: none">' . PHP_EOL;
$out .= self::getStatistic('globals');
$out .= '</div>';
$out .= PHP_EOL;
$out .= '<div id="contentQueries" class="items" style="display: none">' . PHP_EOL;
$out .= $AVE_DB->DBProfilesGet('list');
$out .= '</div>';
$out .= PHP_EOL;
$out .= '<div id="contentSqlTrace" class="items" style="display: none">' . PHP_EOL;
$out .= $AVE_DB->showAllQueries();
$out .= '</div>';
$out .= PHP_EOL;
$out .= '</div>';
echo $out;
}
} }
?> ?>

34
class/class.docs.php

@ -322,7 +322,7 @@ class AVE_Document
$sql_where_field = ''; $sql_where_field = '';
$field_link = ''; $field_link = '';
if ($_REQUEST['field_id'] && (int)$_REQUEST['field_id'] > 0) if (isset($_REQUEST['field_id']) && (int)$_REQUEST['field_id'] > 0)
{ {
$sql_join_field = " $sql_join_field = "
LEFT JOIN LEFT JOIN
@ -415,6 +415,8 @@ class AVE_Document
$nav_lang = '&lang_id=' . $_REQUEST['lang_id']; $nav_lang = '&lang_id=' . $_REQUEST['lang_id'];
} }
else
$nav_lang = '';
// Поиск с выводом всех результатов из всех рубрик // Поиск с выводом всех результатов из всех рубрик
if (@$_REQUEST['rubric_id'] == 'all') if (@$_REQUEST['rubric_id'] == 'all')
@ -699,9 +701,9 @@ class AVE_Document
$row->canDelete = 0; $row->canDelete = 0;
$row->canEndDel = 0; $row->canEndDel = 0;
$row->canOpenClose = 0; $row->canOpenClose = 0;
$row->rubric_admin_teaser_template = @eval2var('?>'.($row->rubric_admin_teaser_template>'' $row->rubric_admin_teaser_template = @eval2var(' ?>'.($row->rubric_admin_teaser_template>''
? @showrequestelement($row, $row->rubric_admin_teaser_template) ? @showrequestelement($row, $row->rubric_admin_teaser_template)
: '').'<?'); : '').'<?php ');
$row->document_title = stripslashes(htmlspecialchars_decode($row->document_title)); $row->document_title = stripslashes(htmlspecialchars_decode($row->document_title));
$row->document_breadcrum_title = stripslashes(htmlspecialchars_decode($row->document_breadcrum_title)); $row->document_breadcrum_title = stripslashes(htmlspecialchars_decode($row->document_breadcrum_title));
@ -915,7 +917,7 @@ class AVE_Document
{ {
$key = trim(mb_substr($v, 0, 254)); $key = trim(mb_substr($v, 0, 254));
$res= $AVE_DB->Query("INSERT INTO ".PREFIX."_document_keywords $res = $AVE_DB->Query("INSERT INTO ".PREFIX."_document_keywords
( (
document_id, document_id,
keyword keyword
@ -1511,7 +1513,7 @@ class AVE_Document
} }
} }
unset($sql, $query); unset ($sql, $query);
$where = ($oper == 'UPDATE' ? 'WHERE Id = ' . $document_id : ''); $where = ($oper == 'UPDATE' ? 'WHERE Id = ' . $document_id : '');
$author = ($oper != 'UPDATE' ? 'document_author_id = ' . $_SESSION['user_id'] . ',' : ''); $author = ($oper != 'UPDATE' ? 'document_author_id = ' . $_SESSION['user_id'] . ',' : '');
@ -1521,6 +1523,10 @@ class AVE_Document
? $data['document_breadcrum_title'] ? $data['document_breadcrum_title']
: ''; : '';
$document_tags = isset($data['document_tags'])
? $data['document_tags']
: '';
// Сохраняем все параметры документа // Сохраняем все параметры документа
$sql = " $sql = "
$operator $operator
@ -1531,7 +1537,7 @@ class AVE_Document
document_title = '" . htmlspecialchars(clean_no_print_char($data['document_title']), ENT_QUOTES) . "', document_title = '" . htmlspecialchars(clean_no_print_char($data['document_title']), ENT_QUOTES) . "',
document_breadcrum_title = '" . htmlspecialchars(clean_no_print_char($breadcrumb_title), ENT_QUOTES) . "', document_breadcrum_title = '" . htmlspecialchars(clean_no_print_char($breadcrumb_title), ENT_QUOTES) . "',
document_alias = '" . $data['document_alias'] . "', document_alias = '" . $data['document_alias'] . "',
document_alias_history = '" . $data['document_alias_log'] . "', document_alias_history = '" . $data['document_alias_history'] . "',
document_published = '" . $data["document_published"] . "', document_published = '" . $data["document_published"] . "',
document_expire = '" . $data["document_expire"] . "', document_expire = '" . $data["document_expire"] . "',
document_changed = '" . $data["document_changed"] . "', document_changed = '" . $data["document_changed"] . "',
@ -1544,7 +1550,7 @@ class AVE_Document
document_sitemap_pr = '" . $data['document_sitemap_pr'] . "', document_sitemap_pr = '" . $data['document_sitemap_pr'] . "',
document_status = '" . $data['document_status'] . "', document_status = '" . $data['document_status'] . "',
document_linked_navi_id = '" . (int)$data['document_linked_navi_id'] . "', document_linked_navi_id = '" . (int)$data['document_linked_navi_id'] . "',
document_tags = '" . addslashes(htmlspecialchars(clean_no_print_char($data['document_tags']))). "', document_tags = '" . addslashes(htmlspecialchars(clean_no_print_char($document_tags))). "',
document_lang = '" . (empty($data['document_lang']) ? DEFAULT_LANGUAGE : $data['document_lang']). "', document_lang = '" . (empty($data['document_lang']) ? DEFAULT_LANGUAGE : $data['document_lang']). "',
document_lang_group = '" . (empty($data['document_lang_group']) ? '0' : (int)$data['document_lang_group']). "', document_lang_group = '" . (empty($data['document_lang_group']) ? '0' : (int)$data['document_lang_group']). "',
document_property = '" . (empty($data['document_property']) ? '' : $data['document_property']). "' document_property = '" . (empty($data['document_property']) ? '' : $data['document_property']). "'
@ -1757,17 +1763,27 @@ class AVE_Document
doc_id = '" . $document_id . "' doc_id = '" . $document_id . "'
"); ");
$field_module = isset($data['field_module'])
? $data['field_module']
: '';
// Запускаем триггер после сохранения // Запускаем триггер после сохранения
Hooks::trigger('DocumentAfterSave', array('rubric_id' => $rubric_id, 'document_id' => $document_id, 'data' => $data, 'field_module' => $data['field_module'])); Hooks::trigger('DocumentAfterSave', array('rubric_id' => $rubric_id, 'document_id' => $document_id, 'data' => $data, 'field_module' => $field_module));
// Выполняем код рубрики, после сохранения // Выполняем код рубрики, после сохранения
if ($rubric_code) if ($rubric_code)
eval ('?>' . $_rubric->rubric_code_end . '<?'); eval (' ?>' . $_rubric->rubric_code_end . '<?php ');
if ($document_id == 1)
$hash_url = md5('');
else
$hash_url = md5($data['document_alias']);
// Чистим кеш // Чистим кеш
$AVE_DB->clearcache('rub_' . $rubric_id); $AVE_DB->clearcache('rub_' . $rubric_id);
$AVE_DB->clearcache('doc_' . $document_id); $AVE_DB->clearcache('doc_' . $document_id);
$AVE_DB->clearcompile('doc_' . $document_id); $AVE_DB->clearcompile('doc_' . $document_id);
$AVE_DB->clearCacheUrl('url_' . $hash_url);
$AVE_DB->clearcacherequest('doc_' . $document_id); $AVE_DB->clearcacherequest('doc_' . $document_id);
unset ($_rubric, $fields); unset ($_rubric, $fields);

15
class/class.hooks.php

@ -1,10 +1,10 @@
<?php <?php
// Проверка // Проверка
if (! defined('BASE_DIR')) if (! defined('BASE_DIR'))
exit('Access denied'); exit('Access denied');
/** /**
* This source file is part of the AVE.cms. More information, * This source file is part of the AVE.cms. More information,
* documentation and tutorials can be found at http://www.ave-cms.ru * documentation and tutorials can be found at http://www.ave-cms.ru
* *
@ -16,10 +16,10 @@ if (! defined('BASE_DIR'))
* @version 4.0 * @version 4.0
* @since $date$ * @since $date$
* @license license GPL v.2 http://www.ave-cms.ru/license.txt * @license license GPL v.2 http://www.ave-cms.ru/license.txt
*/ */
class Hooks class Hooks
{ {
public static $instance; public static $instance;
public static $hooks; public static $hooks;
@ -171,4 +171,5 @@ class Hooks
return false; return false;
} }
} }
} }
?>

25
class/class.logs.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* Класс, предназначенный для управления журналом системных сообщений * Класс, предназначенный для управления журналом системных сообщений
@ -12,10 +12,10 @@
* *
*/ */
class AVE_Logs class AVE_Logs
{ {
/** /**
* Свойства класса * Свойства класса
*/ */
@ -24,16 +24,16 @@ class AVE_Logs
* *
* @public * @public
*/ */
public $_404dir = '/cache/404.php'; public $_404dir = '/tmp/logs/404.php';
public $_logdir = '/cache/log.php'; public $_logdir = '/tmp/logs/log.php';
public $_sqldir = '/cache/sql.php'; public $_sqldir = '/tmp/logs/sql.php';
/** /**
* Внутренние методы класса * Внутренние методы класса
*/ */
/** /**
* Внешние методы класса * Внешние методы класса
*/ */
@ -50,7 +50,7 @@ class AVE_Logs
$logfile = BASE_DIR.$this->_logdir; $logfile = BASE_DIR.$this->_logdir;
if(file_exists($logfile)) if(file_exists($logfile))
@eval('?>'.file_get_contents($logfile).'<?'); @eval(' ?>'.file_get_contents($logfile).'<?php ');
arsort($logdata); arsort($logdata);
@ -183,7 +183,7 @@ class AVE_Logs
$logdata=array(); $logdata=array();
$logfile = BASE_DIR.$this->_logdir; $logfile = BASE_DIR.$this->_logdir;
if(file_exists($logfile)) if(file_exists($logfile))
@eval('?>'.file_get_contents($logfile).'<?'); @eval(' ?>'.file_get_contents($logfile).'<?php ');
arsort($logdata); arsort($logdata);
$fieldcount = count($logdata[0]); $fieldcount = count($logdata[0]);
@ -345,6 +345,5 @@ class AVE_Logs
exit; exit;
} }
} }
?> ?>

108
class/class.modules.php

@ -63,9 +63,9 @@
$module = array(); $module = array();
// Если не удалось подключить основной файл модуля module.php - Фиксируем ошибку
if (! (is_file($module_dir . '/info.php') && @include_once($module_dir . '/info.php'))) if (! (is_file($module_dir . '/info.php') && @include_once($module_dir . '/info.php')))
{ {
// Если не удалось подключить основной файл модуля module.php - Фиксируем ошибку
$modules['errors'][] = $entry; $modules['errors'][] = $entry;
continue; continue;
} }
@ -89,18 +89,20 @@
// установленные модули // установленные модули
if ($row) if ($row)
{ {
$module['status'] = $row->ModuleStatus;
$module['id'] = $row->Id; $module['id'] = $row->Id;
$module['need_update'] = ($row->ModuleVersion != $module['ModuleVersion']); $module['need_update'] = ($row->ModuleVersion != $module['ModuleVersion']);
$module['template'] = ($row->ModuleTemplate ? $row->ModuleTemplate : 0); $module['template'] = ($row->ModuleTemplate ? $row->ModuleTemplate : 0);
$module['ModuleAveTag'] = $row->ModuleAveTag;
$module['ModulePHPTag'] = $row->ModulePHPTag;
$module['ModuleStatus'] = $row->ModuleStatus;
$module['ModuleVersion'] = $row->ModuleVersion; $module['ModuleVersion'] = $row->ModuleVersion;
} }
// неустановленные модули // неустановленные модули
else else
{ {
$module['status'] = false;
$module['id'] = $module['ModuleSysName']; $module['id'] = $module['ModuleSysName'];
$module['template'] = (! empty($module['ModuleTemplate']) ? $module['ModuleTemplate'] : ''); $module['template'] = (! empty($module['ModuleTemplate']) ? $module['ModuleTemplate'] : '');
$module['ModuleStatus'] = false;
} }
// записываем в массив // записываем в массив
@ -151,7 +153,7 @@
? '<br /><br />' ? '<br /><br />'
: "<br /><br /><strong>$author_title</strong><br />" . $module['ModuleAutor'] . "<br />") . '<br /><em>' . $module['ModuleCopyright'] . '</em>'; : "<br /><br /><strong>$author_title</strong><br />" . $module['ModuleAutor'] . "<br />") . '<br /><em>' . $module['ModuleCopyright'] . '</em>';
// установленные модули // установленные модули
if ($module['status'] !== false) if ($module['ModuleStatus'] !== false)
$installed_modules[$module['ModuleSysName']] = $module; $installed_modules[$module['ModuleSysName']] = $module;
// неустановленные модули // неустановленные модули
else else
@ -203,7 +205,7 @@
{ {
foreach ($this->_modules AS $k => $v) foreach ($this->_modules AS $k => $v)
{ {
if ($status && $v['status'] != $status) if ($status && $v['ModuleStatus'] != $status)
continue; continue;
$modules[$k] = $v; $modules[$k] = $v;
@ -218,7 +220,7 @@
// Выполняем запрос к БД и получаем список документов, // Выполняем запрос к БД и получаем список документов,
// согласно статусу, либо все модули, если статус не указан // согласно статусу, либо все модули, если статус не указан
$sql = $AVE_DB->Query(" $sql = "
SELECT SELECT
* *
FROM FROM
@ -226,9 +228,11 @@
" . $where_status . " " . $where_status . "
ORDER BY ORDER BY
ModuleName ASC ModuleName ASC
"); ";
while ($row = $sql->FetchRow()) $query = $AVE_DB->Query($sql, SYSTEM_CACHE_LIFETIME, 'modules');
while ($row = $query->FetchRow())
$modules[$row->ModuleSysName] = $row; $modules[$row->ModuleSysName] = $row;
} }
@ -259,6 +263,8 @@
"); ");
} }
$this->clearModulesCache();
// Выполянем обновление страницы со списком модулей // Выполянем обновление страницы со списком модулей
header('Location:index.php?do=modules&cp=' . SESSION); header('Location:index.php?do=modules&cp=' . SESSION);
exit; exit;
@ -276,7 +282,7 @@
// Получаем данные модуля // Получаем данные модуля
$modules = $this->_modules; $modules = $this->_modules;
$modul = $modules[MODULE_PATH]; $module = $modules[MODULE_PATH];
// Удаляем информацию о модуле в таблице module // Удаляем информацию о модуле в таблице module
$AVE_DB->Query(" $AVE_DB->Query("
@ -288,13 +294,13 @@
"); ");
// Определяем, имеет ли модуль возможность настройки в Панели управления // Определяем, имеет ли модуль возможность настройки в Панели управления
$modul['ModuleAdminEdit'] = (!empty($modul['ModuleAdminEdit'])) $module['ModuleAdminEdit'] = (!empty($module['ModuleAdminEdit']))
? $modul['ModuleAdminEdit'] ? $module['ModuleAdminEdit']
: 0; : 0;
// Определяем, имеет ли модуль возможность смены шаблона // Определяем, имеет ли модуль возможность смены шаблона
$modul['ModuleTemplate'] = ($modul['ModuleTemplate']) $module['ModuleTemplate'] = ($module['ModuleTemplate'])
? $modul['ModuleTemplate'] ? $module['ModuleTemplate']
: 0; : 0;
// Добавляем информацию о модуле в таблицу module // Добавляем информацию о модуле в таблицу module
@ -302,16 +308,16 @@
INSERT INTO INSERT INTO
" . PREFIX . "_module " . PREFIX . "_module
SET SET
ModuleName = '" . $modul['ModuleName'] . "', ModuleName = '" . $module['ModuleName'] . "',
ModuleStatus = '1', ModuleStatus = '1',
ModuleAveTag = '" . $modul['ModuleAveTag'] . "', ModuleAveTag = '" . $module['ModuleAveTag'] . "',
ModulePHPTag = '" . $modul['ModulePHPTag'] . "', ModulePHPTag = '" . $module['ModulePHPTag'] . "',
ModuleFunction = '" . $modul['ModuleFunction'] . "', ModuleFunction = '" . $module['ModuleFunction'] . "',
ModuleIsFunction = '" . $modul['ModuleIsFunction'] . "', ModuleIsFunction = '" . $module['ModuleIsFunction'] . "',
ModuleSysName = '" . MODULE_PATH . "', ModuleSysName = '" . MODULE_PATH . "',
ModuleVersion = '" . $modul['ModuleVersion'] . "', ModuleVersion = '" . $module['ModuleVersion'] . "',
ModuleTemplate = '" . $modul['ModuleTemplate'] . "', ModuleTemplate = '" . $module['ModuleTemplate'] . "',
ModuleAdminEdit = '" . $modul['ModuleAdminEdit'] . "' ModuleAdminEdit = '" . $module['ModuleAdminEdit'] . "'
"); ");
// Подключаем файл с запросами к БД для данного модуля // Подключаем файл с запросами к БД для данного модуля
@ -325,20 +331,22 @@
// из массива $module_sql_deinstall файла sql.php // из массива $module_sql_deinstall файла sql.php
foreach ($module_sql_deinstall as $sql) foreach ($module_sql_deinstall as $sql)
{ {
$AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql)); $AVE_DB->Query(str_replace('%%PRFX%%', PREFIX, $sql));
} }
// Выполняем запросы создания таблиц и данных модуля // Выполняем запросы создания таблиц и данных модуля
// из массива $module_sql_install файла sql.php // из массива $module_sql_install файла sql.php
foreach ($module_sql_install as $sql) foreach ($module_sql_install as $sql)
{ {
$AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql)); $AVE_DB->Query(str_replace('%%PRFX%%', PREFIX, $sql));
} }
} }
// Сохраняем системное сообщение в журнал // Сохраняем системное сообщение в журнал
($_REQUEST['action'] == "reinstall") ($_REQUEST['action'] == "reinstall")
? reportLog($AVE_Template->get_config_vars('MODULES_ACTION_REINSTALL') . ' (' . $modul['ModuleName'] . ')') ? reportLog($AVE_Template->get_config_vars('MODULES_ACTION_REINSTALL') . ' (' . $module['ModuleName'] . ')')
: reportLog($AVE_Template->get_config_vars('MODULES_ACTION_INSTALL') . ' (' . $modul['ModuleName'] . ')'); : reportLog($AVE_Template->get_config_vars('MODULES_ACTION_INSTALL') . ' (' . $module['ModuleName'] . ')');
$this->clearModulesCache();
// Выполняем обновление страницы со списком модулей // Выполняем обновление страницы со списком модулей
header('Location:index.php?do=modules&cp=' . SESSION); header('Location:index.php?do=modules&cp=' . SESSION);
@ -359,38 +367,38 @@
$sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php'; $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
$mod_file = BASE_DIR . '/modules/' . MODULE_PATH . '/module.php'; $mod_file = BASE_DIR . '/modules/' . MODULE_PATH . '/info.php';
if (file_exists($mod_file) && file_exists($sql_file)) if (file_exists($mod_file) && file_exists($sql_file))
{ {
include($mod_file); include ($mod_file);
include($sql_file); include ($sql_file);
// Выполняем запросы обновления модуля // Выполняем запросы обновления модуля
// из массива $module_sql_update файла sql.php // из массива $module_sql_update файла sql.php
foreach ($module_sql_update as $sql) foreach ($module_sql_update as $sql)
{ {
$AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql)); $AVE_DB->Query(str_replace('%%PRFX%%', PREFIX, $sql));
} }
} }
// Обновляем модуль, если в нем не применяется (отсутствует) файл sql.php // Обновляем модуль, если в нем не применяется (отсутствует) файл sql.php
elseif (file_exists($mod_file) && file_exists($sql_file) === false) elseif (file_exists($mod_file) && file_exists($sql_file) === false)
{ {
include($mod_file); include_once ($mod_file);
$AVE_DB->Query(" $AVE_DB->Query("
UPDATE UPDATE
" . PREFIX . "_module " . PREFIX . "_module
SET SET
ModuleName = '" . $modul['ModuleName'] . "', ModuleAveTag = '" . $module['ModuleAveTag'] . "',
ModuleStatus = '1', ModulePHPTag = '" . $module['ModulePHPTag'] . "',
ModuleAveTag = '" . $modul['ModuleAveTag'] . "', ModuleFunction = '" . $module['ModuleFunction'] . "',
ModulePHPTag = '" . $modul['ModulePHPTag'] . "', ModuleIsFunction = '" . $module['ModuleIsFunction'] . "',
ModuleFunction = '" . $modul['ModuleFunction'] . "',
ModuleIsFunction = '" . $modul['ModuleIsFunction'] . "',
ModuleSysName = '" . MODULE_PATH . "', ModuleSysName = '" . MODULE_PATH . "',
ModuleVersion = '" . $modul['ModuleVersion'] . "', ModuleVersion = '" . $module['ModuleVersion'] . "',
ModuleTemplate = '" . $modul['ModuleTemplate'] . "', ModuleTemplate = '" . $module['ModuleTemplate'] . "',
ModuleAdminEdit = '" . $modul['ModuleAdminEdit'] . "' ModuleAdminEdit = '" . $module['ModuleAdminEdit'] . "',
ModuleStatus = '1'
WHERE WHERE
ModuleSysName = '" . MODULE_PATH . "' ModuleSysName = '" . MODULE_PATH . "'
"); ");
@ -398,6 +406,8 @@
// Сохраняем системное сообщение в журнал // Сохраняем системное сообщение в журнал
reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_UPDATE') . ' (' . MODULE_PATH . ')'); reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_UPDATE') . ' (' . MODULE_PATH . ')');
$this->clearModulesCache();
// Выполянем обновление страницы со списком модулей // Выполянем обновление страницы со списком модулей
header('Location:index.php?do=modules&cp=' . SESSION); header('Location:index.php?do=modules&cp=' . SESSION);
exit; exit;
@ -423,7 +433,7 @@
// из массива $module_sql_deinstall файла sql.php // из массива $module_sql_deinstall файла sql.php
foreach ($module_sql_deinstall as $sql) foreach ($module_sql_deinstall as $sql)
{ {
$AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql)); $AVE_DB->Query(str_replace('%%PRFX%%', PREFIX, $sql));
} }
} }
@ -436,6 +446,8 @@
ModuleSysName = '" . MODULE_PATH . "' ModuleSysName = '" . MODULE_PATH . "'
"); ");
$this->clearModulesCache();
// Сохраняем системное сообщение в журнал // Сохраняем системное сообщение в журнал
reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_DELETE') .' (' . MODULE_PATH . ')'); reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_DELETE') .' (' . MODULE_PATH . ')');
@ -477,6 +489,8 @@
ModuleSysName = '" . MODULE_PATH . "' ModuleSysName = '" . MODULE_PATH . "'
"); ");
$this->clearModulesCache();
// Сохраняем системное сообщение в журнал // Сохраняем системное сообщение в журнал
reportLog ((($ModuleStatus == "0") reportLog ((($ModuleStatus == "0")
? $AVE_Template->get_config_vars('MODULES_ACTION_OFFLINE') ? $AVE_Template->get_config_vars('MODULES_ACTION_OFFLINE')
@ -506,6 +520,8 @@
rrmdir ($directory); rrmdir ($directory);
$this->clearModulesCache();
// Сохраняем системное сообщение в журнал // Сохраняем системное сообщение в журнал
reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_REMOVE') . ' (' . $dir . ')'); reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_REMOVE') . ' (' . $dir . ')');
@ -513,5 +529,17 @@
header('Location:index.php?do=modules&cp=' . SESSION); header('Location:index.php?do=modules&cp=' . SESSION);
exit; exit;
} }
/**
* Функция очищает кеш системных настроек
*
*/
function clearModulesCache()
{
$cache_dir = BASE_DIR . '/tmp/cache/sql/modules/';
return rrmdir($cache_dir);
}
} }
?> ?>

46
class/class.navigation.php

@ -244,6 +244,7 @@
//-- Стираем кеш навигации //-- Стираем кеш навигации
$this->clearCache($navigation_id, $_REQUEST['alias']); $this->clearCache($navigation_id, $_REQUEST['alias']);
$this->clearCacheId($navigation_id, $_REQUEST['alias']); $this->clearCacheId($navigation_id, $_REQUEST['alias']);
$this->clearCacheNav($navigation_id, $_REQUEST['alias']);
if ($sql === false) if ($sql === false)
{ {
@ -400,6 +401,8 @@
" . PREFIX . "_navigation " . PREFIX . "_navigation
"); ");
$items = null;
//-- Циклически обрабатываем полученные данные //-- Циклически обрабатываем полученные данные
while ($navigation = $sql->FetchRow()) while ($navigation = $sql->FetchRow())
{ {
@ -1264,24 +1267,24 @@
function clearCache($id, $alias = '') function clearCache($id, $alias = '')
{ {
if (file_exists(BASE_DIR . '/cache/sql/nav/template-' . $id . '.cache')) if (file_exists(BASE_DIR . '/tmp/cache/sql/nav/template-' . $id . '.cache'))
unlink(BASE_DIR . '/cache/sql/nav/template-' . $id . '.cache'); unlink(BASE_DIR . '/tmp/cache/sql/nav/template-' . $id . '.cache');
if (file_exists(BASE_DIR . '/cache/sql/nav/template-' . $alias . '.cache')) if (file_exists(BASE_DIR . '/tmp/cache/sql/nav/template-' . $alias . '.cache'))
unlink(BASE_DIR . '/cache/sql/nav/template-' . $alias . '.cache'); unlink(BASE_DIR . '/tmp/cache/sql/nav/template-' . $alias . '.cache');
if (file_exists(BASE_DIR . '/cache/sql/nav/items-' . $id . '.cache')) if (file_exists(BASE_DIR . '/tmp/cache/sql/nav/items-' . $id . '.cache'))
unlink(BASE_DIR . '/cache/sql/nav/items-' . $id . '.cache'); unlink(BASE_DIR . '/tmp/cache/sql/nav/items-' . $id . '.cache');
if (file_exists(BASE_DIR . '/cache/sql/nav/items-' . $alias . '.cache')) if (file_exists(BASE_DIR . '/tmp/cache/sql/nav/items-' . $alias . '.cache'))
unlink(BASE_DIR . '/cache/sql/nav/items-' . $alias . '.cache'); unlink(BASE_DIR . '/tmp/cache/sql/nav/items-' . $alias . '.cache');
} }
function clearCacheId($id, $alias = '') function clearCacheId($id, $alias = '')
{ {
$dir_id = BASE_DIR . '/cache/sql/nav_' . $id; $dir_id = BASE_DIR . '/tmp/cache/sql/nav_' . $id;
$dir_alias = BASE_DIR . '/cache/sql/nav_' . $alias; $dir_alias = BASE_DIR . '/tmp/cache/sql/nav_' . $alias;
if (file_exists($dir_id)) if (file_exists($dir_id))
{ {
@ -1299,5 +1302,28 @@
} }
} }
} }
function clearCacheNav($id, $alias)
{
$cache_id = str_replace('nav_', '', $id);
$cache_id = 'nav/' . substr($cache_id, 0, 3);
$cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/'
: '');
rrmdir($cache_dir);
$cache_id = str_replace('nav_', '', $alias);
$cache_id = 'nav/' . substr($cache_id, 0, 3);
$cache_dir = BASE_DIR . '/tmp/cache/sql/' . (trim($cache_id) > ''
? trim($cache_id) . '/'
: '');
rrmdir($cache_dir);
}
} }
?> ?>

68
class/class.rubs.php

@ -869,17 +869,24 @@
$sql = $AVE_DB->Query(" $sql = $AVE_DB->Query("
SELECT SELECT
Id Id,
document_alias
FROM FROM
" . PREFIX . "_documents " . PREFIX . "_documents
WHERE WHERE
rubric_id = " . $rubric_id . " rubric_id = " . $rubric_id . "
"); ");
while ($row = $sql->GetCell()) while ($row = $sql->FetchRow())
{ {
$AVE_DB->clearcache('doc_' . $row); if ($row->Id == 1)
$AVE_DB->clearcompile('doc_' . $row); $hash_url = md5('');
else
$hash_url = md5($row->document_alias);
$AVE_DB->clearCacheUrl('url_'.$hash_url);
$AVE_DB->clearcache('doc_' . $row->Id);
$AVE_DB->clearcompile('doc_' . $row->Id);
} }
if ($sql->_result === false) if ($sql->_result === false)
@ -1003,10 +1010,16 @@
WHERE rub_id = '" . $rubric_id . "' WHERE rub_id = '" . $rubric_id . "'
"); ");
$sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id); $sql = $AVE_DB->Query("SELECT Id,document_alias FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
if ($row->Id == 1)
$hash_url = md5('');
else
$hash_url = md5($row->document_alias);
$AVE_DB->clearCacheUrl('url_'.$hash_url);
$AVE_DB->clearcache('doc_'.$row->Id); $AVE_DB->clearcache('doc_'.$row->Id);
$AVE_DB->clearcompile('doc_'.$row->Id); $AVE_DB->clearcompile('doc_'.$row->Id);
$AVE_DB->clearcacherequest('doc_'.$row->Id); $AVE_DB->clearcacherequest('doc_'.$row->Id);
@ -1044,10 +1057,16 @@
$AVE_DB->clearcache('rub_'.$rubric_id); $AVE_DB->clearcache('rub_'.$rubric_id);
$sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id); $sql = $AVE_DB->Query("SELECT Id,document_alias FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
if ($row->Id == 1)
$hash_url = md5('');
else
$hash_url = md5($row->document_alias);
$AVE_DB->clearCacheUrl('url_'.$hash_url);
$AVE_DB->clearcache('doc_'.$row->Id); $AVE_DB->clearcache('doc_'.$row->Id);
$AVE_DB->clearcompile('doc_'.$row->Id); $AVE_DB->clearcompile('doc_'.$row->Id);
} }
@ -1272,10 +1291,16 @@
reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_TEMPL_RUB') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')'); reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_TEMPL_RUB') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
} }
$sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id); $sql = $AVE_DB->Query("SELECT Id, document_alias FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
if ($row->Id == 1)
$hash_url = md5('');
else
$hash_url = md5($row->document_alias);
$AVE_DB->clearCacheUrl('url_'.$hash_url);
$AVE_DB->clearcache('doc_'.$row->Id); $AVE_DB->clearcache('doc_'.$row->Id);
$AVE_DB->clearcompile('doc_'.$row->Id); $AVE_DB->clearcompile('doc_'.$row->Id);
} }
@ -1532,7 +1557,9 @@
$AVE_Template->assign('content', $AVE_Template->fetch('rubs/field_template.tpl')); $AVE_Template->assign('content', $AVE_Template->fetch('rubs/field_template.tpl'));
} }
function rubricFieldTemplateSave($id, $rubric_id) {
function rubricFieldTemplateSave($id, $rubric_id)
{
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$sql = $AVE_DB->Query(" $sql = $AVE_DB->Query("
@ -1546,7 +1573,8 @@
Id = '" . $id . "' Id = '" . $id . "'
"); ");
if ($sql->_result === false) { if ($sql->_result === false)
{
$message = $AVE_Template->get_config_vars('RUBRIC_SAVED_FLDTPL_ERR'); $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_FLDTPL_ERR');
$header = $AVE_Template->get_config_vars('RUBRIK_ERROR'); $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
$theme = 'error'; $theme = 'error';
@ -1559,14 +1587,21 @@
exit; exit;
} }
}else{ }
else
{
$AVE_DB->clearcache('rub_'.$rubric_id); $AVE_DB->clearcache('rub_'.$rubric_id);
$sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents"); $sql = $AVE_DB->Query("SELECT Id, document_alias FROM " . PREFIX . "_documents WHERE rubric_id = '".$rubric_id."'");
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
if ($row->Id == 1)
$hash_url = md5('');
else
$hash_url = md5($row->document_alias);
$AVE_DB->clearCacheUrl('url_'.$hash_url);
$AVE_DB->clearcache('doc_'.$row->Id); $AVE_DB->clearcache('doc_'.$row->Id);
$AVE_DB->clearcompile('doc_'.$row->Id); $AVE_DB->clearcompile('doc_'.$row->Id);
$AVE_DB->clearcacherequest('doc_'.$row->Id); $AVE_DB->clearcacherequest('doc_'.$row->Id);
@ -2072,7 +2107,8 @@
$sql = $AVE_DB->Query(" $sql = $AVE_DB->Query("
SELECT SELECT
Id Id,
document_alias
FROM FROM
" . PREFIX . "_documents " . PREFIX . "_documents
WHERE WHERE
@ -2083,6 +2119,12 @@
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
if ($row->Id == 1)
$hash_url = md5('');
else
$hash_url = md5($row->document_alias);
$AVE_DB->clearCacheUrl('url_'.$hash_url);
$AVE_DB->clearcache('doc_'.$row->Id); $AVE_DB->clearcache('doc_'.$row->Id);
$AVE_DB->clearcompile('doc_'.$row->Id); $AVE_DB->clearcompile('doc_'.$row->Id);
} }

26
class/class.session.files.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -11,8 +11,8 @@
* @license GPL v.2 * @license GPL v.2
*/ */
class AVE_Session class AVE_Session
{ {
public $sess_lifetime; public $sess_lifetime;
@ -32,7 +32,7 @@ class AVE_Session
{ {
global $sess_save_path, $sess_session_name; global $sess_save_path, $sess_session_name;
$sess_save_path = BASE_DIR . '/session'; $sess_save_path = BASE_DIR . '/tmp/session';
$sess_session_name = $session_name; $sess_session_name = $session_name;
return true; return true;
@ -111,15 +111,18 @@ class AVE_Session
function _clear($dir, $mask, $maxlifetime) function _clear($dir, $mask, $maxlifetime)
{ {
foreach(glob($dir . '/*') as $filename) { foreach(glob($dir . '/*') as $filename)
{
if(strtolower(substr($filename, strlen($filename) - strlen($mask), strlen($mask))) == strtolower($mask)) { if (strtolower(substr($filename, strlen($filename) - strlen($mask), strlen($mask))) == strtolower($mask))
if((filemtime($filename) + $maxlifetime) < time()) {
if ((filemtime($filename) + $maxlifetime) < time())
@unlink($filename); @unlink($filename);
} }
if(is_dir($filename)) if (is_dir($filename))
if (!count(glob($filename.'/*'))) @rmdir($filename); if (! count(glob($filename.'/*')))
@rmdir($filename);
self::_clear($filename, $mask, $maxlifetime); self::_clear($filename, $mask, $maxlifetime);
} }
} }
@ -135,6 +138,5 @@ class AVE_Session
{ {
register_shutdown_function('session_write_close'); register_shutdown_function('session_write_close');
} }
}
}
?> ?>

2
class/class.session.php

@ -58,7 +58,7 @@ class AVE_Session_DB
function __construct() function __construct()
{ {
// Подключаем конфигурационный файл с параметрами подключения // Подключаем конфигурационный файл с параметрами подключения
require (BASE_DIR . '/inc/db.config.php'); require (BASE_DIR . '/config/db.config.php');
$this->db_host = $config['dbhost']; $this->db_host = $config['dbhost'];
$this->db_user = $config['dbuser']; $this->db_user = $config['dbuser'];

12
class/class.settings.php

@ -103,7 +103,7 @@ class AVE_Settings
$set .= '?>'; $set .= '?>';
$result = file_put_contents(BASE_DIR . '/inc/config.inc.php', $set); $result = file_put_contents(BASE_DIR . '/config/config.inc.php', $set);
if ($result > 0) if ($result > 0)
{ {
@ -227,9 +227,12 @@ class AVE_Settings
reportLog($AVE_Template->get_config_vars('SETTINGS_SAVE_MAIN')); reportLog($AVE_Template->get_config_vars('SETTINGS_SAVE_MAIN'));
} }
if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1') { if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1')
{
echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme)); echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
} else { }
else
{
$AVE_Template->assign('message', $message); $AVE_Template->assign('message', $message);
header('Location:index.php?do=settings&cp=' . SESSION); header('Location:index.php?do=settings&cp=' . SESSION);
} }
@ -253,6 +256,7 @@ class AVE_Settings
); );
$countries = array(); $countries = array();
while ($row = $sql->FetchAssocArray()) while ($row = $sql->FetchAssocArray())
{ {
array_push($countries, $row); array_push($countries, $row);
@ -599,7 +603,7 @@ class AVE_Settings
*/ */
function clearSettingsCache() function clearSettingsCache()
{ {
$cache_dir = BASE_DIR . '/cache/sql/settings/'; $cache_dir = BASE_DIR . '/tmp/cache/sql/settings/';
return rrmdir($cache_dir); return rrmdir($cache_dir);
} }

28
class/class.sysblocks.php

@ -111,11 +111,7 @@
$theme = 'accept'; $theme = 'accept';
//-- Стираем кеш сисблока //-- Стираем кеш сисблока
if (file_exists(BASE_DIR . '/cache/sql/sysblock/' . $sysblock_id . '.cache')) $this->clearCache($sysblock_id, $_REQUEST['sysblock_alias']);
unlink(BASE_DIR . '/cache/sql/sysblock/' . $sysblock_id . '.cache');
if ($sysblock_alias != '' && file_exists(BASE_DIR . '/cache/sql/sysblock/' . $sysblock_alias . '.cache'))
unlink(BASE_DIR . '/cache/sql/sysblock/' . $sysblock_alias . '.cache');
//-- Сохраняем системное сообщение в журнал //-- Сохраняем системное сообщение в журнал
reportLog($AVE_Template->get_config_vars('SYSBLOCK_SQLUPDATE') . " (" . stripslashes($_REQUEST['sysblock_name']) . ") (id: $sysblock_id)"); reportLog($AVE_Template->get_config_vars('SYSBLOCK_SQLUPDATE') . " (" . stripslashes($_REQUEST['sysblock_name']) . ") (id: $sysblock_id)");
@ -275,11 +271,7 @@
"); ");
//-- Стираем кеш сисблока //-- Стираем кеш сисблока
if (file_exists(BASE_DIR . '/cache/sql/sysblock-' . $sysblock_id . '.cache')) $this->clearCache($sysblock_id, $row->sysblock_alias);
unlink(BASE_DIR . '/cache/sql/sysblock/' . $sysblock_id . '.cache');
if ($row->sysblock_alias != '')
unlink(BASE_DIR . '/cache/sql/sysblock/' . $row->sysblock_alias . '.cache');
//-- Сохраняем системное сообщение в журнал //-- Сохраняем системное сообщение в журнал
reportLog($AVE_Template->get_config_vars('SYSBLOCK_SQLDEL') . " (" . stripslashes($row->sysblock_name) . ") (id: $sysblock_id)"); reportLog($AVE_Template->get_config_vars('SYSBLOCK_SQLDEL') . " (" . stripslashes($row->sysblock_name) . ") (id: $sysblock_id)");
@ -287,5 +279,21 @@
header('Location:index.php?do=sysblocks&cp=' . SESSION); header('Location:index.php?do=sysblocks&cp=' . SESSION);
} }
function clearCache ($id, $alias = null)
{
$cache_id = md5('sysblock' . $id);
$cache_alias = md5('sysblock' . $alias);
$cache_id_file = BASE_DIR . '/tmp/cache/sql/sysblock/' . $cache_id . '.cache';
$cache_alias_file = BASE_DIR . '/tmp/cache/sql/sysblock/' . $cache_alias . '.cache';
if (file_exists($cache_id_file))
unlink($cache_id_file);
if (file_exists($cache_alias_file))
unlink($cache_alias_file);
}
} }
?> ?>

19
class/class.template.php

@ -42,32 +42,32 @@ class AVE_Template extends Smarty
/** /**
* Имя каталога, в котором хранятся компилированные шаблоны. * Имя каталога, в котором хранятся компилированные шаблоны.
*/ */
$this->compile_dir = BASE_DIR . '/cache/smarty'; $this->compile_dir = BASE_DIR . '/tmp/cache/smarty';
/** /**
* Имя каталога, в котором хранится кэш. * Имя каталога, в котором хранится кэш.
*/ */
$this->cache_dir_root = BASE_DIR . '/cache'; $this->cache_dir_root = BASE_DIR . '/tmp/cache';
/** /**
* Имя каталога, в котором хранится кэш шаблонов. * Имя каталога, в котором хранится кэш шаблонов.
*/ */
$this->cache_dir = BASE_DIR . '/cache/tpl'; $this->cache_dir = BASE_DIR . '/tmp/cache/tpl';
/** /**
* Имя каталога, в котором хранится кэш модулей. * Имя каталога, в котором хранится кэш модулей.
*/ */
$this->module_cache_dir = BASE_DIR . '/cache/module'; $this->module_cache_dir = BASE_DIR . '/tmp/cache/module';
/** /**
* Имя каталога, в котором хранится сессии пользователей. * Имя каталога, в котором хранится сессии пользователей.
*/ */
$this->session_dir = BASE_DIR . '/session'; $this->session_dir = BASE_DIR . '/tmp/session';
/** /**
* Имя каталога, в котором хранится сессии пользователей. * Имя каталога, в котором хранится сессии пользователей.
*/ */
$this->sql_cache_dir = BASE_DIR . '/cache/sql'; $this->sql_cache_dir = BASE_DIR . '/tmp/cache/sql';
/** /**
* Использование поддиректорий для хранения кэша и скомпилированных шаблонов. * Использование поддиректорий для хранения кэша и скомпилированных шаблонов.
@ -217,13 +217,14 @@ class AVE_Template extends Smarty
{ {
$this->clear_all_cache(); $this->clear_all_cache();
foreach (glob($this->cache_dir_root."/cache_*") as $filename) foreach (glob($this->cache_dir_root . "/cache_*") as $filename)
{ {
@unlink($filename); @unlink($filename);
} }
$filename = $this->cache_dir . '/.htaccess'; $filename = $this->cache_dir . '/.htaccess';
if (!file_exists($filename))
if (! file_exists($filename))
{ {
$fp = @fopen($filename, 'w'); $fp = @fopen($filename, 'w');
if ($fp) if ($fp)
@ -233,7 +234,7 @@ class AVE_Template extends Smarty
} }
} }
if($_REQUEST['ajax'] && Memcached_Server && Memcached_Port) if ($_REQUEST['ajax'] && Memcached_Server && Memcached_Port)
{ {
$memcache = new Memcache; $memcache = new Memcache;
$memcache->connect(Memcached_Server, Memcached_Port); $memcache->connect(Memcached_Server, Memcached_Port);

37
class/class.templates.php

@ -142,6 +142,12 @@
{ {
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$template_id = (int)$_REQUEST['Id'];
$cache = 'template_' . $template_id;
$cache_file = BASE_DIR . '/tmp/cache/templates/' . $cache . '.inc';
$row = $AVE_DB->Query(" $row = $AVE_DB->Query("
SELECT SELECT
* *
@ -159,8 +165,15 @@
$AVE_Template->assign('read_only', 'readonly'); $AVE_Template->assign('read_only', 'readonly');
} }
if (file_exists($cache_file) && filesize($cache_file))
{
$row->template_text = file_get_contents($cache_file);
}
else
{
$row->template_text = pretty_chars($row->template_text); $row->template_text = pretty_chars($row->template_text);
$row->template_text = stripslashes($row->template_text); $row->template_text = stripslashes($row->template_text);
}
$AVE_Template->assign('row', $row); $AVE_Template->assign('row', $row);
$AVE_Template->assign('content', $AVE_Template->fetch('templates/form.tpl')); $AVE_Template->assign('content', $AVE_Template->fetch('templates/form.tpl'));
@ -173,6 +186,8 @@
if (isset($_REQUEST['Id']) AND is_numeric($_REQUEST['Id'])) if (isset($_REQUEST['Id']) AND is_numeric($_REQUEST['Id']))
{ {
$template_id = $_REQUEST['Id'];
$ok = true; $ok = true;
$check_code = strtolower($_REQUEST['template_text']); $check_code = strtolower($_REQUEST['template_text']);
@ -190,6 +205,10 @@
$theme = 'error'; $theme = 'error';
} }
$cache = 'template_' . $template_id;
$cache_file = BASE_DIR . '/tmp/cache/templates/' . $cache . '.inc';
if ($ok === false) if ($ok === false)
{ {
if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1') if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1')
@ -212,7 +231,7 @@
template_title = '" . $_REQUEST['template_title'] . "', template_title = '" . $_REQUEST['template_title'] . "',
template_text = '" . addslashes(pretty_chars($_REQUEST['template_text'])) . "' template_text = '" . addslashes(pretty_chars($_REQUEST['template_text'])) . "'
WHERE WHERE
Id = '" . (int)$_REQUEST['Id'] . "' Id = '" . $template_id . "'
"); ");
if ($sql === false) if ($sql === false)
@ -223,6 +242,11 @@
} }
else else
{ {
if (! file_exists(dirname($cache_file)))
mkdir(dirname($cache_file), 0766, true);
file_put_contents($cache_file, stripslashes(pretty_chars($_REQUEST['template_text'])));
$message = $AVE_Template->get_config_vars('TEMPLATES_SAVED'); $message = $AVE_Template->get_config_vars('TEMPLATES_SAVED');
$header = $AVE_Template->get_config_vars('TEMPLATES_SUCCESS'); $header = $AVE_Template->get_config_vars('TEMPLATES_SUCCESS');
$theme = 'accept'; $theme = 'accept';
@ -295,6 +319,15 @@
$iid = $AVE_DB->InsertId(); $iid = $AVE_DB->InsertId();
$cache = 'template_' . $iid;
$cache_file = BASE_DIR . '/tmp/cache/templates/' . $cache . '.inc';
if (! file_exists(dirname($cache_file)))
mkdir(dirname($cache_file), 0766, true);
file_put_contents($cache_file, stripslashes(pretty_chars($_REQUEST['template_text'])));
reportLog($AVE_Template->get_config_vars('TEMPLATES_REPORT_NEW') . '(' . stripslashes(htmlspecialchars($_REQUEST['template_text'], ENT_QUOTES)) . ') (Id:' . (int)$iid . ')'); reportLog($AVE_Template->get_config_vars('TEMPLATES_REPORT_NEW') . '(' . stripslashes(htmlspecialchars($_REQUEST['template_text'], ENT_QUOTES)) . ') (Id:' . (int)$iid . ')');
if (!$_REQUEST['next_edit']) if (!$_REQUEST['next_edit'])
@ -440,7 +473,7 @@
{ {
case 'save': case 'save':
$dir = BASE_DIR.'/templates/'.DEFAULT_THEME_FOLDER.'/css/'.$_REQUEST['name_file']; $dir = BASE_DIR . '/templates/' . DEFAULT_THEME_FOLDER . '/css/' . $_REQUEST['name_file'];
$check_code = stripcslashes($_REQUEST['code_text']); $check_code = stripcslashes($_REQUEST['code_text']);

1
config/.htaccess

@ -0,0 +1 @@
deny from all

0
inc/config.inc.php → config/config.inc.php

0
inc/db.config.php → config/db.config.php

2
fields/checkbox/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

2
fields/date/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

2
fields/doc_from_rub/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

2
fields/doc_from_rub_check/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

2
fields/drop_down/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

2
fields/drop_down_key/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

11
fields/image_mega/field.php

@ -91,7 +91,15 @@
$default = explode('|', $default); $default = explode('|', $default);
if (count($default) > 1)
list ($path, $watermark, $position, $transparency) = $default; list ($path, $watermark, $position, $transparency) = $default;
else
{
list ($path) = $default;
$watermark = false;
$position = null;
$transparency = null;
}
if (preg_match("/%id/i", $path)) if (preg_match("/%id/i", $path))
{ {
@ -288,6 +296,8 @@
break; break;
case 'save': case 'save':
if (is_array($field_value))
{
foreach ($field_value as $v) foreach ($field_value as $v)
{ {
if (! empty($v['url'])) if (! empty($v['url']))
@ -299,6 +309,7 @@
. ($v['link'] ? '|' . ltrim($v['link'], '/') : '|'); . ($v['link'] ? '|' . ltrim($v['link'], '/') : '|');
} }
} }
}
if (isset($field_value_new)) if (isset($field_value_new))
return serialize($field_value_new); return serialize($field_value_new);

4
fields/image_single/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms
@ -31,7 +31,7 @@
switch ($action) switch ($action)
{ {
case 'edit': case 'edit':
$blanc = '/uploads/images/noimage.gif'; $blanc = '/uploads/images/noimage.png';
$image = explode('|', $field_value); $image = explode('|', $field_value);
$img = $image[0]; $img = $image[0];
unset($image[0]); unset($image[0]);

4
fields/image_single/js/field.js

@ -40,10 +40,10 @@ var SingleImage = {
if (input.val() == '') { if (input.val() == '') {
$('#preview__' + image_id + '_' + doc_id).attr({ $('#preview__' + image_id + '_' + doc_id).attr({
'src': '/uploads/images/' + thumbdir + '/noimage-f128x128.gif' 'src': '/uploads/images/' + thumbdir + '/noimage-f128x128.png'
}); });
$('.preview__' + image_id + '_' + doc_id).attr({ $('.preview__' + image_id + '_' + doc_id).attr({
'href': '/uploads/images/noimage.gif' 'href': '/uploads/images/noimage.png'
}); });
} }
}); });

2
fields/single_line/field.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

2
functions/func.block.php

@ -29,7 +29,7 @@
{ {
$cache = md5('block' . $id); $cache = md5('block' . $id);
$cache_file = BASE_DIR . '/cache/sql/block/' . $cache . '.cache'; $cache_file = BASE_DIR . '/tmp/cache/sql/block/' . $cache . '.cache';
// Если включен DEV MODE, то отключаем кеширование запросов // Если включен DEV MODE, то отключаем кеширование запросов
if (defined('DEV_MODE') AND DEV_MODE) if (defined('DEV_MODE') AND DEV_MODE)

19
functions/func.common.php

@ -84,8 +84,10 @@
{ {
if ($object != '.' && $object != '..') if ($object != '.' && $object != '..')
{ {
if (filetype($dir . '/' . $object) == 'dir') rrmdir($dir . '/' . $object, $result); if (filetype($dir . '/' . $object) == 'dir')
else $result = $result + (unlink($dir . '/' . $object) ? 0 : 1); rrmdir($dir . '/' . $object, $result);
else
$result = $result + (unlink($dir . '/' . $object) ? 0 : 1);
} }
} }
@ -93,6 +95,7 @@
$result = $result + (rmdir($dir) ? 0 : 1); $result = $result + (rmdir($dir) ? 0 : 1);
} }
return $result > 0 ? false : true; return $result > 0 ? false : true;
} }
@ -105,7 +108,7 @@
*/ */
function clean_php($text) function clean_php($text)
{ {
return str_replace(array('<?', '?>', '<script'), '', $text); return str_replace(array('<?php', '<?', '?>', '<script'), '', $text);
} }
@ -128,7 +131,7 @@
* @internal param int $id идентификатор запроса * @internal param int $id идентификатор запроса
* @return string * @return string
*/ */
function eval2var( $expression ) function eval2var($expression)
{ {
global $AVE_DB, $AVE_Core, $AVE_Template; global $AVE_DB, $AVE_Core, $AVE_Template;
@ -151,7 +154,7 @@
* @param mixed $offset с какого символа в haystack начинать поиск. * @param mixed $offset с какого символа в haystack начинать поиск.
* @return int числовая позиция * @return int числовая позиция
*/ */
if (!function_exists("stripos")) if (! function_exists("stripos"))
{ {
function stripos($haystack, $needle, $offset = 0) function stripos($haystack, $needle, $offset = 0)
{ {
@ -767,7 +770,7 @@
{ {
$object = (array)$object; $object = (array)$object;
if($object === array()) if ($object === array())
return; return;
foreach($object as $key => &$value) foreach($object as $key => &$value)
@ -1063,6 +1066,7 @@
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')); return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'));
} }
/** /**
* Функция делает html в 1 строчку, удаляет лишние пробелы, комментарии и т.д. * Функция делает html в 1 строчку, удаляет лишние пробелы, комментарии и т.д.
* *
@ -1124,7 +1128,4 @@
echo $content; echo $content;
} }
?> ?>

2
functions/func.custom.php

@ -1,4 +1,4 @@
<? <?php
/** /**
* AVE.cms * AVE.cms

13
functions/func.hidden.php

@ -1,6 +1,5 @@
<? <?php
/**
/**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -12,15 +11,15 @@
*/ */
/** /**
* Обработка парного тега [tag:hide:X,X:text]...[/tag:hide] (скрытый текст) * Обработка парного тега [tag:hide:X,X:text]...[/tag:hide] (скрытый текст)
* Заменяет скрываемый текст в зависимости от группы пользователя * Заменяет скрываемый текст в зависимости от группы пользователя
* *
* @param string $data обрабатываемый текст * @param string $data обрабатываемый текст
* @return string обработанный текст * @return string обработанный текст
*/ */
function parse_hide($data) function parse_hide($data)
{ {
static $matches = null; static $matches = null;
static $i = null; static $i = null;
@ -46,5 +45,5 @@ function parse_hide($data)
$data = preg_replace('/\[tag:hide:\d+(,\d+)*.*?](.*?)\[\/tag:hide]/s', '\\2', $data); $data = preg_replace('/\[tag:hide:\d+(,\d+)*.*?](.*?)\[\/tag:hide]/s', '\\2', $data);
return $data; return $data;
} }
?> ?>

2
functions/func.locale.php

@ -1,4 +1,4 @@
<? <?php
// Язык системы // Язык системы
function set_locale() function set_locale()
{ {

75
functions/func.logs.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -12,7 +12,7 @@
*/ */
/** /**
* Запись события в лог * Запись события в лог
* *
* @param string $message Текст сообщения * @param string $message Текст сообщения
@ -20,50 +20,55 @@
* @param int $rub номер рубрики * @param int $rub номер рубрики
* @return * @return
*/ */
function reportLog($message, $typ = 0, $rub = 0) function reportLog($message, $typ = 0, $rub = 0)
{ {
$logdata=array(); $logdata=array();
$logfile=BASE_DIR.'/cache/log.php'; $logfile = BASE_DIR . '/tmp/logs/log.php';
if(file_exists($logfile))
@eval('?>'.file_get_contents($logfile).'<?'); if (file_exists($logfile))
@eval(' ?'.'>' . file_get_contents($logfile) . '<?'.'php ');
$logdata[]=array( $logdata[]=array(
'log_time' =>time(), 'log_time' => time(),
'log_ip' =>$_SERVER['REMOTE_ADDR'], 'log_ip' => $_SERVER['REMOTE_ADDR'],
'log_url' =>$_SERVER['QUERY_STRING'], 'log_url' => $_SERVER['QUERY_STRING'],
'log_user_id' =>(isset($_SESSION['user_id']) ? $_SESSION['user_id'] : '0'), 'log_user_id' => (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : '0'),
'log_user_name' =>(isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'Anonymous'), 'log_user_name' => (isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'Anonymous'),
'log_text' =>$message, 'log_text' => $message,
'log_type' =>(int)$typ, 'log_type' => (int)$typ,
'log_rubric' =>(int)$rub 'log_rubric' => (int)$rub
); );
$messlimit = 1000; $messlimit = 1000;
$logdata = array_slice($logdata,-1*$messlimit); $logdata = array_slice($logdata,-1*$messlimit);
file_put_contents($logfile,'<?php $logdata=' . var_export($logdata,true) . ' ?>'); file_put_contents($logfile,'<?php $logdata=' . var_export($logdata,true) . ' ?>');
} }
/** /**
* Запись события в лог для Sql ошибок * Запись события в лог для Sql ошибок
* *
* @param string $message Текст сообщения * @param string $message Текст сообщения
* @return * @return
*/ */
function reportSqlLog($message) function reportSqlLog($message)
{ {
$logsql = array(); $logsql = array();
$logfile = BASE_DIR . '/cache/sql.php'; $logfile = BASE_DIR . '/tmp/logs/sql.php';
if(file_exists($logfile)) if (file_exists($logfile))
@eval('?>'.file_get_contents($logfile).'<?'); @eval(' ?'.'>' . file_get_contents($logfile) . '<?'.'php ');
$logsql[] = array( $logsql[] = array(
'log_time' =>time(), 'log_time' => time(),
'log_ip' =>$_SERVER['REMOTE_ADDR'], 'log_ip' => $_SERVER['REMOTE_ADDR'],
'log_url' =>$_SERVER['QUERY_STRING'], 'log_url' => $_SERVER['QUERY_STRING'],
'log_user_id' =>$_SESSION['user_id'], 'log_user_id' => $_SESSION['user_id'],
'log_user_name' =>$_SESSION['user_name'], 'log_user_name' => $_SESSION['user_name'],
'log_text' =>$message 'log_text' => $message
); );
$messlimit = 1000; $messlimit = 1000;
@ -71,21 +76,21 @@ function reportSqlLog($message)
$logsql = array_slice($logsql,-1*$messlimit); $logsql = array_slice($logsql,-1*$messlimit);
file_put_contents($logfile, '<?php $logsql = ' . var_export($logsql, true) . ' ?>'); file_put_contents($logfile, '<?php $logsql = ' . var_export($logsql, true) . ' ?>');
} }
/** /**
* Запись события в лог для 404 ошибок * Запись события в лог для 404 ошибок
* *
* @param string $message Текст сообщения * @param string $message Текст сообщения
* @return * @return
*/ */
function report404() function report404()
{ {
$log404 = array(); $log404 = array();
$logfile = BASE_DIR . '/cache/404.php'; $logfile = BASE_DIR . '/tmp/logs/404.php';
if(file_exists($logfile)) if (file_exists($logfile))
@include($logfile); @include($logfile);
$log404[] = array( $log404[] = array(
@ -102,6 +107,6 @@ function report404()
$log404 = array_slice($log404, -1*$messlimit); $log404 = array_slice($log404, -1*$messlimit);
file_put_contents($logfile,'<?php $log404=' . var_export($log404, true) . ' ?>'); file_put_contents($logfile,'<?php $log404=' . var_export($log404, true) . ' ?>');
} }
?> ?>

2
functions/func.mail.php

@ -114,7 +114,7 @@ if ( ! function_exists('send_mail'))
// Сохраняем вложения в ATTACH_DIR, если просили // Сохраняем вложения в ATTACH_DIR, если просили
if ($attach && $saveattach) if ($attach && $saveattach)
{ {
$attach_dir = BASE_DIR . '/' . ATTACH_DIR . '/'; $attach_dir = BASE_DIR . '/tmp/' . ATTACH_DIR . '/';
foreach ($attach as $file_path) foreach ($attach as $file_path)
{ {
if ($file_path && file_exists($file_path)) if ($file_path && file_exists($file_path))

6
functions/func.navigation.php

@ -47,7 +47,7 @@
$navi = ''; $navi = '';
$cache_file = BASE_DIR . '/cache/sql/nav/template-' . $navi_id . '.cache'; $cache_file = BASE_DIR . '/tmp/cache/sql/nav/template-' . $navi_id . '.cache';
// Если включен DEV MODE, то отключаем кеширование запросов // Если включен DEV MODE, то отключаем кеширование запросов
if (defined('DEV_MODE') AND DEV_MODE || $expnad_ext != 1) if (defined('DEV_MODE') AND DEV_MODE || $expnad_ext != 1)
@ -201,7 +201,7 @@
} }
} }
$cache_items = BASE_DIR . '/cache/sql/nav/items-' . $navi_id . '.cache'; $cache_items = BASE_DIR . '/tmp/cache/sql/nav/items-' . $navi_id . '.cache';
$navi_items = array(); $navi_items = array();
@ -464,7 +464,7 @@
if (empty($navi)) if (empty($navi))
$navi = ''; $navi = '';
$navi .= eval2var('?>' . $item . '<?'); $navi .= eval2var(' ?>' . $item . '<?php ');
} }
// Вставляем все пункты уровня в шаблон уровня // Вставляем все пункты уровня в шаблон уровня

15
functions/func.parserequest.php

@ -370,7 +370,7 @@
"SELECT rubric_teaser_template FROM " . PREFIX . "_rubrics WHERE Id='" . intval($row->rubric_id) . "'" "SELECT rubric_teaser_template FROM " . PREFIX . "_rubrics WHERE Id='" . intval($row->rubric_id) . "'"
)->GetCell()); )->GetCell());
$cachefile_docid = BASE_DIR . '/cache/sql/request/' . $row->Id . '/request-' . md5($template) . '.cache'; $cachefile_docid = BASE_DIR . '/tmp/cache/sql/request/' . $row->Id . '/request-' . md5($template) . '.cache';
// Если включен DEV MODE, то отключаем кеширование запросов // Если включен DEV MODE, то отключаем кеширование запросов
if (defined('DEV_MODE') AND DEV_MODE) if (defined('DEV_MODE') AND DEV_MODE)
@ -799,6 +799,7 @@
// Составляем запрос к БД // Составляем запрос к БД
$sql = " ?> $sql = " ?>
#REQUEST = $request->Id
SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS
a.* a.*
" . $request_select_str . " " . $request_select_str . "
@ -1026,8 +1027,8 @@
$main_template = str_replace('[tag:docauthorid]', $AVE_Core->curentdoc->document_author_id, $main_template); $main_template = str_replace('[tag:docauthorid]', $AVE_Core->curentdoc->document_author_id, $main_template);
//-- Имя автора //-- Имя автора
if (preg_match('[tag:docauthor]', $main_content)) if (preg_match('[tag:docauthor]', $main_template))
$main_content = str_replace('[tag:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_content); $main_template = str_replace('[tag:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_template);
//-- Время - 1 день назад //-- Время - 1 день назад
$main_template = str_replace('[tag:humandate]', human_date($AVE_Core->curentdoc->document_published), $main_template); $main_template = str_replace('[tag:humandate]', human_date($AVE_Core->curentdoc->document_published), $main_template);
@ -1128,8 +1129,8 @@
*/ */
function request_get_document_field_value($rubric_id, $document_id, $maxlength = 0) function request_get_document_field_value($rubric_id, $document_id, $maxlength = 0)
{ {
if (! is_numeric($rubric_id) || $rubric_id < 1 || ! is_numeric($document_id) || $document_id < 1)
if (! is_numeric($rubric_id) || $rubric_id < 1 || ! is_numeric($document_id) || $document_id < 1) return ''; return '';
$document_fields = get_document_fields($document_id); $document_fields = get_document_fields($document_id);
@ -1153,7 +1154,9 @@
$maxlength = abs($maxlength); $maxlength = abs($maxlength);
} }
$field_value = mb_substr($field_value, 0, $maxlength) . (strlen($field_value) > $maxlength ? '... ' : ''); $field_value = mb_substr($field_value, 0, $maxlength) . (strlen($field_value) > $maxlength
? '... '
: '');
} }
return $field_value; return $field_value;

2
functions/func.sysblock.php

@ -33,7 +33,7 @@
$cache = md5('sysblock' . $id); $cache = md5('sysblock' . $id);
$cache_file = BASE_DIR . '/cache/sql/sysblock/' . $cache . '.cache'; $cache_file = BASE_DIR . '/tmp/cache/sql/sysblock/' . $cache . '.cache';
// Если включен DEV MODE, то отключаем кеширование запросов // Если включен DEV MODE, то отключаем кеширование запросов
if (defined('DEV_MODE') AND DEV_MODE) if (defined('DEV_MODE') AND DEV_MODE)

84
inc/antispam.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -11,8 +11,8 @@
* @license GPL v.2 * @license GPL v.2
*/ */
function get_securecode() function get_securecode()
{ {
@require('./db.config.php'); @require('./db.config.php');
if (! isset($config)) die; if (! isset($config)) die;
@ -24,54 +24,54 @@ function get_securecode()
if (! $row = mysql_fetch_assoc(mysql_query("SELECT Code FROM " . $config['dbpref'] . "_antispam WHERE Id = '" . $_GET['cp_secureimage'] . "'"))) die; if (! $row = mysql_fetch_assoc(mysql_query("SELECT Code FROM " . $config['dbpref'] . "_antispam WHERE Id = '" . $_GET['cp_secureimage'] . "'"))) die;
return $row['Code']; return $row['Code'];
} }
$code = get_securecode(); $code = get_securecode();
$font = 'fonts/ft16.ttf'; $font = 'fonts/ft16.ttf';
$raster = 0; $raster = 0;
$step = 10; $step = 10;
$size = 26; $size = 26;
$code_top = 38; $code_top = 38;
$rect_width = 120; $rect_width = 120;
$rect_height = 40; $rect_height = 40;
$bild = imagecreate(++$rect_width, ++$rect_height); $bild = imagecreate(++$rect_width, ++$rect_height);
$back = imagecolorallocate($bild, 255, 255, 255); $back = imagecolorallocate($bild, 255, 255, 255);
$gelb = imagecolorallocate($bild, 238, 192, 10); $gelb = imagecolorallocate($bild, 238, 192, 10);
$schwarz = imagecolorallocate($bild, 0, 0, 0); $schwarz = imagecolorallocate($bild, 0, 0, 0);
$grau = imagecolorallocate($bild, 204, 204, 204); $grau = imagecolorallocate($bild, 204, 204, 204);
$dunkelgrau = imagecolorallocate($bild, 119, 119, 119); $dunkelgrau = imagecolorallocate($bild, 119, 119, 119);
// Prevent the browser from caching the result. // Prevent the browser from caching the result.
// Date in the past // Date in the past
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT') ; header('Expires: Mon, 26 Jul 1997 05:00:00 GMT') ;
// always modified // always modified
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT') ; header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT') ;
// HTTP/1.1 // HTTP/1.1
header('Cache-Control: no-store, no-cache, must-revalidate') ; header('Cache-Control: no-store, no-cache, must-revalidate') ;
header('Cache-Control: post-check=0, pre-check=0', false) ; header('Cache-Control: post-check=0, pre-check=0', false) ;
// HTTP/1.0 // HTTP/1.0
header('Pragma: no-cache') ; header('Pragma: no-cache') ;
// Set the response format. // Set the response format.
header('Content-type: image/jpeg'); header('Content-type: image/jpeg');
$count_vert = $rect_width/$step; $count_vert = $rect_width/$step;
$count_hori = $rect_height/$step; $count_hori = $rect_height/$step;
if ($raster == 1) if ($raster == 1)
{ {
for($i=0;$i<$count_vert;$i++) imageline($bild, $i*$step, 0, $i*$step, $rect_height, $grau); for($i=0;$i<$count_vert;$i++) imageline($bild, $i*$step, 0, $i*$step, $rect_height, $grau);
for($i=0;$i<$count_hori;$i++) imageline($bild, 0, $i*$step, $rect_width, $i*$step, $grau); for($i=0;$i<$count_hori;$i++) imageline($bild, 0, $i*$step, $rect_width, $i*$step, $grau);
} }
else else
{ {
for($a=0;$a<$count_hori;$a++) for($i=0;$i<$count_vert;$i++) imagesetpixel($bild, $i*$step, $a*$step, $grau); for($a=0;$a<$count_hori;$a++) for($i=0;$i<$count_vert;$i++) imagesetpixel($bild, $i*$step, $a*$step, $grau);
} }
imagettftext($bild, $size, 7, 25, $code_top, $dunkelgrau, $font, $code); imagettftext($bild, $size, 7, 25, $code_top, $dunkelgrau, $font, $code);
imagerectangle($bild, 0, 0, $rect_width, $rect_height, $dunkelgrau); imagerectangle($bild, 0, 0, $rect_width, $rect_height, $dunkelgrau);
imagejpeg($bild); imagejpeg($bild);
imagedestroy($bild); imagedestroy($bild);
?> ?>

6
inc/config.php

@ -92,7 +92,7 @@
$GLOBALS['CMS_CONFIG']['ADMIN_CAPTCHA'] = array('DESCR' => 'Использовать капчу при входе в админку','default'=>false,'TYPE'=>'bool','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['ADMIN_CAPTCHA'] = array('DESCR' => 'Использовать капчу при входе в админку','default'=>false,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['ADMIN_EDITMENU'] = array('DESCR' => 'Использовать всплывающие "Действия" в системе','default'=>true,'TYPE'=>'bool','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['ADMIN_EDITMENU'] = array('DESCR' => 'Использовать всплывающие "Действия" в системе','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['ATTACH_DIR'] = array('DESCR' => 'Директория для хранения вложений','default'=>'cache/attachments','TYPE'=>'string','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['ATTACH_DIR'] = array('DESCR' => 'Директория для хранения вложений','default'=>'attachments','TYPE'=>'string','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['UPLOAD_DIR'] = array('DESCR' => 'Директория для хранения файлов','default'=>'uploads','TYPE'=>'string','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['UPLOAD_DIR'] = array('DESCR' => 'Директория для хранения файлов','default'=>'uploads','TYPE'=>'string','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['UPLOAD_SHOP_DIR'] = array('DESCR' => 'Директория для хранения миниатюр Магазина','default'=>'uploads/shop','TYPE'=>'string','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['UPLOAD_SHOP_DIR'] = array('DESCR' => 'Директория для хранения миниатюр Магазина','default'=>'uploads/shop','TYPE'=>'string','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['UPLOAD_GALLERY_DIR'] = array('DESCR' => 'Директория для хранения миниатюр Галерей','default'=>'uploads/gallery','TYPE'=>'string','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['UPLOAD_GALLERY_DIR'] = array('DESCR' => 'Директория для хранения миниатюр Галерей','default'=>'uploads/gallery','TYPE'=>'string','VARIANT'=>'');
@ -124,6 +124,7 @@
$GLOBALS['CMS_CONFIG']['SMARTY_USE_SUB_DIRS'] = array('DESCR' => 'Создание папок для кэширования Установите это в false если ваше окружение PHP не разрешает создание директорий от имени Smarty. Поддиректории более эффективны, так что используйте их, если можете.','default'=>true,'TYPE'=>'bool','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['SMARTY_USE_SUB_DIRS'] = array('DESCR' => 'Создание папок для кэширования Установите это в false если ваше окружение PHP не разрешает создание директорий от имени Smarty. Поддиректории более эффективны, так что используйте их, если можете.','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['CACHE_DOC_TPL'] = array('DESCR' => 'Кэширование скомпилированных шаблонов документов','default'=>true,'TYPE'=>'bool','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['CACHE_DOC_TPL'] = array('DESCR' => 'Кэширование скомпилированных шаблонов документов','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['CACHE_DOC_FILE'] = array('DESCR' => 'Кэширование скомпилированных шаблонов документов в файлах','default'=>true,'TYPE'=>'bool','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['CACHE_DOC_FILE'] = array('DESCR' => 'Кэширование скомпилированных шаблонов документов в файлах','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['CACHE_DOC_SQL'] = array('DESCR' => 'Кэширование SQL запроса информации о документе','default'=>0,'TYPE'=>'integer','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['SYSTEM_CACHE_LIFETIME'] = array('DESCR' => 'Время жизни кеша запроса к настройкам системы (60*60*24*14 - 2 недели)','default'=>0,'TYPE'=>'integer','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['SYSTEM_CACHE_LIFETIME'] = array('DESCR' => 'Время жизни кеша запроса к настройкам системы (60*60*24*14 - 2 недели)','default'=>0,'TYPE'=>'integer','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['YANDEX_MAP_API_KEY'] = array('DESCR' => 'Yandex MAP API REY','default'=>'','TYPE'=>'string','VARIANT'=>''); $GLOBALS['CMS_CONFIG']['YANDEX_MAP_API_KEY'] = array('DESCR' => 'Yandex MAP API REY','default'=>'','TYPE'=>'string','VARIANT'=>'');
@ -152,7 +153,8 @@
$GLOBALS['CMS_CONFIG']['DEV_MODE'] = array('DESCR' => 'Режим разработчика (Отключено кеширование SQL)', 'default'=>false, 'TYPE'=>'bool', 'VARIANT'=>''); $GLOBALS['CMS_CONFIG']['DEV_MODE'] = array('DESCR' => 'Режим разработчика (Отключено кеширование SQL)', 'default'=>false, 'TYPE'=>'bool', 'VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['SQL_QUERY_SANITIZE'] = array('DESCR' => 'Принудительно проверять SQL запросы', 'default'=>false, 'TYPE'=>'bool', 'VARIANT'=>''); $GLOBALS['CMS_CONFIG']['SQL_QUERY_SANITIZE'] = array('DESCR' => 'Принудительно проверять SQL запросы', 'default'=>false, 'TYPE'=>'bool', 'VARIANT'=>'');
include_once(dirname(dirname(__FILE__)) . '/inc/config.inc.php'); if (file_exists(dirname(dirname(__FILE__)) . '/config/config.inc.php'))
include_once(dirname(dirname(__FILE__)) . '/config/config.inc.php');
foreach($GLOBALS['CMS_CONFIG'] as $k => $v) foreach($GLOBALS['CMS_CONFIG'] as $k => $v)
if(! defined($k)) if(! defined($k))

136
inc/init.php

@ -16,26 +16,32 @@
if (! defined('BASE_DIR')) if (! defined('BASE_DIR'))
exit; exit;
// Подключаем файл настроек //-- Подключаем файл настроек
require_once (BASE_DIR . '/inc/config.php'); require_once (BASE_DIR . '/inc/config.php');
if (PHP_DEBUGGING_FILE && ! defined('ACP')) if (PHP_DEBUGGING_FILE && ! defined('ACP'))
include_once BASE_DIR . '/inc/errors.php'; include_once BASE_DIR . '/inc/errors.php';
/** //-- Удаление глобальных массивов
* Удаление глобальных массивов
*
*/
function unsetGlobals() function unsetGlobals()
{ {
if (! ini_get('register_globals')) if (! ini_get('register_globals'))
return; return;
$allowed = array('_ENV'=>1, '_GET'=>1, '_POST'=>1, '_COOKIE'=>1, '_FILES'=>1, '_SERVER'=>1, '_REQUEST'=>1, 'GLOBALS'=>1); $allowed = array(
'_ENV' => 1,
'_GET' => 1,
'_POST' => 1,
'_COOKIE' => 1,
'_FILES' => 1,
'_SERVER' => 1,
'_REQUEST' => 1,
'GLOBALS' => 1
);
foreach ($GLOBALS as $key => $value) foreach ($GLOBALS as $key => $value)
{ {
if (!isset($allowed[$key])) if (! isset($allowed[$key]))
unset($GLOBALS[$key]); unset($GLOBALS[$key]);
} }
} }
@ -82,7 +88,7 @@
} }
function is_ssl() function isSSL()
{ {
if (isset($_SERVER['HTTPS'])) if (isset($_SERVER['HTTPS']))
{ {
@ -101,13 +107,14 @@
} }
function set_host() function setHost()
{ {
if (isset($_SERVER['HTTP_HOST'])) if (isset($_SERVER['HTTP_HOST']))
{ {
// Все символы $_SERVER['HTTP_HOST'] приводим к строчным и проверяем // Все символы $_SERVER['HTTP_HOST'] приводим к строчным и проверяем
// на наличие запрещённых символов в соответствии с RFC 952 и RFC 2181. // на наличие запрещённых символов в соответствии с RFC 952 и RFC 2181.
$_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']); $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
if (! preg_match('/^\[?(?:[a-z0-9-:\]_]+\.?)+$/', $_SERVER['HTTP_HOST'])) if (! preg_match('/^\[?(?:[a-z0-9-:\]_]+\.?)+$/', $_SERVER['HTTP_HOST']))
{ {
// $_SERVER['HTTP_HOST'] не соответствует спецификациям. // $_SERVER['HTTP_HOST'] не соответствует спецификациям.
@ -121,7 +128,7 @@
$_SERVER['HTTP_HOST'] = ''; $_SERVER['HTTP_HOST'] = '';
} }
$ssl = is_ssl(); $ssl = isSSL();
$schema = ($ssl) ? 'https://' : 'http://'; $schema = ($ssl) ? 'https://' : 'http://';
$host = str_replace(':' . $_SERVER['SERVER_PORT'], '', $_SERVER['HTTP_HOST']); $host = str_replace(':' . $_SERVER['SERVER_PORT'], '', $_SERVER['HTTP_HOST']);
$port = ($_SERVER['SERVER_PORT'] == '80' || $_SERVER['SERVER_PORT'] == '443' || $ssl) $port = ($_SERVER['SERVER_PORT'] == '80' || $_SERVER['SERVER_PORT'] == '443' || $ssl)
@ -136,10 +143,11 @@
if (defined('ACP')) if (defined('ACP'))
$abs_path = dirname($abs_path); $abs_path = dirname($abs_path);
define('ABS_PATH', rtrim(str_replace("\\", "/", $abs_path), '/') . '/'); define('ABS_PATH', rtrim(str_replace("\\", "/", $abs_path), '/') . '/');
} }
set_host(); setHost();
set_include_path (get_include_path() . '/' . BASE_DIR . '/lib'); set_include_path (get_include_path() . '/' . BASE_DIR . '/lib');
@ -153,11 +161,10 @@
ini_set ('url_rewriter.tags', ''); ini_set ('url_rewriter.tags', '');
// Переключение для нормальной работы с русскими буквами в некоторых функциях //-- Переключение для нормальной работы с русскими буквами в некоторых функциях
mb_internal_encoding("UTF-8"); mb_internal_encoding("UTF-8");
//-- Вкл/Выкл отображения ошибок php
// Вкл/Выкл отображения ошибок php
if (! PHP_DEBUGGING_FILE) if (! PHP_DEBUGGING_FILE)
{ {
if (! PHP_DEBUGGING) if (! PHP_DEBUGGING)
@ -172,10 +179,15 @@
} }
} }
//-- Debug Class
require (BASE_DIR . '/class/class.debug.php');
$Debug = new Debug;
/** //-- Hooks Class
* Подкючаем необходимые файлы функций require (BASE_DIR . '/class/class.hooks.php');
*/ $Hooks = new Hooks;
//-- Подкючаем необходимые файлы функций
require_once (BASE_DIR . '/functions/func.breadcrumbs.php'); // Хлебные крошки require_once (BASE_DIR . '/functions/func.breadcrumbs.php'); // Хлебные крошки
require_once (BASE_DIR . '/functions/func.common.php'); // Основные функции require_once (BASE_DIR . '/functions/func.common.php'); // Основные функции
require_once (BASE_DIR . '/functions/func.locale.php'); // Языковые функции require_once (BASE_DIR . '/functions/func.locale.php'); // Языковые функции
@ -196,44 +208,38 @@
require_once (BASE_DIR . '/functions/func.watermarks.php'); // Функции по работе с водными знаками require_once (BASE_DIR . '/functions/func.watermarks.php'); // Функции по работе с водными знаками
/** //-- Создание папок и файлов
* Создание папок и файлов foreach (array(ATTACH_DIR, 'cache', 'backup', 'logs', 'session', 'update') as $dir)
*/ write_htaccess_deny(BASE_DIR . '/tmp/' . $dir);
foreach (array('cache', 'backup', 'session') as $dir)
{
write_htaccess_deny(BASE_DIR . '/' . $dir);
}
foreach (array('attachments', 'combine', 'module', 'redactor', 'smarty', 'sql', 'tpl') as $dir) foreach (array('combine', 'module', 'redactor', 'smarty', 'sql', 'templates', 'tpl') as $dir)
{ write_htaccess_deny(BASE_DIR . '/tmp/cache/' . $dir);
write_htaccess_deny(BASE_DIR . '/cache/' . $dir);
}
global $AVE_DB; global $AVE_DB;
// Класс для работы с MySQL (Global $AVE_DB) //-- Класс для работы с MySQL (Global $AVE_DB)
require_once (BASE_DIR . '/class/class.database.php'); require_once (BASE_DIR . '/class/class.database.php');
// Если не существует объекта по работе с БД //-- Если не существует объекта по работе с БД
if (! isset($AVE_DB)) if (! isset($AVE_DB))
{ {
// Подключаем конфигурационный файл с параметрами подключения //-- Подключаем конфигурационный файл с параметрами подключения
require_once (BASE_DIR . '/inc/db.config.php'); require_once (BASE_DIR . '/config/db.config.php');
// Если параметры не указаны, прерываем работу //-- Если параметры не указаны, прерываем работу
if (! isset($config)) if (! isset($config))
exit; exit;
// Если константа префикса таблиц не задана, принудительно определяем ее на основании параметров в файле db.config.php //-- Если константа префикса таблиц не задана, принудительно определяем ее на основании параметров в файле db.config.php
if (! defined('PREFIX')) if (! defined('PREFIX'))
define('PREFIX', $config['dbpref']); define('PREFIX', $config['dbpref']);
// Создаем объект для работы с БД //-- Создаем объект для работы с БД
try { try {
$AVE_DB = AVE_DB::getInstance($config) $AVE_DB = AVE_DB::getInstance($config)
// Назначаем кодировку //-- Назначаем кодировку
->setCharset('utf8') ->setCharset('utf8')
// Назначаем БД //-- Назначаем БД
->setDatabaseName($config['dbname']); ->setDatabaseName($config['dbname']);
} }
catch (AVE_DB_Exception $e) catch (AVE_DB_Exception $e)
@ -250,10 +256,10 @@
unset ($config); unset ($config);
} }
// Устанавливаем обновления системы //-- Устанавливаем обновления системы
if ($AVE_DB) if ($AVE_DB)
{ {
$updaters = (glob(BASE_DIR . "/cache/*.update.php")); $updaters = (glob(BASE_DIR . '/tmp/update/*.update.php'));
if ($updaters) if ($updaters)
{ {
@ -261,9 +267,9 @@
foreach ($updaters as $ufile) foreach ($updaters as $ufile)
{ {
@eval('?>' . @file_get_contents($ufile) . '<?'); @eval(' ?'.'>' . @file_get_contents($ufile) . '<?'.'php ');
if ($ufile != BASE_DIR . '/cache/debug.update.php') if ($ufile != BASE_DIR . '/tmp/update/debug.update.php')
{ {
@unlink($ufile); @unlink($ufile);
@reportLog('Установил обновления (' . $ufile . ')'); @reportLog('Установил обновления (' . $ufile . ')');
@ -274,21 +280,21 @@
set_cookie_domain(); set_cookie_domain();
// Работа с сессиями //-- Работа с сессиями
if (! SESSION_SAVE_HANDLER) if (! SESSION_SAVE_HANDLER)
{ {
// Класс для работы с сессиями //-- Класс для работы с сессиями
require (BASE_DIR . '/class/class.session.files.php'); require (BASE_DIR . '/class/class.session.files.php');
$ses_class = new AVE_Session(); $ses_class = new AVE_Session();
} }
else else
{ {
// Класс для работы с сессиями //-- Класс для работы с сессиями
require (BASE_DIR . '/class/class.session.php'); require (BASE_DIR . '/class/class.session.php');
$ses_class = new AVE_Session_DB(); $ses_class = new AVE_Session_DB();
} }
/* Изменяем save_handler, используем функции класса */ //-- Изменяем save_handler, используем функции класса
session_set_save_handler ( session_set_save_handler (
array(&$ses_class, '_open'), array(&$ses_class, '_open'),
array(&$ses_class, '_close'), array(&$ses_class, '_close'),
@ -298,13 +304,14 @@
array(&$ses_class, '_gc') array(&$ses_class, '_gc')
); );
/* Страт сессии */ //-- Страт сессии
session_start(); session_start();
if (isset($HTTP_SESSION_VARS)) if (isset($HTTP_SESSION_VARS))
$_SESSION = $HTTP_SESSION_VARS; $_SESSION = $HTTP_SESSION_VARS;
//-- Logout
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout')
{ {
user_logout(); user_logout();
@ -314,15 +321,18 @@
} }
//-- Если нет авторизации
if (! defined('ACPL') && ! auth_sessions()) if (! defined('ACPL') && ! auth_sessions())
{ {
if (! auth_cookie()) if (! auth_cookie())
{ {
// чистим данные авторизации в сессии //-- Чистим данные авторизации в сессии
unset($_SESSION['user_id'], $_SESSION['user_pass']); unset($_SESSION['user_id'], $_SESSION['user_pass']);
// считаем пользователя Гостем
//-- Считаем пользователя Гостем
$_SESSION['user_group'] = 2; $_SESSION['user_group'] = 2;
$_SESSION['user_name'] = get_username(); $_SESSION['user_name'] = get_username();
define('UID', 0); define('UID', 0);
define('UGROUP', 2); define('UGROUP', 2);
define('UNAME', $_SESSION['user_name']); define('UNAME', $_SESSION['user_name']);
@ -330,7 +340,7 @@
} }
//Запоминаем время последнего визита пользователя //-- Запоминаем время последнего визита пользователя
if (! empty($_SESSION['user_id'])) if (! empty($_SESSION['user_id']))
{ {
$AVE_DB->Query(" $AVE_DB->Query("
@ -343,7 +353,7 @@
"); ");
} }
//Запоминаем язык браузера //-- Запоминаем язык браузера
$browlang = $_SERVER['HTTP_ACCEPT_LANGUAGE']; $browlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$browlang = explode('-', $browlang); $browlang = explode('-', $browlang);
$browlang = $browlang[0]; $browlang = $browlang[0];
@ -372,43 +382,31 @@
} }
} }
//-- Язык пользователя
$_SESSION['user_language'] = (! empty($_SESSION['user_language']) $_SESSION['user_language'] = (! empty($_SESSION['user_language'])
? $_SESSION['user_language'] ? $_SESSION['user_language']
:(isset($_SESSION['accept_langs'][$browlang]) :(isset($_SESSION['accept_langs'][$browlang])
? $browlang ? $browlang
: DEFAULT_LANGUAGE)); : DEFAULT_LANGUAGE));
define('DATE_FORMAT', get_settings('date_format')); define('DATE_FORMAT', get_settings('date_format'));
define('TIME_FORMAT', get_settings('time_format')); define('TIME_FORMAT', get_settings('time_format'));
define('PAGE_NOT_FOUND_ID', intval(get_settings('page_not_found_id'))); define('PAGE_NOT_FOUND_ID', (int)get_settings('page_not_found_id'));
// Вывод данных документа без общего шаблона //-- Вывод данных документа без общего шаблона
if (isset($_REQUEST['onlycontent']) && 1 == $_REQUEST['onlycontent']) if (isset($_REQUEST['onlycontent']) && 1 == $_REQUEST['onlycontent'])
{
define('ONLYCONTENT', 1); define('ONLYCONTENT', 1);
}
// Язык системы //-- Язык системы
set_locale(); set_locale();
// Debug //-- Класс Шаблонов SMARTY
require (BASE_DIR . '/class/class.debug.php');
$Debug = new Debug;
// Hooks
require (BASE_DIR . '/class/class.hooks.php');
$Hooks = new Hooks;
// Класс Шаблонов SMARTY
require (BASE_DIR . '/class/class.template.php'); require (BASE_DIR . '/class/class.template.php');
// Класс пагинации //-- Класс пагинации
require (BASE_DIR . '/class/class.paginations.php'); require (BASE_DIR . '/class/class.paginations.php');
// Класс Модулей //-- Класс Модулей
require (BASE_DIR . '/class/class.modules.php'); require (BASE_DIR . '/class/class.modules.php');
$AVE_Module = new AVE_Module; $AVE_Module = new AVE_Module;
?> ?>

2
inc/thumb.php

@ -224,7 +224,7 @@
{ {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
$imageName = 'default.png'; $imageName = 'noimage.png';
if (! file_exists("$imagePath/$imageName")) if (! file_exists("$imagePath/$imageName"))
{ {

70
index.php

@ -15,15 +15,15 @@
define ('START_MEMORY', memory_get_usage()); define ('START_MEMORY', memory_get_usage());
define ('BASE_DIR', str_replace("\\", "/", dirname(__FILE__))); define ('BASE_DIR', str_replace("\\", "/", dirname(__FILE__)));
// Проверяем уставлена ли CMS //-- Проверяем уставлена ли CMS
if (! @filesize(BASE_DIR . '/inc/db.config.php')) if (! @filesize(BASE_DIR . '/config/db.config.php'))
{ {
header ('Location:install/index.php'); header ('Location:install/index.php');
exit; exit;
} }
// Если в запросе пришел вызов thumbnail //-- Если в запросе пришел вызов thumbnail
// подключаем файл обработки thumbnail //-- подключаем файл обработки thumbnail
if (! empty($_REQUEST['thumb'])) if (! empty($_REQUEST['thumb']))
{ {
require (BASE_DIR . '/inc/thumb.php'); require (BASE_DIR . '/inc/thumb.php');
@ -32,41 +32,47 @@
ob_start(); ob_start();
// Подключаем файл определения мобильных устройств //-- Подключаем файл определения мобильных устройств
// далее пользуемся $MDetect //-- далее пользуемся $MDetect
require_once (BASE_DIR . '/lib/mobile_detect/Mobile_Detect.php'); require_once (BASE_DIR . '/lib/mobile_detect/Mobile_Detect.php');
$MDetect = new Mobile_Detect; $MDetect = new Mobile_Detect;
// Подключаем файл инициализации //-- Подключаем файл инициализации
require (BASE_DIR . '/inc/init.php'); require (BASE_DIR . '/inc/init.php');
unset ($GLOBALS['CMS_CONFIG']); unset ($GLOBALS['CMS_CONFIG']);
// Проверяем нет ли в запросе папки UPLOADS_DIR //-- Проверяем нет ли в запросе папки UPLOADS_DIR
// подключаем файл для работы thumbsnail //-- подключаем файл для работы thumbsnail
if (strpos ($_SERVER['REQUEST_URI'], ABS_PATH . UPLOAD_DIR . '/') === 0) if (strpos ($_SERVER['REQUEST_URI'], ABS_PATH . UPLOAD_DIR . '/') === 0)
{ {
require (BASE_DIR . '/inc/thumb.php'); require (BASE_DIR . '/inc/thumb.php');
exit; exit;
} }
// Папка с шаблонами для Smarty //-- Папка с шаблонами для Smarty
$AVE_Template = new AVE_Template(BASE_DIR . '/templates/'); $AVE_Template = new AVE_Template(BASE_DIR . '/templates/');
// Подключаем ядро системы //-- Подключаем ядро системы
require (BASE_DIR . '/class/class.core.php'); require (BASE_DIR . '/class/class.core.php');
$AVE_Core = new AVE_Core; $AVE_Core = new AVE_Core;
// Проверям на вызов внешних модулей и системных блоков //-- Проверям на вызов внешних модулей и системных блоков
if (empty ($_REQUEST['module']) || empty ($_REQUEST['sysblock']) || empty ($_REQUEST['request'])) if (
empty ($_REQUEST['module'])
||
empty ($_REQUEST['sysblock'])
||
empty ($_REQUEST['request'])
)
$AVE_Core->coreUrlParse($_SERVER['REQUEST_URI']); $AVE_Core->coreUrlParse($_SERVER['REQUEST_URI']);
$GLOBALS['page_id'] = array((isset($_REQUEST['id']) $GLOBALS['page_id'] = array((isset($_REQUEST['id'])
? $_REQUEST['id'] ? $_REQUEST['id']
: '') : '')
=> array('apage' => floatval(0))); => array('page' => floatval(0)));
// Если пришел вызов на показ ревизии документа //-- Если пришел вызов на показ ревизии документа
if (! empty($_REQUEST['revission'])) if (! empty($_REQUEST['revission']))
{ {
$res = $AVE_DB->Query(" $res = $AVE_DB->Query("
@ -86,7 +92,7 @@
$flds = get_document_fields((int)$_REQUEST['id'], $res); $flds = get_document_fields((int)$_REQUEST['id'], $res);
} }
// Собираем страницу //-- Собираем страницу
$AVE_Core->coreSiteFetch(get_current_document_id()); $AVE_Core->coreSiteFetch(get_current_document_id());
$content = ob_get_clean(); $content = ob_get_clean();
@ -98,20 +104,20 @@
else else
ob_start(); ob_start();
eval ('?>' . $content . '<?'); eval (' '.'?>' . $content . '<?'.'php ');
$render = ob_get_clean(); $render = ob_get_clean();
unset ($content); unset ($content);
// Ловим 404 ошибку //-- Ловим 404 ошибку
if (isset($_REQUEST['id']) AND ($_REQUEST['id']) == PAGE_NOT_FOUND_ID) if (isset($_REQUEST['id']) AND ($_REQUEST['id']) == PAGE_NOT_FOUND_ID)
{ {
report404(); report404();
header ($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true); header ($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true);
} }
// Постраничка //-- Постраничка
if ( if (
empty($_REQUEST['module']) && empty($_REQUEST['module']) &&
( (
@ -142,16 +148,16 @@
exit; exit;
} }
// Тут заменяем [tag:rubheader] //-- Тут заменяем [tag:rubheader]
// на собранный $GLOBALS["user_header"] //-- на собранный $GLOBALS["user_header"]
$rubheader = (empty($GLOBALS['user_header']) $rubheader = (empty($GLOBALS['user_header'])
? '' ? ''
: implode(chr(10), $GLOBALS['user_header'])); : implode(chr(10), $GLOBALS['user_header']));
$render = str_replace('[tag:rubheader]', $rubheader, $render); $render = str_replace('[tag:rubheader]', $rubheader, $render);
// Тут заменяем [tag:rubfooter] //-- Тут заменяем [tag:rubfooter]
// на собранный $GLOBALS["user_footer"] //-- на собранный $GLOBALS["user_footer"]
$rubfooter = (empty($GLOBALS['user_footer']) $rubfooter = (empty($GLOBALS['user_footer'])
? '' ? ''
: implode(chr(10), $GLOBALS['user_footer'])); : implode(chr(10), $GLOBALS['user_footer']));
@ -165,14 +171,16 @@
header('X-Engine-Copyright: 2007-' . date('Y') . ' (c) AVE.cms'); header('X-Engine-Copyright: 2007-' . date('Y') . ' (c) AVE.cms');
header('X-Engine-Site: https://ave-cms.ru'); header('X-Engine-Site: https://ave-cms.ru');
//Вывод статистики загрузки и запросов SQL (только для администраторов) //-- Вывод конечного результата
if (! defined('ONLYCONTENT') && UGROUP == 1 && defined('PROFILING') && PROFILING)
$render .= get_statistic(1, 1, 1, 1);
//Вывод конечного результата
output_compress($render); output_compress($render);
//Debug::_print($GLOBALS['block_generate']); //-- Вывод статистики загрузки и запросов SQL (только для администраторов)
if (
//$AVE_DB->showAllQueries(); ! defined('ONLYCONTENT')
&&
UGROUP == 1
&&
defined('PROFILING') && PROFILING
)
Debug::displayInfo();
?> ?>

26
install/data_base.sql

@ -248,7 +248,10 @@ INSERT INTO `%%PRFX%%_documents` VALUES
(2, 1, 0, 0, '404-not-found', '0', '404 - Документ не найден', 'Ошибка 404', 0, 0, 0, 1, '0', '', '', 'noindex,nofollow', '6', '0', '1', '0', 0, 0, 0, '', '', 'ru', '2', '');#inst# (2, 1, 0, 0, '404-not-found', '0', '404 - Документ не найден', 'Ошибка 404', 0, 0, 0, 1, '0', '', '', 'noindex,nofollow', '6', '0', '1', '0', 0, 0, 0, '', '', 'ru', '2', '');#inst#
INSERT INTO `%%PRFX%%_navigation` VALUES INSERT INTO `%%PRFX%%_navigation` VALUES
(1, 'main', 'Основное меню', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '1,2,3,4,5', '1');#inst# (1,'main','Основное меню','<li class=\"nav-item\">\n <a class=\"nav-link\" href=\"[tag:link]\">[tag:linkname]</a>\n</li>','','','<li class=\"nav-item active\">\n <a class=\"nav-link\" href=\"[tag:link]\">[tag:linkname]</a>\n</li>','','','<ul class=\"navbar-nav mr-auto\">\n[tag:content]\n</ul>','','','','','','','','1,2,3,4,5','1');#inst#
INSERT INTO `%%PRFX%%_navigation_items` VALUES
(1,1,1,'/','Главная','','_self','','','','',0,'1',0,'1');#inst#
INSERT INTO `%%PRFX%%_rubric_fields` VALUES INSERT INTO `%%PRFX%%_rubric_fields` VALUES
(1, 1, 0, 'header', 'Заголовок', 'single_line', 0, 1, '', '', '', '', ''), (1, 1, 0, 'header', 'Заголовок', 'single_line', 0, 1, '', '', '', '', ''),
@ -262,7 +265,7 @@ INSERT INTO `%%PRFX%%_rubric_permissions` VALUES
(5, 1, 5, 'docread');#inst# (5, 1, 5, 'docread');#inst#
INSERT INTO `%%PRFX%%_rubrics` VALUES INSERT INTO `%%PRFX%%_rubrics` VALUES
(1, 'Основные страницы', '', '0', '<h1>[tag:fld:header]</h1>[tag:fld:text]', 1, 1, 0, 1, '', '', '', '', '', '', '', '0', '', '0', '');#inst# (1,'Основные страницы','','0','<h1 class=\"mt-5\">[tag:fld:header]</h1>\n[tag:fld:text]',1,1,0,1,'','','','','','','','0','','0',0);#inst#
INSERT INTO `%%PRFX%%_settings` VALUES INSERT INTO `%%PRFX%%_settings` VALUES
( (
@ -280,9 +283,9 @@ INSERT INTO `%%PRFX%%_settings` VALUES
'%%EMAIL%%', '%%EMAIL%%',
'%%USERNAME%%', '%%USERNAME%%',
'Здравствуйте %NAME%,\r\nВаша регистрация на сайте %HOST%. \r\n\r\nТеперь Вы можете войти на %HOST% со следующими данными:: \r\n\r\nПароль: %PASSWORD%\r\nE-Mail: %EMAIL%\r\n\r\n--------------------------------------------------\r\n%EMAILSIGNATURE%\r\n\r\n', 'Здравствуйте %NAME%,\r\nВаша регистрация на сайте %HOST%. \r\n\r\nТеперь Вы можете войти на %HOST% со следующими данными:: \r\n\r\nПароль: %PASSWORD%\r\nE-Mail: %EMAIL%\r\n\r\n--------------------------------------------------\r\n%EMAILSIGNATURE%\r\n\r\n',
'С уважением,\r\nслужба поддержки AVE.CMS\r\nsupport@ave-cms.ru | www.ave-cms.ru', 'С уважением,\r\nслужба поддержки',
'2', '2',
'<h2>Ошибка...</h2>\r\n<br />\r\nУ Вас нет прав на просмотр этого документа!.', '<h2>Ошибка...</h2>\r\n<p>\r\nУ Вас нет прав на просмотр этого документа!.\r\n</p>',
'<ul class=\"page_nav\">%s</ul>', '<ul class=\"page_nav\">%s</ul>',
'Первая «', 'Первая «',
'» Последняя', '» Последняя',
@ -299,22 +302,22 @@ INSERT INTO `%%PRFX%%_settings` VALUES
'0', '0',
'<li>&nbsp;&rarr;&nbsp;</li>', '<li>&nbsp;&rarr;&nbsp;</li>',
'0', '0',
'<li itemprop=\"itemListElement\" itemscope itemtype=\"http://schema.org/ListItem\">%s</li>', '<li class="breadcrumb-item" itemprop=\"itemListElement\" itemscope itemtype=\"http://schema.org/ListItem\">%s</li>',
'<a itemprop=\"item\" href=\"[link]\"><span itemprop=\"name\">[name]</span></a><meta itemprop=\"position\" content=\"[count]\" />', '<a itemprop=\"item\" href=\"[link]\"><span itemprop=\"name\">[name]</span></a><meta itemprop=\"position\" content=\"[count]\" />',
'<li class=\"active\">%s</li>', '<li class=\"breadcrumb-item active\">%s</li>',
'1', '1',
'%d %B %Y', '%d %B %Y',
'%d %B %Y, %H:%M', '%d %B %Y, %H:%M',
'RU', 'RU',
'0', '0',
'0', '0',
'<div class=\"hidden_box\">\n Содержимое скрыто. Пожалуйста, <a href=\"index.php?module=login&action=register\">зарегистрируйтесь</a>\n</div>' '<div class=\"hidden_box\">\n Содержимое скрыто.\n</div>'
);#inst# );#inst#
INSERT INTO `%%PRFX%%_settings_lang` VALUES INSERT INTO `%%PRFX%%_settings_lang` VALUES
(1, 'ru', 'Русский', 'ru', '1', '1'), (1, 'ru', 'Русский', 'ru', '1', '1'),
(2, 'en', 'English', 'en', '0', '1'), (2, 'en', 'English', 'en', '0', '0'),
(3, 'ua', 'Українська', 'ua', '0', '1'), (3, 'ua', 'Українська', 'ua', '0', '0'),
(4, 'de', 'Deutsch', 'de', '0', '0'), (4, 'de', 'Deutsch', 'de', '0', '0'),
(5, 'it', 'Italian', 'it', '0', '0'), (5, 'it', 'Italian', 'it', '0', '0'),
(6, 'fr', 'France', 'fr', '0', '0'), (6, 'fr', 'France', 'fr', '0', '0'),
@ -325,14 +328,13 @@ INSERT INTO `%%PRFX%%_settings_lang` VALUES
(11, 'bg', 'Български', 'bg', '0', '0');#inst# (11, 'bg', 'Български', 'bg', '0', '0');#inst#
INSERT INTO `%%PRFX%%_templates` VALUES INSERT INTO `%%PRFX%%_templates` VALUES
(1, 'Основной шаблон', '<!DOCTYPE html>\n<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\" lang=\\\"ru\\\">\n <head>\n <title>[tag:title] - [tag:sitename]</title>\n\n <meta http-equiv=\\\"content-type\\\" content=\\\"text/html; charset=UTF-8\\\" />\n\n <meta name=\\\"robots\\\" content=\\\"[tag:robots]\\\" />\n <meta name=\\\"keywords\\\" content=\\\"[tag:keywords]\\\" />\n <meta name=\\\"description\\\" content=\\\"[tag:description]\\\" />\n\n <link href=\\\"[tag:canonical]\\\" rel=\\\"canonical\\\" />\n\n <link rel=\\\"stylesheet\\\" href=\\\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css\\\" />\n <link rel=\\\"stylesheet\\\" href=\\\"[tag:mediapath]css/styles.css\\\" />\n\n [tag:rubheader]\n\n </head>\n <body>\n\n <div class=\\\"container\\\">\n <div class=\\\"row\\\">\n <!--Page content-->\n <div class=\\\"col-md-12\\\">\n [tag:maincontent]\n </div>\n </div>\n </div>\n\n <script src=\\\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\\\"></script>\n <script src=\\\"https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.0/jquery-migrate.min.js\\\"></script>\n <script src=\\\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js\\\"></script>\n <script src=\\\"[tag:mediapath]js/main.js\\\"></script>\n </body>\n</html>', 1, 0);#inst# (1,'Основной шаблон','<!DOCTYPE html>\n<html lang=\\\"ru\\\">\n <head>\n <meta charset=\\\"utf-8\\\">\n\n <meta name=\\\"robots\\\" content=\\\"[tag:robots]\\\">\n <meta name=\\\"keywords\\\" content=\\\"[tag:keywords]\\\">\n <meta name=\\\"description\\\" content=\\\"[tag:description]\\\">\n\n <meta name=\\\"viewport\\\" content=\\\"width=device-width, initial-scale=1, shrink-to-fit=no\\\">\n\n <link href=\\\"[tag:canonical]\\\" rel=\\\"canonical\\\">\n\n <!-- Bootstrap CSS -->\n <link rel=\\\"stylesheet\\\" href=\\\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\\\">\n <!-- Font awesome CSS -->\n <link rel=\\\"stylesheet\\\" href=\\\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\\\">\n <!-- Custom styles -->\n <link rel=\\\"stylesheet\\\" href=\\\"[tag:mediapath]css/styles.css\\\">\n\n [tag:rubheader]\n\n <title>[tag:title] - [tag:sitename]</title>\n </head>\n <body>\n <!--Header-->\n <header>\n <nav class=\\\"navbar navbar-expand-md navbar-dark fixed-top bg-dark\\\">\n <a class=\\\"navbar-brand\\\" href=\\\"[tag:path]\\\">[tag:sitename]</a>\n <button class=\\\"navbar-toggler\\\" type=\\\"button\\\" data-toggle=\\\"collapse\\\" data-target=\\\"#navbarCollapse\\\" aria-controls=\\\"navbarCollapse\\\" aria-expanded=\\\"false\\\" aria-label=\\\"Toggle navigation\\\">\n <span class=\\\"navbar-toggler-icon\\\"></span>\n </button>\n <div class=\\\"collapse navbar-collapse\\\" id=\\\"navbarCollapse\\\">\n [tag:navigation:main]\n </div>\n </nav>\n </header><!--./Header-->\n\n <!--Page content-->\n <main role=\\\"main\\\" class=\\\"container\\\">\n <div class=\\\"row\\\">\n <div class=\\\"col-12\\\">\n [tag:maincontent]\n </div>\n </div>\n </main><!--./Page content-->\n\n <!--Footer-->\n <footer class=\\\"footer\\\">\n <div class=\\\"container\\\">\n <span class=\\\"text-muted\\\">Создано при помощи [tag:version]</span>\n </div>\n </footer><!--./Footer-->\n\n <!-- JavaScript\n ================================================== -->\n <script src=\\\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\\\"></script>\n <script src=\\\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js\\\"></script>\n <script src=\\\"https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js\\\"></script>\n <script src=\\\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\\\"></script>\n <script src=\\\"[tag:mediapath]js/main.js\\\"></script>\n\n [tag:rubfooter]\n </body>\n</html>',1,0);#inst#
INSERT INTO `%%PRFX%%_user_groups` VALUES INSERT INTO `%%PRFX%%_user_groups` VALUES
(1, 'Администраторы', '1', '0', '', 'alles'), (1, 'Администраторы', '1', '0', '', 'alles'),
(2, 'Анонимные пользователи', '1', '0', '', ''), (2, 'Анонимные пользователи', '1', '0', '', ''),
(3, 'Модераторы', '1', '0', '', ''), (3, 'Модераторы', '1', '0', '', ''),
(4, 'Зарегистрированные', '1', '0', '', ''), (4, 'Зарегистрированные', '1', '0', '', '');#inst#
(5, 'Через логинзу', '1', '0', '', '');#inst#
INSERT INTO `%%PRFX%%_users` VALUES INSERT INTO `%%PRFX%%_users` VALUES
(1, '%%PASS%%', '%%EMAIL%%', '', '', '', '', '', '', '', '', '', '%%USERNAME%%', 1, '', '', '1', '', 'RU', '', '0', '0', '0', '0', '', '', '', '%%SALT%%', '', 0);#inst# (1, '%%PASS%%', '%%EMAIL%%', '', '', '', '', '', '', '', '', '', '%%USERNAME%%', 1, '', '', '1', '', 'RU', '', '0', '0', '0', '0', '', '', '', '%%SALT%%', '', 0);#inst#

219
install/index.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
@ -11,42 +11,42 @@
* @license GPL v.2 * @license GPL v.2
*/ */
/** /**
* Функции * Функции
*/ */
function check_mysql_connect($dbhost = '', $dbuser = '', $dbpass = '') function check_mysql_connect($dbhost = '', $dbuser = '', $dbpass = '')
{ {
if ($dbhost != '' && $dbuser != '') if ($dbhost != '' && $dbuser != '')
{ {
if (@mysqli_connect($dbhost, $dbuser, $dbpass)) return true; if (@mysqli_connect($dbhost, $dbuser, $dbpass)) return true;
} }
return false; return false;
} }
function check_mysql_query($link = '', $sql = '') function check_mysql_query($link = '', $sql = '')
{ {
if ($sql != '' && $link != '') if ($sql != '' && $link != '')
{ {
if (@mysqli_query($link, $sql)) return true; if (@mysqli_query($link, $sql)) return true;
} }
return false; return false;
} }
function check_db_connect($dbhost = '', $dbuser = '', $dbpass = '', $dbname = '') function check_db_connect($dbhost = '', $dbuser = '', $dbpass = '', $dbname = '')
{ {
if ($dbhost != '' && $dbuser != '' && $dbname != '') if ($dbhost != '' && $dbuser != '' && $dbname != '')
{ {
if (@mysqli_select_db(@mysqli_connect($dbhost, $dbuser, $dbpass), $dbname)) return true; if (@mysqli_select_db(@mysqli_connect($dbhost, $dbuser, $dbpass), $dbname)) return true;
} }
return false; return false;
} }
function check_installed($prefix) function check_installed($prefix)
{ {
global $config; global $config;
$mysql = @mysqli_connect($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']); $mysql = @mysqli_connect($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']);
@ -54,10 +54,10 @@ function check_installed($prefix)
if (@mysqli_num_rows($query)) return true; if (@mysqli_num_rows($query)) return true;
else return false; else return false;
} }
function check_required() function check_required()
{ {
global $error_is_required, $lang_i; global $error_is_required, $lang_i;
$required_php = 522; $required_php = 522;
@ -81,28 +81,29 @@ function check_required()
array_push($error_is_required, $lang_i['phpversion_toold'] . $required_php); array_push($error_is_required, $lang_i['phpversion_toold'] . $required_php);
} }
} }
} }
function check_writable() function check_writable()
{ {
global $error_is_required, $lang_i; global $error_is_required, $lang_i;
$writeable = array(); $writeable = array();
$writeable[] = '/cache/'; $writeable[] = '/tmp/';
$writeable[] = '/tmp/cache/';
$writeable[] = '/uploads/'; $writeable[] = '/uploads/';
$writeable[] = '/inc/db.config.php'; $writeable[] = '/config/db.config.php';
foreach ($writeable as $must_writeable) foreach ($writeable as $must_writeable)
{ {
if (!is_writable(BASE_DIR . $must_writeable)) if (! is_writable(BASE_DIR . $must_writeable))
{ {
array_push($error_is_required, $lang_i['error_is_writeable'] . $must_writeable . $lang_i['error_is_writeable_2'] ); array_push($error_is_required, $lang_i['error_is_writeable'] . $must_writeable . $lang_i['error_is_writeable_2'] );
} }
} }
} }
function clean_db ($name="", $prefix="", $mysql_connect) function clean_db ($name="", $prefix="", $mysql_connect)
{ {
@mysqli_select_db($mysql_connect, $name); @mysqli_select_db($mysql_connect, $name);
$query = @mysqli_query($mysql_connect, "SHOW TABLES FROM " . $name); $query = @mysqli_query($mysql_connect, "SHOW TABLES FROM " . $name);
@ -113,16 +114,16 @@ function clean_db ($name="", $prefix="", $mysql_connect)
@mysqli_query($mysql_connect ,"DROP TABLE " . $row[0]); @mysqli_query($mysql_connect ,"DROP TABLE " . $row[0]);
} }
} }
} }
/** /**
* Convert size from 10M to bytes * Convert size from 10M to bytes
* *
* @param string $str e.g. 10M * @param string $str e.g. 10M
* @return int * @return int
*/ */
function convertSizeToBytes($str) function convertSizeToBytes($str)
{ {
$str = trim($str); $str = trim($str);
if (strlen($str) > 0) if (strlen($str) > 0)
{ {
@ -145,14 +146,14 @@ function convertSizeToBytes($str)
$size = 0; $size = 0;
} }
return $size; return $size;
} }
/** /**
* Get GD version * Get GD version
* @return string * @return string
*/ */
function getGdVersion() function getGdVersion()
{ {
if (function_exists('gd_info')) if (function_exists('gd_info'))
{ {
$gd_info = @gd_info(); $gd_info = @gd_info();
@ -160,33 +161,33 @@ function getGdVersion()
} }
return NULL; return NULL;
} }
/** /**
* Get PCRE version * Get PCRE version
* @return string * @return string
*/ */
function getPcreVersion() function getPcreVersion()
{ {
defined('PCRE_VERSION') defined('PCRE_VERSION')
? list($version) = explode(' ', constant('PCRE_VERSION')) ? list($version) = explode(' ', constant('PCRE_VERSION'))
: $version = NULL; : $version = NULL;
return $version; return $version;
} }
/** /**
* Get MySQL version * Get MySQL version
* @return string * @return string
*/ */
function getMySQLVersion() { function getMySQLVersion() {
$output = mysqli_get_client_info(); $output = mysqli_get_client_info();
preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $output, $version); preg_match('@[0-9]+\.[0-9]+\.[0-9]+@', $output, $version);
return $version[0]; return $version[0];
} }
function check_param($level, $text) function check_param($level, $text)
{ {
$level = intval($level); $level = intval($level);
switch ($level) switch ($level)
@ -209,93 +210,94 @@ function check_param($level, $text)
break; break;
} }
return $img; return $img;
} }
/** /**
* @subpackage install * @subpackage install
*/ */
error_reporting(E_ERROR); error_reporting(E_ERROR);
ini_set('display_errors', 7); ini_set('display_errors', 7);
global $config; global $config;
ob_start(); ob_start();
define('SETUP', 1); define('SETUP', 1);
define('BASE_DIR', str_replace("\\", "/", dirname(dirname(__FILE__)))); define('BASE_DIR', str_replace("\\", "/", dirname(dirname(__FILE__))));
if (!is_writable(BASE_DIR . '/cache/smarty/')) die('Cache folder is not writeable!'); if (! is_writable(BASE_DIR . '/cache/smarty/'))
die('Cache folder is not writeable!');
include(BASE_DIR . '/inc/db.config.php'); include(BASE_DIR . '/config/db.config.php');
include(BASE_DIR . '/inc/config.php'); include(BASE_DIR . '/inc/config.php');
include(BASE_DIR . '/functions/func.common.php'); include(BASE_DIR . '/functions/func.common.php');
include(BASE_DIR . '/functions/func.helpers.php'); include(BASE_DIR . '/functions/func.helpers.php');
include(BASE_DIR . '/class/class.template.php'); include(BASE_DIR . '/class/class.template.php');
$AVE_Template = new AVE_Template(BASE_DIR . '/install/tpl/'); $AVE_Template = new AVE_Template(BASE_DIR . '/install/tpl/');
$lang_file = BASE_DIR . '/install/lang/ru.txt'; $lang_file = BASE_DIR . '/install/lang/ru.txt';
$AVE_Template->config_load($lang_file); $AVE_Template->config_load($lang_file);
$ver = APP_NAME . ' v' . APP_VERSION; $ver = APP_NAME . ' v' . APP_VERSION;
$db_connect = check_db_connect($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']); $db_connect = check_db_connect($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']);
$check_installed = check_installed($config['dbpref']); $check_installed = check_installed($config['dbpref']);
if ((true === $db_connect) && $_REQUEST['step'] != 'finish' && check_installed($config['dbpref'])) { if ((true === $db_connect) && $_REQUEST['step'] != 'finish' && check_installed($config['dbpref'])) {
echo '<pre>' . $AVE_Template->get_config_vars('installed') . '</pre>'; echo '<pre>' . $AVE_Template->get_config_vars('installed') . '</pre>';
exit; exit;
}; };
$error_is_required = array(); $error_is_required = array();
check_required(); check_required();
check_writable(); check_writable();
// include_once(BASE_DIR . '/inc/errors.php'); // include_once(BASE_DIR . '/inc/errors.php');
$count_error = sizeof((array) $error_is_required); $count_error = sizeof((array) $error_is_required);
if (1 == $count_error) if (1 == $count_error)
{ {
$AVE_Template->assign('error_header', $AVE_Template->get_config_vars('erroro')); $AVE_Template->assign('error_header', $AVE_Template->get_config_vars('erroro'));
} }
elseif ($count_error > 1) elseif ($count_error > 1)
{ {
$AVE_Template->assign('error_header', $AVE_Template->get_config_vars('erroro_more')); $AVE_Template->assign('error_header', $AVE_Template->get_config_vars('erroro_more'));
} }
if ($count_error > 0 && ! (isset($_REQUEST['force']) && 1 == $_REQUEST['force'])) if ($count_error > 0 && ! (isset($_REQUEST['force']) && 1 == $_REQUEST['force']))
{ {
$AVE_Template->assign('error_is_required', $error_is_required); $AVE_Template->assign('error_is_required', $error_is_required);
$AVE_Template->display('error.tpl'); $AVE_Template->display('error.tpl');
exit; exit;
} }
$_REQUEST['step'] = isset($_REQUEST['step']) ? $_REQUEST['step'] : ''; $_REQUEST['step'] = isset($_REQUEST['step']) ? $_REQUEST['step'] : '';
// Минимальные требования к системе // Минимальные требования к системе
define('PHP_version', '5.5'); define('PHP_version', '5.6');
define('MySQL_version', '5.0.0'); define('MySQL_version', '5.0.0');
define('GD_version', '2.0'); define('GD_version', '2.0');
define('PCRE_version', '7.0'); define('PCRE_version', '7.0');
define('JSON', $AVE_Template->get_config_vars('mess_on')); define('JSON', $AVE_Template->get_config_vars('mess_on'));
define('MbString', $AVE_Template->get_config_vars('mess_on')); define('MbString', $AVE_Template->get_config_vars('mess_on'));
define('SimpleXML', $AVE_Template->get_config_vars('mess_on')); define('SimpleXML', $AVE_Template->get_config_vars('mess_on'));
define('Iconv', $AVE_Template->get_config_vars('mess_on')); define('Iconv', $AVE_Template->get_config_vars('mess_on'));
define('XSLT', $AVE_Template->get_config_vars('mess_supported')); define('XSLT', $AVE_Template->get_config_vars('mess_supported'));
define('Data_limit', '2'); // Mb define('Data_limit', '2'); // Mb
define('TIME_limit', '30'); // Sec define('TIME_limit', '30'); // Sec
define('DISC_space', '30'); // Mb define('DISC_space', '30'); // Mb
define('RAM_space', '32M'); // Mb define('RAM_space', '32M'); // Mb
define('SAFE_MODE', $AVE_Template->get_config_vars('mess_off')); define('SAFE_MODE', $AVE_Template->get_config_vars('mess_off'));
define('REGISTER_GLOBALS', $AVE_Template->get_config_vars('mess_off')); define('REGISTER_GLOBALS', $AVE_Template->get_config_vars('mess_off'));
define('MAGIC_QUOTES_GPC', $AVE_Template->get_config_vars('mess_off')); define('MAGIC_QUOTES_GPC', $AVE_Template->get_config_vars('mess_off'));
switch ($_REQUEST['step']) switch ($_REQUEST['step'])
{ {
//Начало //Начало
case '' : case '' :
@ -395,14 +397,14 @@ switch ($_REQUEST['step'])
if (true === $connect && false === $check_installed) if (true === $connect && false === $check_installed)
{ {
if (! @is_writeable(BASE_DIR . '/inc/db.config.php')) if (! @is_writeable(BASE_DIR . '/config/db.config.php'))
{ {
$AVE_Template->assign('config_isnt_writeable', 1); $AVE_Template->assign('config_isnt_writeable', 1);
$AVE_Template->display('error.tpl'); $AVE_Template->display('error.tpl');
exit; exit;
} }
$fp = @fopen(BASE_DIR . '/inc/db.config.php', 'w+'); $fp = @fopen(BASE_DIR . '/config/db.config.php', 'w+');
@fwrite($fp, "<?php\n" @fwrite($fp, "<?php\n"
. "\$config = array();\n" . "\$config = array();\n"
. "\$config['dbhost'] = \"" . stripslashes(trim($_POST['dbhost'])) . "\";\n" . "\$config['dbhost'] = \"" . stripslashes(trim($_POST['dbhost'])) . "\";\n"
@ -503,12 +505,6 @@ switch ($_REQUEST['step'])
$dbin = str_replace('%%FIRSTNAME%%', $_POST['firstname'], $dbin); $dbin = str_replace('%%FIRSTNAME%%', $_POST['firstname'], $dbin);
$dbin = str_replace('%%LASTNAME%%', $_POST['lastname'], $dbin); $dbin = str_replace('%%LASTNAME%%', $_POST['lastname'], $dbin);
$dbin = str_replace('%%USERNAME%%', $_POST['username'], $dbin); $dbin = str_replace('%%USERNAME%%', $_POST['username'], $dbin);
$dbin = str_replace('%%PHONE%%', $_POST['fon'], $dbin);
$dbin = str_replace('%%FAX%%', $_POST['fax'], $dbin);
$dbin = str_replace('%%ZIP%%', $_POST['zip'], $dbin);
$dbin = str_replace('%%TOWN%%', $_POST['town'], $dbin);
$dbin = str_replace('%%STREET%%', $_POST['street'], $dbin);
$dbin = str_replace('%%HNR%%', $_POST['hnr'], $dbin);
$ar = explode('#inst#', $dbin); $ar = explode('#inst#', $dbin);
@ -518,16 +514,15 @@ switch ($_REQUEST['step'])
@mysqli_query($mysql_connect, "SET COLLATION_CONNECTION = 'utf8_general_ci'"); @mysqli_query($mysql_connect, "SET COLLATION_CONNECTION = 'utf8_general_ci'");
@mysqli_query($mysql_connect, $in); @mysqli_query($mysql_connect, $in);
} }
/* /*
$auth = base64_encode(serialize(array('id' => '1', 'hash'=>$hash))); $auth = base64_encode(serialize(array('id' => '1', 'hash'=>$hash)));
@setcookie('auth', $auth); @setcookie('auth', $auth);
*/ */
$AVE_Template->display('step6.tpl'); $AVE_Template->display('step6.tpl');
exit; exit;
} }
$AVE_Template->display('step5.tpl'); $AVE_Template->display('step5.tpl');
break; break;
} }
?> ?>

19
install/structure_base.sql

@ -30,6 +30,7 @@ CREATE TABLE `%%PRFX%%_document_fields` (
PRIMARY KEY (`Id`), PRIMARY KEY (`Id`),
KEY `document_id` (`document_id`), KEY `document_id` (`document_id`),
KEY `field_value` (`field_value`), KEY `field_value` (`field_value`),
KEY `field_number_value` (`field_number_value`),
KEY `rubric_field_id` (`rubric_field_id`) KEY `rubric_field_id` (`rubric_field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst# ) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
@ -81,17 +82,17 @@ CREATE TABLE `%%PRFX%%_documents` (
`rubric_id` mediumint(5) unsigned NOT NULL DEFAULT '0', `rubric_id` mediumint(5) unsigned NOT NULL DEFAULT '0',
`rubric_tmpl_id` mediumint(5) unsigned NOT NULL DEFAULT '0', `rubric_tmpl_id` mediumint(5) unsigned NOT NULL DEFAULT '0',
`document_parent` int(10) unsigned NOT NULL DEFAULT '0', `document_parent` int(10) unsigned NOT NULL DEFAULT '0',
`document_alias` varchar(255) NOT NULL, `document_alias` varchar(255) NOT NULL DEFAULT '',
`document_alias_history` enum('0','1','2') NOT NULL DEFAULT '0', `document_alias_history` enum('0','1','2') NOT NULL DEFAULT '0',
`document_title` varchar(255) NOT NULL, `document_title` varchar(255) NOT NULL DEFAULT '',
`document_breadcrum_title` varchar(255) NOT NULL, `document_breadcrum_title` varchar(255) NOT NULL DEFAULT '',
`document_published` int(10) unsigned NOT NULL DEFAULT '0', `document_published` int(10) unsigned NOT NULL DEFAULT '0',
`document_expire` int(10) unsigned NOT NULL DEFAULT '0', `document_expire` int(10) unsigned NOT NULL DEFAULT '0',
`document_changed` int(10) unsigned NOT NULL DEFAULT '0', `document_changed` int(10) unsigned NOT NULL DEFAULT '0',
`document_author_id` mediumint(5) unsigned NOT NULL DEFAULT '1', `document_author_id` mediumint(5) unsigned NOT NULL DEFAULT '1',
`document_in_search` enum('1','0') NOT NULL DEFAULT '1', `document_in_search` enum('1','0') NOT NULL DEFAULT '1',
`document_meta_keywords` text NOT NULL, `document_meta_keywords` text NOT NULL DEFAULT '',
`document_meta_description` text NOT NULL, `document_meta_description` text NOT NULL DEFAULT '',
`document_meta_robots` enum('index,follow','index,nofollow','noindex,nofollow') NOT NULL DEFAULT 'index,follow', `document_meta_robots` enum('index,follow','index,nofollow','noindex,nofollow') NOT NULL DEFAULT 'index,follow',
`document_sitemap_freq` tinyint(1) NOT NULL DEFAULT '3', `document_sitemap_freq` tinyint(1) NOT NULL DEFAULT '3',
`document_sitemap_pr` float NOT NULL DEFAULT '0.5', `document_sitemap_pr` float NOT NULL DEFAULT '0.5',
@ -100,14 +101,15 @@ CREATE TABLE `%%PRFX%%_documents` (
`document_count_print` int(10) unsigned NOT NULL DEFAULT '0', `document_count_print` int(10) unsigned NOT NULL DEFAULT '0',
`document_count_view` int(10) unsigned NOT NULL DEFAULT '0', `document_count_view` int(10) unsigned NOT NULL DEFAULT '0',
`document_linked_navi_id` mediumint(5) unsigned NOT NULL DEFAULT '0', `document_linked_navi_id` mediumint(5) unsigned NOT NULL DEFAULT '0',
`document_teaser` text NOT NULL, `document_teaser` text NOT NULL DEFAULT '',
`document_tags` text NOT NULL, `document_tags` text NOT NULL DEFAULT '',
`document_lang` varchar(5) NOT NULL, `document_lang` varchar(5) NOT NULL DEFAULT '',
`document_lang_group` int(10) NOT NULL DEFAULT '0', `document_lang_group` int(10) NOT NULL DEFAULT '0',
`document_property` text, `document_property` text,
PRIMARY KEY (`Id`), PRIMARY KEY (`Id`),
UNIQUE KEY `document_alias` (`document_alias`), UNIQUE KEY `document_alias` (`document_alias`),
KEY `rubric_id` (`rubric_id`), KEY `rubric_id` (`rubric_id`),
KEY `document_parent` (`document_parent`),
KEY `document_status` (`document_status`), KEY `document_status` (`document_status`),
KEY `document_published` (`document_published`), KEY `document_published` (`document_published`),
KEY `document_expire` (`document_expire`) KEY `document_expire` (`document_expire`)
@ -152,6 +154,7 @@ CREATE TABLE `%%PRFX%%_module` (
CREATE TABLE `%%PRFX%%_modules_aliases` ( CREATE TABLE `%%PRFX%%_modules_aliases` (
`id` tinyint(5) unsigned NOT NULL AUTO_INCREMENT, `id` tinyint(5) unsigned NOT NULL AUTO_INCREMENT,
`document_id` int(10) NOT NULL DEFAULT '0',
`module_name` char(50) NOT NULL DEFAULT '', `module_name` char(50) NOT NULL DEFAULT '',
`module_action` varchar(255) NOT NULL DEFAULT '', `module_action` varchar(255) NOT NULL DEFAULT '',
`module_link` varchar(500) NOT NULL DEFAULT '', `module_link` varchar(500) NOT NULL DEFAULT '',

48
lib/debug/debug.css

@ -0,0 +1,48 @@
/* == Debug Panel == */
#debug-panel {
font-size: 12px;
opacity: 0.9;
position: fixed;
bottom: 0;
left: 0;
z-index: 2000;
width: 100%;
}
#debug-panel .debug-wrapper {
padding: 0px .875em;
background-color: #fff;
border: 1px solid rgba(0,0,0,0.2);
border-bottom: 0;
margin: 0px auto 0px auto;
}
#debug-panel .items {
padding: 10px;
height: 350px;
padding-top: 1em;
font-size: 12px;
color: #888;
font-family: Monaco, Menlo, Consolas, "Courier New", monospace
}
#debug-panel .debug-wrapper .legend {
background-color: #f9f9f9;
padding: .25em;
border: 1px solid rgba(0,0,0,0.2);
width: auto;
margin-top: -1.25em;
}
#debug-panel .debug-wrapper .legend span {
color: #999;
font-weight: 300
}
#debug-panel a {
text-decoration: none;
color: rgba(0,0,0,0.5);
font-size: 12px;
margin: 0 .25em;
}
#debug-panel pre {
border: 0px;
}
#debugArrowMinimize {
float: right;
}

30
lib/debug/debug.js

@ -0,0 +1,30 @@
function appExpandTabs(act, key) {
var arrDebugTabs = ["General", "Params", "Globals", "Queries", "SqlTrace"];
keyTab = (key == null)
? "General"
: key;
for (var i = 0; i < arrDebugTabs.length; i++) {
if (act == "min" || arrDebugTabs[i] != keyTab) {
$("#content" + arrDebugTabs[i]).css("display", "none");
$("#tab" + arrDebugTabs[i]).css("color", "#bbb")
}
}
if (act != "min") {
$("#content" + keyTab).css("display", "");
$("#content" + keyTab).css({
"overflow-y": "auto"
});
$("#tab" + keyTab).css("color", "#222")
}
$("#debug-panel").css("opacity", (act == "min") ? "0.9" : "1");
};
function appTabsHide()
{
$('#debug-panel-legend span a').css("color", "#bbb");
$("#debug-panel .items").hide();
}

1077
lib/debug/sql.php

File diff suppressed because it is too large Load Diff

4
lib/redactor/codemirror/addon/comment/comment.js vendored

@ -172,10 +172,6 @@
if (open == -1) return false if (open == -1) return false
var endLine = end == start ? startLine : self.getLine(end) var endLine = end == start ? startLine : self.getLine(end)
var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
if (close == -1 && start != end) {
endLine = self.getLine(--end);
close = endLine.indexOf(endString);
}
var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1) var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1)
if (close == -1 || if (close == -1 ||
!/comment/.test(self.getTokenTypeAt(insideStart)) || !/comment/.test(self.getTokenTypeAt(insideStart)) ||

1
lib/redactor/codemirror/addon/display/placeholder.js vendored

@ -38,6 +38,7 @@
clearPlaceholder(cm); clearPlaceholder(cm);
var elt = cm.state.placeholder = document.createElement("pre"); var elt = cm.state.placeholder = document.createElement("pre");
elt.style.cssText = "height: 0; overflow: visible"; elt.style.cssText = "height: 0; overflow: visible";
elt.style.direction = cm.getOption("direction");
elt.className = "CodeMirror-placeholder"; elt.className = "CodeMirror-placeholder";
var placeHolder = cm.getOption("placeholder") var placeHolder = cm.getOption("placeholder")
if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder) if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)

26
lib/redactor/codemirror/addon/edit/closebrackets.js vendored

@ -129,11 +129,12 @@
else else
curType = "skip"; curType = "skip";
} else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
(cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) { if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
curType = "addFour"; curType = "addFour";
} else if (identical) { } else if (identical) {
if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both"; var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
else return CodeMirror.Pass; else return CodeMirror.Pass;
} else if (opening && (cm.getLine(cur.line).length == cur.ch || } else if (opening && (cm.getLine(cur.line).length == cur.ch ||
isClosingBracket(next, pairs) || isClosingBracket(next, pairs) ||
@ -185,24 +186,9 @@
return str.length == 2 ? str : null; return str.length == 2 ? str : null;
} }
// Project the token type that will exists after the given char is
// typed, and use it to determine whether it would cause the start
// of a string token.
function enteringString(cm, pos, ch) {
var line = cm.getLine(pos.line);
var token = cm.getTokenAt(pos);
if (/\bstring2?\b/.test(token.type) || stringStartsAfter(cm, pos)) return false;
var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
stream.pos = stream.start = token.start;
for (;;) {
var type1 = cm.getMode().token(stream, token.state);
if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
stream.start = stream.pos;
}
}
function stringStartsAfter(cm, pos) { function stringStartsAfter(cm, pos) {
var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
return /\bstring/.test(token.type) && token.start == pos.ch return /\bstring/.test(token.type) && token.start == pos.ch &&
(pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
} }
}); });

10
lib/redactor/codemirror/addon/edit/closetag.js vendored

@ -53,13 +53,14 @@
function autoCloseGT(cm) { function autoCloseGT(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass; if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), replacements = []; var ranges = cm.listSelections(), replacements = [];
var opt = cm.getOption("autoCloseTags");
for (var i = 0; i < ranges.length; i++) { for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass; if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos); var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass; if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass;
var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var html = inner.mode.configuration == "html";
var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
@ -81,13 +82,14 @@
newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)}; newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};
} }
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnAutoClose);
for (var i = ranges.length - 1; i >= 0; i--) { for (var i = ranges.length - 1; i >= 0; i--) {
var info = replacements[i]; var info = replacements[i];
cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert"); cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert");
var sel = cm.listSelections().slice(0); var sel = cm.listSelections().slice(0);
sel[i] = {head: info.newPos, anchor: info.newPos}; sel[i] = {head: info.newPos, anchor: info.newPos};
cm.setSelections(sel); cm.setSelections(sel);
if (info.indent) { if (!dontIndentOnAutoClose && info.indent) {
cm.indentLine(info.newPos.line, null, true); cm.indentLine(info.newPos.line, null, true);
cm.indentLine(info.newPos.line + 1, null, true); cm.indentLine(info.newPos.line + 1, null, true);
} }
@ -97,6 +99,8 @@
function autoCloseCurrent(cm, typingSlash) { function autoCloseCurrent(cm, typingSlash) {
var ranges = cm.listSelections(), replacements = []; var ranges = cm.listSelections(), replacements = [];
var head = typingSlash ? "/" : "</"; var head = typingSlash ? "/" : "</";
var opt = cm.getOption("autoCloseTags");
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnSlash);
for (var i = 0; i < ranges.length; i++) { for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass; if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos); var pos = ranges[i].head, tok = cm.getTokenAt(pos);
@ -127,10 +131,12 @@
} }
cm.replaceSelections(replacements); cm.replaceSelections(replacements);
ranges = cm.listSelections(); ranges = cm.listSelections();
if (!dontIndentOnAutoClose) {
for (var i = 0; i < ranges.length; i++) for (var i = 0; i < ranges.length; i++)
if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line) if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)
cm.indentLine(ranges[i].head.line); cm.indentLine(ranges[i].head.line);
} }
}
function autoCloseSlash(cm) { function autoCloseSlash(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass; if (cm.getOption("disableInput")) return CodeMirror.Pass;

45
lib/redactor/codemirror/addon/edit/continuelist.js vendored

@ -39,14 +39,51 @@
replacements[i] = "\n"; replacements[i] = "\n";
} else { } else {
var indent = match[1], after = match[5]; var indent = match[1], after = match[5];
var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0 var numbered = !(unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0);
? match[2].replace("x", " ") var bullet = numbered ? (parseInt(match[3], 10) + 1) + match[4] : match[2].replace("x", " ");
: (parseInt(match[3], 10) + 1) + match[4];
replacements[i] = "\n" + indent + bullet + after; replacements[i] = "\n" + indent + bullet + after;
if (numbered) incrementRemainingMarkdownListNumbers(cm, pos);
} }
} }
cm.replaceSelections(replacements); cm.replaceSelections(replacements);
}; };
// Auto-updating Markdown list numbers when a new item is added to the
// middle of a list
function incrementRemainingMarkdownListNumbers(cm, pos) {
var startLine = pos.line, lookAhead = 0, skipCount = 0;
var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
do {
lookAhead += 1;
var nextLineNumber = startLine + lookAhead;
var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
if (nextItem) {
var nextIndent = nextItem[1];
var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
if (startIndent === nextIndent && !isNaN(nextNumber)) {
if (newNumber === nextNumber) itemNumber = nextNumber + 1;
if (newNumber > nextNumber) itemNumber = newNumber + 1;
cm.replaceRange(
nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
{
line: nextLineNumber, ch: 0
}, {
line: nextLineNumber, ch: nextLine.length
});
} else {
if (startIndent.length > nextIndent.length) return;
// This doesn't run if the next line immediatley indents, as it is
// not clear of the users intention (new indented item or same level)
if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
skipCount += 1;
}
}
} while (nextItem);
}
}); });

13
lib/redactor/codemirror/addon/edit/matchbrackets.js vendored

@ -102,18 +102,23 @@
} }
} }
var currentlyHighlighted = null;
function doMatchBrackets(cm) { function doMatchBrackets(cm) {
cm.operation(function() { cm.operation(function() {
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} if (cm.state.matchBrackets.currentlyHighlighted) {
currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); cm.state.matchBrackets.currentlyHighlighted();
cm.state.matchBrackets.currentlyHighlighted = null;
}
cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
}); });
} }
CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) { if (old && old != CodeMirror.Init) {
cm.off("cursorActivity", doMatchBrackets); cm.off("cursorActivity", doMatchBrackets);
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
cm.state.matchBrackets.currentlyHighlighted();
cm.state.matchBrackets.currentlyHighlighted = null;
}
} }
if (val) { if (val) {
cm.state.matchBrackets = typeof val == "object" ? val : {}; cm.state.matchBrackets = typeof val == "object" ? val : {};

2
lib/redactor/codemirror/addon/fold/xml-fold.js vendored

@ -138,7 +138,7 @@
var iter = new Iter(cm, start.line, 0); var iter = new Iter(cm, start.line, 0);
for (;;) { for (;;) {
var openTag = toNextTag(iter), end; var openTag = toNextTag(iter), end;
if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return; if (!openTag || !(end = toTagEnd(iter)) || iter.line != start.line) return;
if (!openTag[1] && end != "selfClose") { if (!openTag[1] && end != "selfClose") {
var startPos = Pos(iter.line, iter.ch); var startPos = Pos(iter.line, iter.ch);
var endPos = findMatchingClose(iter, openTag[2]); var endPos = findMatchingClose(iter, openTag[2]);

8
lib/redactor/codemirror/addon/hint/javascript-hint.js vendored

@ -32,7 +32,9 @@
// Find the token at the cursor // Find the token at the cursor
var cur = editor.getCursor(), token = getToken(editor, cur); var cur = editor.getCursor(), token = getToken(editor, cur);
if (/\b(?:string|comment)\b/.test(token.type)) return; if (/\b(?:string|comment)\b/.test(token.type)) return;
token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; var innerMode = CodeMirror.innerMode(editor.getMode(), token.state);
if (innerMode.mode.helperType === "json") return;
token.state = innerMode.state;
// If it's not a 'word-style' token, ignore the token. // If it's not a 'word-style' token, ignore the token.
if (!/^[\w$_]*$/.test(token.string)) { if (!/^[\w$_]*$/.test(token.string)) {
@ -92,8 +94,8 @@
var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
"lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
var funcProps = "prototype apply call bind".split(" "); var funcProps = "prototype apply call bind".split(" ");
var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + var javascriptKeywords = ("break case catch class const continue debugger default delete do else export extends false finally for function " +
"if in instanceof new null return switch throw true try typeof var void while with").split(" "); "if in import instanceof new null return super switch this throw true try typeof var void while with yield").split(" ");
var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
"if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" "); "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");

17
lib/redactor/codemirror/addon/hint/show-hint.js vendored

@ -121,7 +121,6 @@
var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle); var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
if (this.widget) this.widget.close(); if (this.widget) this.widget.close();
if (data && this.data && isNewCompletion(this.data, data)) return;
this.data = data; this.data = data;
if (data && data.list.length) { if (data && data.list.length) {
@ -135,11 +134,6 @@
} }
}; };
function isNewCompletion(old, nw) {
var moved = CodeMirror.cmpPos(nw.from, old.from)
return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch
}
function parseOptions(cm, pos, options) { function parseOptions(cm, pos, options) {
var editor = cm.options.hintOptions; var editor = cm.options.hintOptions;
var out = {}; var out = {};
@ -403,12 +397,13 @@
}); });
CodeMirror.registerHelper("hint", "fromList", function(cm, options) { CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
var cur = cm.getCursor(), token = cm.getTokenAt(cur); var cur = cm.getCursor(), token = cm.getTokenAt(cur)
var to = CodeMirror.Pos(cur.line, token.end); var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
if (token.string && /\w/.test(token.string[token.string.length - 1])) { if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
var term = token.string, from = CodeMirror.Pos(cur.line, token.start); term = token.string.substr(0, cur.ch - token.start)
} else { } else {
var term = "", from = to; term = ""
from = cur
} }
var found = []; var found = [];
for (var i = 0; i < options.words.length; i++) { for (var i = 0; i < options.words.length; i++) {

4
lib/redactor/codemirror/addon/hint/sql-hint.js vendored

@ -222,6 +222,7 @@
prevItem = separator[i]; prevItem = separator[i];
} }
if (validRange.start) {
var query = doc.getRange(validRange.start, validRange.end, false); var query = doc.getRange(validRange.start, validRange.end, false);
for (var i = 0; i < query.length; i++) { for (var i = 0; i < query.length; i++) {
@ -235,6 +236,7 @@
}); });
if (table) break; if (table) break;
} }
}
return table; return table;
} }
@ -273,8 +275,8 @@
if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) {
start = nameCompletion(cur, token, result, editor); start = nameCompletion(cur, token, result, editor);
} else { } else {
addMatches(result, search, tables, function(w) {return w;});
addMatches(result, search, defaultTable, function(w) {return w;}); addMatches(result, search, defaultTable, function(w) {return w;});
addMatches(result, search, tables, function(w) {return w;});
if (!disableKeywords) if (!disableKeywords)
addMatches(result, search, keywords, function(w) {return w.toUpperCase();}); addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
} }

106
lib/redactor/codemirror/addon/lint/javascript-lint.js vendored

@ -12,15 +12,6 @@
"use strict"; "use strict";
// declare global: JSHINT // declare global: JSHINT
var bogus = [ "Dangerous comment" ];
var warnings = [ [ "Expected '{'",
"Statement body should be inside '{ }' braces." ] ];
var errors = [ "Missing semicolon", "Extra comma", "Missing property name",
"Unmatched ", " and instead saw", " is not defined",
"Unclosed string", "Stopping, unable to continue" ];
function validator(text, options) { function validator(text, options) {
if (!window.JSHINT) { if (!window.JSHINT) {
if (window.console) { if (window.console) {
@ -28,6 +19,8 @@
} }
return []; return [];
} }
if (!options.indent) // JSHint error.character actually is a column index, this fixes underlining on lines using tabs for indentation
options.indent = 1; // JSHint default value is 4
JSHINT(text, options, options.globals); JSHINT(text, options, options.globals);
var errors = JSHINT.data().errors, result = []; var errors = JSHINT.data().errors, result = [];
if (errors) parseErrors(errors, result); if (errors) parseErrors(errors, result);
@ -36,105 +29,34 @@
CodeMirror.registerHelper("lint", "javascript", validator); CodeMirror.registerHelper("lint", "javascript", validator);
function cleanup(error) {
// All problems are warnings by default
fixWith(error, warnings, "warning", true);
fixWith(error, errors, "error");
return isBogus(error) ? null : error;
}
function fixWith(error, fixes, severity, force) {
var description, fix, find, replace, found;
description = error.description;
for ( var i = 0; i < fixes.length; i++) {
fix = fixes[i];
find = (typeof fix === "string" ? fix : fix[0]);
replace = (typeof fix === "string" ? null : fix[1]);
found = description.indexOf(find) !== -1;
if (force || found) {
error.severity = severity;
}
if (found && replace) {
error.description = replace;
}
}
}
function isBogus(error) {
var description = error.description;
for ( var i = 0; i < bogus.length; i++) {
if (description.indexOf(bogus[i]) !== -1) {
return true;
}
}
return false;
}
function parseErrors(errors, output) { function parseErrors(errors, output) {
for ( var i = 0; i < errors.length; i++) { for ( var i = 0; i < errors.length; i++) {
var error = errors[i]; var error = errors[i];
if (error) { if (error) {
var linetabpositions, index; if (error.line <= 0) {
if (window.console) {
linetabpositions = []; window.console.warn("Cannot display JSHint error (invalid line " + error.line + ")", error);
// This next block is to fix a problem in jshint. Jshint
// replaces
// all tabs with spaces then performs some checks. The error
// positions (character/space) are then reported incorrectly,
// not taking the replacement step into account. Here we look
// at the evidence line and try to adjust the character position
// to the correct value.
if (error.evidence) {
// Tab positions are computed once per line and cached
var tabpositions = linetabpositions[error.line];
if (!tabpositions) {
var evidence = error.evidence;
tabpositions = [];
// ugggh phantomjs does not like this
// forEachChar(evidence, function(item, index) {
Array.prototype.forEach.call(evidence, function(item,
index) {
if (item === '\t') {
// First col is 1 (not 0) to match error
// positions
tabpositions.push(index + 1);
}
});
linetabpositions[error.line] = tabpositions;
}
if (tabpositions.length > 0) {
var pos = error.character;
tabpositions.forEach(function(tabposition) {
if (pos > tabposition) pos -= 1;
});
error.character = pos;
} }
continue;
} }
var start = error.character - 1, end = start + 1; var start = error.character - 1, end = start + 1;
if (error.evidence) { if (error.evidence) {
index = error.evidence.substring(start).search(/.\b/); var index = error.evidence.substring(start).search(/.\b/);
if (index > -1) { if (index > -1) {
end += index; end += index;
} }
} }
// Convert to format expected by validation service // Convert to format expected by validation service
error.description = error.reason;// + "(jshint)"; var hint = {
error.start = error.character; message: error.reason,
error.end = end; severity: error.code ? (error.code.startsWith('W') ? "warning" : "error") : "error",
error = cleanup(error);
if (error)
output.push({message: error.description,
severity: error.severity,
from: CodeMirror.Pos(error.line - 1, start), from: CodeMirror.Pos(error.line - 1, start),
to: CodeMirror.Pos(error.line - 1, end)}); to: CodeMirror.Pos(error.line - 1, end)
};
output.push(hint);
} }
} }
} }

6
lib/redactor/codemirror/addon/lint/lint.js vendored

@ -132,7 +132,7 @@
cm.off("change", abort) cm.off("change", abort)
if (state.waitingFor != id) return if (state.waitingFor != id) return
if (arg2 && annotations instanceof CodeMirror) annotations = arg2 if (arg2 && annotations instanceof CodeMirror) annotations = arg2
updateLinting(cm, annotations) cm.operation(function() {updateLinting(cm, annotations)})
}, passOptions, cm); }, passOptions, cm);
} }
@ -151,9 +151,9 @@
var annotations = getAnnotations(cm.getValue(), passOptions, cm); var annotations = getAnnotations(cm.getValue(), passOptions, cm);
if (!annotations) return; if (!annotations) return;
if (annotations.then) annotations.then(function(issues) { if (annotations.then) annotations.then(function(issues) {
updateLinting(cm, issues); cm.operation(function() {updateLinting(cm, issues)})
}); });
else updateLinting(cm, annotations); else cm.operation(function() {updateLinting(cm, annotations)})
} }
} }

6
lib/redactor/codemirror/addon/merge/merge.css vendored

@ -48,6 +48,12 @@
color: #555; color: #555;
line-height: 1; line-height: 1;
} }
.CodeMirror-merge-scrolllock:after {
content: "\21db\00a0\00a0\21da";
}
.CodeMirror-merge-scrolllock.CodeMirror-merge-scrolllock-enabled:after {
content: "\21db\21da";
}
.CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right { .CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {
position: absolute; position: absolute;

5
lib/redactor/codemirror/addon/merge/merge.js vendored

@ -211,7 +211,7 @@
function setScrollLock(dv, val, action) { function setScrollLock(dv, val, action) {
dv.lockScroll = val; dv.lockScroll = val;
if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv); if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db&nbsp;&nbsp;\u21da"; (val ? CodeMirror.addClass : CodeMirror.rmClass)(dv.lockButton, "CodeMirror-merge-scrolllock-enabled");
} }
// Updating the marks for editor content // Updating the marks for editor content
@ -738,6 +738,9 @@
mark.clear(); mark.clear();
cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line"); cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
} }
if (mark.explicitlyCleared) clear();
CodeMirror.on(widget, "click", clear);
mark.on("clear", clear);
CodeMirror.on(widget, "click", clear); CodeMirror.on(widget, "click", clear);
return {mark: mark, clear: clear}; return {mark: mark, clear: clear};
} }

10
lib/redactor/codemirror/addon/mode/multiplex.js vendored

@ -50,7 +50,15 @@ CodeMirror.multiplexingMode = function(outer /*, others */) {
if (found == stream.pos) { if (found == stream.pos) {
if (!other.parseDelimiters) stream.match(other.open); if (!other.parseDelimiters) stream.match(other.open);
state.innerActive = other; state.innerActive = other;
state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
// Get the outer indent, making sure to handle CodeMirror.Pass
var outerIndent = 0;
if (outer.indent) {
var possibleOuterIndent = outer.indent(state.outer, "");
if (possibleOuterIndent !== CodeMirror.Pass) outerIndent = possibleOuterIndent;
}
state.inner = CodeMirror.startState(other.mode, outerIndent);
return other.delimStyle && (other.delimStyle + " " + other.delimStyle + "-open"); return other.delimStyle && (other.delimStyle + " " + other.delimStyle + "-open");
} else if (found != -1 && found < cutOff) { } else if (found != -1 && found < cutOff) {
cutOff = found; cutOff = found;

2
lib/redactor/codemirror/addon/search/match-highlighter.js vendored

@ -90,7 +90,7 @@
var state = cm.state.matchHighlighter; var state = cm.state.matchHighlighter;
cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style)); cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));
if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) { if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {
var searchFor = hasBoundary ? new RegExp("\\b" + query + "\\b") : query; var searchFor = hasBoundary ? new RegExp("\\b" + query.replace(/[\\\[.+*?(){|^$]/g, "\\$&") + "\\b") : query;
state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false, state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false,
{className: "CodeMirror-selection-highlight-scrollbar"}); {className: "CodeMirror-selection-highlight-scrollbar"});
} }

20
lib/redactor/codemirror/addon/search/searchcursor.js vendored

@ -19,8 +19,11 @@
+ (regexp.multiline ? "m" : "") + (regexp.multiline ? "m" : "")
} }
function ensureGlobal(regexp) { function ensureFlags(regexp, flags) {
return regexp.global ? regexp : new RegExp(regexp.source, regexpFlags(regexp) + "g") var current = regexpFlags(regexp), target = current
for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1)
target += flags.charAt(i)
return current == target ? regexp : new RegExp(regexp.source, target)
} }
function maybeMultiline(regexp) { function maybeMultiline(regexp) {
@ -28,7 +31,7 @@
} }
function searchRegexpForward(doc, regexp, start) { function searchRegexpForward(doc, regexp, start) {
regexp = ensureGlobal(regexp) regexp = ensureFlags(regexp, "g")
for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
regexp.lastIndex = ch regexp.lastIndex = ch
var string = doc.getLine(line), match = regexp.exec(string) var string = doc.getLine(line), match = regexp.exec(string)
@ -42,7 +45,7 @@
function searchRegexpForwardMultiline(doc, regexp, start) { function searchRegexpForwardMultiline(doc, regexp, start) {
if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start) if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)
regexp = ensureGlobal(regexp) regexp = ensureFlags(regexp, "gm")
var string, chunk = 1 var string, chunk = 1
for (var line = start.line, last = doc.lastLine(); line <= last;) { for (var line = start.line, last = doc.lastLine(); line <= last;) {
// This grows the search buffer in exponentially-sized chunks // This grows the search buffer in exponentially-sized chunks
@ -51,6 +54,7 @@
// searching for something that has tons of matches), but at the // searching for something that has tons of matches), but at the
// same time, the amount of retries is limited. // same time, the amount of retries is limited.
for (var i = 0; i < chunk; i++) { for (var i = 0; i < chunk; i++) {
if (line > last) break
var curLine = doc.getLine(line++) var curLine = doc.getLine(line++)
string = string == null ? curLine : string + "\n" + curLine string = string == null ? curLine : string + "\n" + curLine
} }
@ -81,7 +85,7 @@
} }
function searchRegexpBackward(doc, regexp, start) { function searchRegexpBackward(doc, regexp, start) {
regexp = ensureGlobal(regexp) regexp = ensureFlags(regexp, "g")
for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
var string = doc.getLine(line) var string = doc.getLine(line)
if (ch > -1) string = string.slice(0, ch) if (ch > -1) string = string.slice(0, ch)
@ -94,7 +98,7 @@
} }
function searchRegexpBackwardMultiline(doc, regexp, start) { function searchRegexpBackwardMultiline(doc, regexp, start) {
regexp = ensureGlobal(regexp) regexp = ensureFlags(regexp, "gm")
var string, chunk = 1 var string, chunk = 1
for (var line = start.line, first = doc.firstLine(); line >= first;) { for (var line = start.line, first = doc.firstLine(); line >= first;) {
for (var i = 0; i < chunk; i++) { for (var i = 0; i < chunk; i++) {
@ -159,7 +163,7 @@
for (var i = 1; i < lines.length - 1; i++) for (var i = 1; i < lines.length - 1; i++)
if (fold(doc.getLine(line + i)) != lines[i]) continue search if (fold(doc.getLine(line + i)) != lines[i]) continue search
var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1] var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1]
if (end.slice(0, lastLine.length) != lastLine) continue search if (endString.slice(0, lastLine.length) != lastLine) continue search
return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),
to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))} to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}
} }
@ -213,7 +217,7 @@
return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold) return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)
} }
} else { } else {
query = ensureGlobal(query) query = ensureFlags(query, "gm")
if (!options || options.multiline !== false) if (!options || options.multiline !== false)
this.matches = function(reverse, pos) { this.matches = function(reverse, pos) {
return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos) return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)

3
lib/redactor/codemirror/addon/tern/tern.js vendored

@ -614,7 +614,8 @@
var mouseOnTip = false, old = false; var mouseOnTip = false, old = false;
CodeMirror.on(tip, "mousemove", function() { mouseOnTip = true; }); CodeMirror.on(tip, "mousemove", function() { mouseOnTip = true; });
CodeMirror.on(tip, "mouseout", function(e) { CodeMirror.on(tip, "mouseout", function(e) {
if (!CodeMirror.contains(tip, e.relatedTarget || e.toElement)) { var related = e.relatedTarget || e.toElement
if (!related || !CodeMirror.contains(tip, related)) {
if (old) clear(); if (old) clear();
else mouseOnTip = false; else mouseOnTip = false;
} }

1
lib/redactor/codemirror/codemirror_connect.tpl

@ -16,6 +16,7 @@
<script src="{$ABS_PATH}lib/redactor/codemirror/mode/clike/clike.js"></script> <script src="{$ABS_PATH}lib/redactor/codemirror/mode/clike/clike.js"></script>
<script src="{$ABS_PATH}lib/redactor/codemirror/mode/php/php.js"></script> <script src="{$ABS_PATH}lib/redactor/codemirror/mode/php/php.js"></script>
<script src="{$ABS_PATH}lib/redactor/codemirror/mode/smarty/smarty.js"></script> <script src="{$ABS_PATH}lib/redactor/codemirror/mode/smarty/smarty.js"></script>
<script src="{$ABS_PATH}lib/redactor/codemirror/mode/smartymixed/smartymixed.js"></script>
<script src="{$ABS_PATH}lib/redactor/codemirror/mode/htmlmixed/htmlmixed.js"></script> <script src="{$ABS_PATH}lib/redactor/codemirror/mode/htmlmixed/htmlmixed.js"></script>
<script src="{$ABS_PATH}lib/redactor/codemirror/addon/edit/closetag.js"></script> <script src="{$ABS_PATH}lib/redactor/codemirror/addon/edit/closetag.js"></script>

3
lib/redactor/codemirror/codemirror_editor.tpl

@ -50,7 +50,8 @@ editor{$conn_id} = CodeMirror.fromTextArea(document.getElementById('{$textarea_i
enterMode: 'keep', enterMode: 'keep',
tabMode: 'shift', tabMode: 'shift',
autoCloseTags: true, autoCloseTags: true,
styleActiveLine: true styleActiveLine: true,
smartyVersion : 2
{rdelim}); {rdelim});
editor{$conn_id}.setSize('{$width|default:'100%'}', '{$height|default:'400px'}'); editor{$conn_id}.setSize('{$width|default:'100%'}', '{$height|default:'400px'}');

6
lib/redactor/codemirror/lib/codemirror.css vendored

@ -145,8 +145,8 @@
/* Default styles for common addons */ /* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;} .CodeMirror-activeline-background {background: #e8f2ff;}
@ -270,7 +270,7 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
.CodeMirror-linewidget { .CodeMirror-linewidget {
position: relative; position: relative;
z-index: 2; z-index: 2;
overflow: auto; padding: 0.1px; /* Force widget margins to stay inside of the container */
} }
.CodeMirror-widget {} .CodeMirror-widget {}

84
lib/redactor/codemirror/lib/codemirror.js vendored

@ -3274,8 +3274,10 @@ function updateHeightsInViewport(cm) {
// Read and store the height of line widgets associated with the // Read and store the height of line widgets associated with the
// given line. // given line.
function updateWidgetHeight(line) { function updateWidgetHeight(line) {
if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
{ line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } } var w = line.widgets[i], parent = w.node.parentNode
if (parent) { w.height = parent.offsetHeight }
} }
} }
// Compute the lines that are visible in a given viewport (defaults // Compute the lines that are visible in a given viewport (defaults
@ -4781,7 +4783,7 @@ function addChangeToHistory(doc, change, selAfter, opId) {
if ((hist.lastOp == opId || if ((hist.lastOp == opId ||
hist.lastOrigin == change.origin && change.origin && hist.lastOrigin == change.origin && change.origin &&
((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
change.origin.charAt(0) == "*")) && change.origin.charAt(0) == "*")) &&
(cur = lastChangeEvent(hist, hist.lastOp == opId))) { (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
// Merge this change into the last event // Merge this change into the last event
@ -5210,7 +5212,8 @@ function makeChangeInner(doc, change) {
// Revert a change stored in a document's history. // Revert a change stored in a document's history.
function makeChangeFromHistory(doc, type, allowSelectionOnly) { function makeChangeFromHistory(doc, type, allowSelectionOnly) {
if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } var suppress = doc.cm && doc.cm.state.suppressEdits
if (suppress && !allowSelectionOnly) { return }
var hist = doc.history, event, selAfter = doc.sel var hist = doc.history, event, selAfter = doc.sel
var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
@ -5235,8 +5238,10 @@ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
return return
} }
selAfter = event selAfter = event
} } else if (suppress) {
else { break } source.push(event)
return
} else { break }
} }
// Build up a reverse change object to add to the opposite history // Build up a reverse change object to add to the opposite history
@ -5712,7 +5717,7 @@ function addLineWidget(doc, handle, node, options) {
} }
return true return true
}) })
signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) }
return widget return widget
} }
@ -6571,11 +6576,11 @@ function onResize(cm) {
} }
var keyNames = { var keyNames = {
3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
@ -6722,6 +6727,9 @@ function keyName(event, noShift) {
if (presto && event.keyCode == 34 && event["char"]) { return false } if (presto && event.keyCode == 34 && event["char"]) { return false }
var name = keyNames[event.keyCode] var name = keyNames[event.keyCode]
if (name == null || event.altGraphKey) { return false } if (name == null || event.altGraphKey) { return false }
// Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
// so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
if (event.keyCode == 3 && event.code) { name = event.code }
return addModifierNames(name, event, noShift) return addModifierNames(name, event, noShift)
} }
@ -7061,18 +7069,26 @@ function lookupKeyForEditor(cm, name, handle) {
// for bound mouse clicks. // for bound mouse clicks.
var stopSeq = new Delayed var stopSeq = new Delayed
function dispatchKey(cm, name, e, handle) { function dispatchKey(cm, name, e, handle) {
var seq = cm.state.keySeq var seq = cm.state.keySeq
if (seq) { if (seq) {
if (isModifierKey(name)) { return "handled" } if (isModifierKey(name)) { return "handled" }
stopSeq.set(50, function () { if (/\'$/.test(name))
{ cm.state.keySeq = null }
else
{ stopSeq.set(50, function () {
if (cm.state.keySeq == seq) { if (cm.state.keySeq == seq) {
cm.state.keySeq = null cm.state.keySeq = null
cm.display.input.reset() cm.display.input.reset()
} }
}) }) }
name = seq + " " + name if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
} }
return dispatchKeyInner(cm, name, e, handle)
}
function dispatchKeyInner(cm, name, e, handle) {
var result = lookupKeyForEditor(cm, name, handle) var result = lookupKeyForEditor(cm, name, handle)
if (result == "multi") if (result == "multi")
@ -7085,10 +7101,6 @@ function dispatchKey(cm, name, e, handle) {
restartBlink(cm) restartBlink(cm)
} }
if (seq && !result && /\'$/.test(name)) {
e_preventDefault(e)
return true
}
return !!result return !!result
} }
@ -7300,8 +7312,8 @@ function leftButtonStartDrag(cm, event, pos, behavior) {
var dragEnd = operation(cm, function (e) { var dragEnd = operation(cm, function (e) {
if (webkit) { display.scroller.draggable = false } if (webkit) { display.scroller.draggable = false }
cm.state.draggingText = false cm.state.draggingText = false
off(document, "mouseup", dragEnd) off(display.wrapper.ownerDocument, "mouseup", dragEnd)
off(document, "mousemove", mouseMove) off(display.wrapper.ownerDocument, "mousemove", mouseMove)
off(display.scroller, "dragstart", dragStart) off(display.scroller, "dragstart", dragStart)
off(display.scroller, "drop", dragEnd) off(display.scroller, "drop", dragEnd)
if (!moved) { if (!moved) {
@ -7310,7 +7322,7 @@ function leftButtonStartDrag(cm, event, pos, behavior) {
{ extendSelection(cm.doc, pos, null, null, behavior.extend) } { extendSelection(cm.doc, pos, null, null, behavior.extend) }
// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
if (webkit || ie && ie_version == 9) if (webkit || ie && ie_version == 9)
{ setTimeout(function () {document.body.focus(); display.input.focus()}, 20) } { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20) }
else else
{ display.input.focus() } { display.input.focus() }
} }
@ -7325,8 +7337,8 @@ function leftButtonStartDrag(cm, event, pos, behavior) {
dragEnd.copy = !behavior.moveOnDrag dragEnd.copy = !behavior.moveOnDrag
// IE's approach to draggable // IE's approach to draggable
if (display.scroller.dragDrop) { display.scroller.dragDrop() } if (display.scroller.dragDrop) { display.scroller.dragDrop() }
on(document, "mouseup", dragEnd) on(display.wrapper.ownerDocument, "mouseup", dragEnd)
on(document, "mousemove", mouseMove) on(display.wrapper.ownerDocument, "mousemove", mouseMove)
on(display.scroller, "dragstart", dragStart) on(display.scroller, "dragstart", dragStart)
on(display.scroller, "drop", dragEnd) on(display.scroller, "drop", dragEnd)
@ -7458,8 +7470,8 @@ function leftButtonSelect(cm, event, start, behavior) {
counter = Infinity counter = Infinity
e_preventDefault(e) e_preventDefault(e)
display.input.focus() display.input.focus()
off(document, "mousemove", move) off(display.wrapper.ownerDocument, "mousemove", move)
off(document, "mouseup", up) off(display.wrapper.ownerDocument, "mouseup", up)
doc.history.lastSelOrigin = null doc.history.lastSelOrigin = null
} }
@ -7469,8 +7481,8 @@ function leftButtonSelect(cm, event, start, behavior) {
}) })
var up = operation(cm, done) var up = operation(cm, done)
cm.state.selectingText = up cm.state.selectingText = up
on(document, "mousemove", move) on(display.wrapper.ownerDocument, "mousemove", move)
on(document, "mouseup", up) on(display.wrapper.ownerDocument, "mouseup", up)
} }
// Used when mouse-selecting to adjust the anchor to the proper side // Used when mouse-selecting to adjust the anchor to the proper side
@ -7600,6 +7612,7 @@ function defineOptions(CodeMirror) {
clearCaches(cm) clearCaches(cm)
regChange(cm) regChange(cm)
}, true) }, true)
option("lineSeparator", null, function (cm, val) { option("lineSeparator", null, function (cm, val) {
cm.doc.lineSep = val cm.doc.lineSep = val
if (!val) { return } if (!val) { return }
@ -8006,7 +8019,7 @@ function applyTextInput(cm, inserted, deleted, sel, origin) {
var paste = cm.state.pasteIncoming || origin == "paste" var paste = cm.state.pasteIncoming || origin == "paste"
var textLines = splitLinesAuto(inserted), multiPaste = null var textLines = splitLinesAuto(inserted), multiPaste = null
// When pasing N lines into N selections, insert one line per selection // When pasting N lines into N selections, insert one line per selection
if (paste && sel.ranges.length > 1) { if (paste && sel.ranges.length > 1) {
if (lastCopied && lastCopied.text.join("\n") == inserted) { if (lastCopied && lastCopied.text.join("\n") == inserted) {
if (sel.ranges.length % lastCopied.text.length == 0) { if (sel.ranges.length % lastCopied.text.length == 0) {
@ -9174,13 +9187,10 @@ TextareaInput.prototype.init = function (display) {
var this$1 = this; var this$1 = this;
var input = this, cm = this.cm var input = this, cm = this.cm
this.createField(display)
var te = this.textarea
// Wraps and hides input textarea display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild)
var div = this.wrapper = hiddenTextarea()
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
var te = this.textarea = div.firstChild
display.wrapper.insertBefore(div, display.wrapper.firstChild)
// Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
if (ios) { te.style.width = "0px" } if (ios) { te.style.width = "0px" }
@ -9247,6 +9257,14 @@ TextareaInput.prototype.init = function (display) {
}) })
}; };
TextareaInput.prototype.createField = function (_display) {
// Wraps and hides input textarea
this.wrapper = hiddenTextarea()
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
this.textarea = this.wrapper.firstChild
};
TextareaInput.prototype.prepareSelection = function () { TextareaInput.prototype.prepareSelection = function () {
// Redraw the selection and/or cursor // Redraw the selection and/or cursor
var cm = this.cm, display = cm.display, doc = cm.doc var cm = this.cm, display = cm.display, doc = cm.doc
@ -9640,7 +9658,7 @@ CodeMirror.fromTextArea = fromTextArea
addLegacyProps(CodeMirror) addLegacyProps(CodeMirror)
CodeMirror.version = "5.31.0" CodeMirror.version = "5.36.0"
return CodeMirror; return CodeMirror;

45
lib/redactor/codemirror/mode/clike/clike.js vendored

@ -374,7 +374,7 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
blockKeywords: words("case do else for if switch while struct"), blockKeywords: words("case do else for if switch while struct"),
defKeywords: words("struct"), defKeywords: words("struct"),
typeFirstDefinitions: true, typeFirstDefinitions: true,
atoms: words("null true false"), atoms: words("NULL true false"),
hooks: {"#": cppHook, "*": pointerHook}, hooks: {"#": cppHook, "*": pointerHook},
modeProps: {fold: ["brace", "include"]} modeProps: {fold: ["brace", "include"]}
}); });
@ -390,7 +390,7 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
blockKeywords: words("catch class do else finally for if struct switch try while"), blockKeywords: words("catch class do else finally for if struct switch try while"),
defKeywords: words("class namespace struct enum union"), defKeywords: words("class namespace struct enum union"),
typeFirstDefinitions: true, typeFirstDefinitions: true,
atoms: words("true false null"), atoms: words("true false NULL"),
dontIndentStatements: /^template$/, dontIndentStatements: /^template$/,
isIdentifierChar: /[\w\$_~\xa1-\uffff]/, isIdentifierChar: /[\w\$_~\xa1-\uffff]/,
hooks: { hooks: {
@ -432,7 +432,7 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
"Integer Long Number Object Short String StringBuffer StringBuilder Void"), "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
blockKeywords: words("catch class do else finally for if switch try while"), blockKeywords: words("catch class do else finally for if switch try while"),
defKeywords: words("class interface package enum @interface"), defKeywords: words("class interface enum @interface"),
typeFirstDefinitions: true, typeFirstDefinitions: true,
atoms: words("true false null"), atoms: words("true false null"),
number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
@ -489,6 +489,27 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
return "string"; return "string";
} }
function tokenNestedComment(depth) {
return function (stream, state) {
var ch
while (ch = stream.next()) {
if (ch == "*" && stream.eat("/")) {
if (depth == 1) {
state.tokenize = null
break
} else {
state.tokenize = tokenNestedComment(depth - 1)
return state.tokenize(stream, state)
}
} else if (ch == "/" && stream.eat("*")) {
state.tokenize = tokenNestedComment(depth + 1)
return state.tokenize(stream, state)
}
}
return "comment"
}
}
def("text/x-scala", { def("text/x-scala", {
name: "clike", name: "clike",
keywords: words( keywords: words(
@ -544,6 +565,12 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
} else { } else {
return false return false
} }
},
"/": function(stream, state) {
if (!stream.eat("*")) return false
state.tokenize = tokenNestedComment(1)
return state.tokenize(stream, state)
} }
}, },
modeProps: {closeBrackets: {triples: '"'}} modeProps: {closeBrackets: {triples: '"'}}
@ -570,27 +597,29 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
name: "clike", name: "clike",
keywords: words( keywords: words(
/*keywords*/ /*keywords*/
"package as typealias class interface this super val " + "package as typealias class interface this super val operator " +
"var fun for is in This throw return " + "var fun for is in This throw return annotation " +
"break continue object if else while do try when !in !is as? " + "break continue object if else while do try when !in !is as? " +
/*soft keywords*/ /*soft keywords*/
"file import where by get set abstract enum open inner override private public internal " + "file import where by get set abstract enum open inner override private public internal " +
"protected catch finally out final vararg reified dynamic companion constructor init " + "protected catch finally out final vararg reified dynamic companion constructor init " +
"sealed field property receiver param sparam lateinit data inline noinline tailrec " + "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
"external annotation crossinline const operator infix suspend" "external annotation crossinline const operator infix suspend actual expect setparam"
), ),
types: words( types: words(
/* package java.lang */ /* package java.lang */
"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " +
"ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " +
"LazyThreadSafetyMode LongArray Nothing ShortArray Unit"
), ),
intendSwitch: false, intendSwitch: false,
indentStatements: false, indentStatements: false,
multiLineStrings: true, multiLineStrings: true,
number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
blockKeywords: words("catch class do else finally for if where try while enum"), blockKeywords: words("catch class do else finally for if where try while enum"),
defKeywords: words("class val var object interface fun"), defKeywords: words("class val var object interface fun"),
atoms: words("true false null this"), atoms: words("true false null this"),

360
lib/redactor/codemirror/mode/clike/index.html vendored

@ -1,360 +0,0 @@
<!doctype html>
<title>CodeMirror: C-like mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<link rel="stylesheet" href="../../addon/hint/show-hint.css">
<script src="../../addon/hint/show-hint.js"></script>
<script src="clike.js"></script>
<style>.CodeMirror {border: 2px inset #dee;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">C-like</a>
</ul>
</div>
<article>
<h2>C-like mode</h2>
<div><textarea id="c-code">
/* C demo code */
#include <zmq.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <malloc.h>
typedef struct {
void* arg_socket;
zmq_msg_t* arg_msg;
char* arg_string;
unsigned long arg_len;
int arg_int, arg_command;
int signal_fd;
int pad;
void* context;
sem_t sem;
} acl_zmq_context;
#define p(X) (context->arg_##X)
void* zmq_thread(void* context_pointer) {
acl_zmq_context* context = (acl_zmq_context*)context_pointer;
char ok = 'K', err = 'X';
int res;
while (1) {
while ((res = sem_wait(&amp;context->sem)) == EINTR);
if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}
switch(p(command)) {
case 0: goto cleanup;
case 1: p(socket) = zmq_socket(context->context, p(int)); break;
case 2: p(int) = zmq_close(p(socket)); break;
case 3: p(int) = zmq_bind(p(socket), p(string)); break;
case 4: p(int) = zmq_connect(p(socket), p(string)); break;
case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;
case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
}
p(command) = errno;
write(context->signal_fd, &amp;ok, 1);
}
cleanup:
close(context->signal_fd);
free(context_pointer);
return 0;
}
void* zmq_thread_init(void* zmq_context, int signal_fd) {
acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
pthread_t thread;
context->context = zmq_context;
context->signal_fd = signal_fd;
sem_init(&amp;context->sem, 1, 0);
pthread_create(&amp;thread, 0, &amp;zmq_thread, context);
pthread_detach(thread);
return context;
}
</textarea></div>
<h2>C++ example</h2>
<div><textarea id="cpp-code">
#include <iostream>
#include "mystuff/util.h"
namespace {
enum Enum {
VAL1, VAL2, VAL3
};
char32_t unicode_string = U"\U0010FFFF";
string raw_string = R"delim(anything
you
want)delim";
int Helper(const MyType& param) {
return 0;
}
} // namespace
class ForwardDec;
template <class T, class V>
class Class : public BaseClass {
const MyType<T, V> member_;
public:
const MyType<T, V>& Method() const {
return member_;
}
void Method2(MyType<T, V>* value);
}
template <class T, class V>
void Class::Method2(MyType<T, V>* value) {
std::out << 1 >> method();
value->Method3(member_);
member_ = value;
}
</textarea></div>
<h2>Objective-C example</h2>
<div><textarea id="objectivec-code">
/*
This is a longer comment
That spans two lines
*/
#import <Test/Test.h>
@implementation YourAppDelegate
// This is a one-line comment
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
char myString[] = "This is a C character array";
int test = 5;
return YES;
}
</textarea></div>
<h2>Java example</h2>
<div><textarea id="java-code">
import com.demo.util.MyType;
import com.demo.util.MyInterface;
public enum Enum {
VAL1, VAL2, VAL3
}
public class Class<T, V> implements MyInterface {
public static final MyType<T, V> member;
private class InnerClass {
public int zero() {
return 0;
}
}
@Override
public MyType method() {
return member;
}
public void method2(MyType<T, V> value) {
method();
value.method3();
member = value;
}
}
</textarea></div>
<h2>Scala example</h2>
<div><textarea id="scala-code">
object FilterTest extends App {
def filter(xs: List[Int], threshold: Int) = {
def process(ys: List[Int]): List[Int] =
if (ys.isEmpty) ys
else if (ys.head < threshold) ys.head :: process(ys.tail)
else process(ys.tail)
process(xs)
}
println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))
}
</textarea></div>
<h2>Kotlin mode</h2>
<div><textarea id="kotlin-code">
package org.wasabi.http
import java.util.concurrent.Executors
import java.net.InetSocketAddress
import org.wasabi.app.AppConfiguration
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import org.wasabi.app.AppServer
public class HttpServer(private val appServer: AppServer) {
val bootstrap: ServerBootstrap
val primaryGroup: NioEventLoopGroup
val workerGroup: NioEventLoopGroup
init {
// Define worker groups
primaryGroup = NioEventLoopGroup()
workerGroup = NioEventLoopGroup()
// Initialize bootstrap of server
bootstrap = ServerBootstrap()
bootstrap.group(primaryGroup, workerGroup)
bootstrap.channel(javaClass<NioServerSocketChannel>())
bootstrap.childHandler(NettyPipelineInitializer(appServer))
}
public fun start(wait: Boolean = true) {
val channel = bootstrap.bind(appServer.configuration.port)?.sync()?.channel()
if (wait) {
channel?.closeFuture()?.sync()
}
}
public fun stop() {
// Shutdown all event loops
primaryGroup.shutdownGracefully()
workerGroup.shutdownGracefully()
// Wait till all threads are terminated
primaryGroup.terminationFuture().sync()
workerGroup.terminationFuture().sync()
}
}
</textarea></div>
<h2>Ceylon mode</h2>
<div><textarea id="ceylon-code">
"Produces the [[stream|Iterable]] that results from repeated
application of the given [[function|next]] to the given
[[first]] element of the stream, until the function first
returns [[finished]]. If the given function never returns
`finished`, the resulting stream is infinite.
For example:
loop(0)(2.plus).takeWhile(10.largerThan)
produces the stream `{ 0, 2, 4, 6, 8 }`."
tagged("Streams")
shared {Element+} loop&lt;Element&gt;(
"The first element of the resulting stream."
Element first)(
"The function that produces the next element of the
stream, given the current element. The function may
return [[finished]] to indicate the end of the
stream."
Element|Finished next(Element element))
=&gt; let (start = first)
object satisfies {Element+} {
first =&gt; start;
empty =&gt; false;
function nextElement(Element element)
=&gt; next(element);
iterator()
=&gt; object satisfies Iterator&lt;Element&gt; {
variable Element|Finished current = start;
shared actual Element|Finished next() {
if (!is Finished result = current) {
current = nextElement(result);
return result;
}
else {
return finished;
}
}
};
};
</textarea></div>
<script>
var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csrc"
});
var cppEditor = CodeMirror.fromTextArea(document.getElementById("cpp-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-c++src"
});
var javaEditor = CodeMirror.fromTextArea(document.getElementById("java-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-java"
});
var objectivecEditor = CodeMirror.fromTextArea(document.getElementById("objectivec-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-objectivec"
});
var scalaEditor = CodeMirror.fromTextArea(document.getElementById("scala-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-scala"
});
var kotlinEditor = CodeMirror.fromTextArea(document.getElementById("kotlin-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-kotlin"
});
var ceylonEditor = CodeMirror.fromTextArea(document.getElementById("ceylon-code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-ceylon"
});
var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault;
CodeMirror.keyMap.default[(mac ? "Cmd" : "Ctrl") + "-Space"] = "autocomplete";
</script>
<p>Simple mode that tries to handle C-like languages as well as it
can. Takes two configuration parameters: <code>keywords</code>, an
object whose property names are the keywords in the language,
and <code>useCPP</code>, which determines whether C preprocessor
directives are recognized.</p>
<p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
(C), <code>text/x-c++src</code> (C++), <code>text/x-java</code>
(Java), <code>text/x-csharp</code> (C#),
<code>text/x-objectivec</code> (Objective-C),
<code>text/x-scala</code> (Scala), <code>text/x-vertex</code>
<code>x-shader/x-fragment</code> (shader programs),
<code>text/x-squirrel</code> (Squirrel) and
<code>text/x-ceylon</code> (Ceylon)</p>
</article>

767
lib/redactor/codemirror/mode/clike/scala.html vendored

@ -1,767 +0,0 @@
<!doctype html>
<title>CodeMirror: Scala mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../theme/ambiance.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="clike.js"></script>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Scala</a>
</ul>
</div>
<article>
<h2>Scala mode</h2>
<form>
<textarea id="code" name="code">
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala.collection
import generic._
import mutable.{ Builder, ListBuffer }
import annotation.{tailrec, migration, bridge}
import annotation.unchecked.{ uncheckedVariance => uV }
import parallel.ParIterable
/** A template trait for traversable collections of type `Traversable[A]`.
*
* $traversableInfo
* @define mutability
* @define traversableInfo
* This is a base trait of all kinds of $mutability Scala collections. It
* implements the behavior common to all collections, in terms of a method
* `foreach` with signature:
* {{{
* def foreach[U](f: Elem => U): Unit
* }}}
* Collection classes mixing in this trait provide a concrete
* `foreach` method which traverses all the
* elements contained in the collection, applying a given function to each.
* They also need to provide a method `newBuilder`
* which creates a builder for collections of the same kind.
*
* A traversable class might or might not have two properties: strictness
* and orderedness. Neither is represented as a type.
*
* The instances of a strict collection class have all their elements
* computed before they can be used as values. By contrast, instances of
* a non-strict collection class may defer computation of some of their
* elements until after the instance is available as a value.
* A typical example of a non-strict collection class is a
* <a href="../immutable/Stream.html" target="ContentFrame">
* `scala.collection.immutable.Stream`</a>.
* A more general class of examples are `TraversableViews`.
*
* If a collection is an instance of an ordered collection class, traversing
* its elements with `foreach` will always visit elements in the
* same order, even for different runs of the program. If the class is not
* ordered, `foreach` can visit elements in different orders for
* different runs (but it will keep the same order in the same run).'
*
* A typical example of a collection class which is not ordered is a
* `HashMap` of objects. The traversal order for hash maps will
* depend on the hash codes of its elements, and these hash codes might
* differ from one run to the next. By contrast, a `LinkedHashMap`
* is ordered because it's `foreach` method visits elements in the
* order they were inserted into the `HashMap`.
*
* @author Martin Odersky
* @version 2.8
* @since 2.8
* @tparam A the element type of the collection
* @tparam Repr the type of the actual collection containing the elements.
*
* @define Coll Traversable
* @define coll traversable collection
*/
trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr]
with FilterMonadic[A, Repr]
with TraversableOnce[A]
with GenTraversableLike[A, Repr]
with Parallelizable[A, ParIterable[A]]
{
self =>
import Traversable.breaks._
/** The type implementing this traversable */
protected type Self = Repr
/** The collection of type $coll underlying this `TraversableLike` object.
* By default this is implemented as the `TraversableLike` object itself,
* but this can be overridden.
*/
def repr: Repr = this.asInstanceOf[Repr]
/** The underlying collection seen as an instance of `$Coll`.
* By default this is implemented as the current collection object itself,
* but this can be overridden.
*/
protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
/** A conversion from collections of type `Repr` to `$Coll` objects.
* By default this is implemented as just a cast, but this can be overridden.
*/
protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
/** Creates a new builder for this collection type.
*/
protected[this] def newBuilder: Builder[A, Repr]
protected[this] def parCombiner = ParIterable.newCombiner[A]
/** Applies a function `f` to all elements of this $coll.
*
* Note: this method underlies the implementation of most other bulk operations.
* It's important to implement this method in an efficient way.
*
*
* @param f the function that is applied for its side-effect to every element.
* The result of function `f` is discarded.
*
* @tparam U the type parameter describing the result of function `f`.
* This result will always be ignored. Typically `U` is `Unit`,
* but this is not necessary.
*
* @usecase def foreach(f: A => Unit): Unit
*/
def foreach[U](f: A => U): Unit
/** Tests whether this $coll is empty.
*
* @return `true` if the $coll contain no elements, `false` otherwise.
*/
def isEmpty: Boolean = {
var result = true
breakable {
for (x <- this) {
result = false
break
}
}
result
}
/** Tests whether this $coll is known to have a finite size.
* All strict collections are known to have finite size. For a non-strict collection
* such as `Stream`, the predicate returns `true` if all elements have been computed.
* It returns `false` if the stream is not yet evaluated to the end.
*
* Note: many collection methods will not work on collections of infinite sizes.
*
* @return `true` if this collection is known to have finite size, `false` otherwise.
*/
def hasDefiniteSize = true
def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
b ++= thisCollection
b ++= that.seq
b.result
}
@bridge
def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
++(that: GenTraversableOnce[B])(bf)
/** Concatenates this $coll with the elements of a traversable collection.
* It differs from ++ in that the right operand determines the type of the
* resulting collection rather than the left one.
*
* @param that the traversable to append.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` which contains all elements
* of this $coll followed by all elements of `that`.
*
* @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
*
* @return a new $coll which contains all elements of this $coll
* followed by all elements of `that`.
*/
def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
b ++= that
b ++= thisCollection
b.result
}
/** This overload exists because: for the implementation of ++: we should reuse
* that of ++ because many collections override it with more efficient versions.
* Since TraversableOnce has no '++' method, we have to implement that directly,
* but Traversable and down can use the overload.
*/
def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
(that ++ seq)(breakOut)
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
b.sizeHint(this)
for (x <- this) b += f(x)
b.result
}
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- this) b ++= f(x).seq
b.result
}
/** Selects all elements of this $coll which satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that satisfy the given
* predicate `p`. The order of the elements is preserved.
*/
def filter(p: A => Boolean): Repr = {
val b = newBuilder
for (x <- this)
if (p(x)) b += x
b.result
}
/** Selects all elements of this $coll which do not satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that do not satisfy the given
* predicate `p`. The order of the elements is preserved.
*/
def filterNot(p: A => Boolean): Repr = filter(!p(_))
def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
b.result
}
/** Builds a new collection by applying an option-valued function to all
* elements of this $coll on which the function is defined.
*
* @param f the option-valued function which filters and maps the $coll.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` resulting from applying the option-valued function
* `f` to each element and collecting all defined results.
* The order of the elements is preserved.
*
* @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
*
* @param pf the partial function which filters and maps the $coll.
* @return a new $coll resulting from applying the given option-valued function
* `f` to each element and collecting all defined results.
* The order of the elements is preserved.
def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- this)
f(x) match {
case Some(y) => b += y
case _ =>
}
b.result
}
*/
/** Partitions this $coll in two ${coll}s according to a predicate.
*
* @param p the predicate on which to partition.
* @return a pair of ${coll}s: the first $coll consists of all elements that
* satisfy the predicate `p` and the second $coll consists of all elements
* that don't. The relative order of the elements in the resulting ${coll}s
* is the same as in the original $coll.
*/
def partition(p: A => Boolean): (Repr, Repr) = {
val l, r = newBuilder
for (x <- this) (if (p(x)) l else r) += x
(l.result, r.result)
}
def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
val m = mutable.Map.empty[K, Builder[A, Repr]]
for (elem <- this) {
val key = f(elem)
val bldr = m.getOrElseUpdate(key, newBuilder)
bldr += elem
}
val b = immutable.Map.newBuilder[K, Repr]
for ((k, v) <- m)
b += ((k, v.result))
b.result
}
/** Tests whether a predicate holds for all elements of this $coll.
*
* $mayNotTerminateInf
*
* @param p the predicate used to test elements.
* @return `true` if the given predicate `p` holds for all elements
* of this $coll, otherwise `false`.
*/
def forall(p: A => Boolean): Boolean = {
var result = true
breakable {
for (x <- this)
if (!p(x)) { result = false; break }
}
result
}
/** Tests whether a predicate holds for some of the elements of this $coll.
*
* $mayNotTerminateInf
*
* @param p the predicate used to test elements.
* @return `true` if the given predicate `p` holds for some of the
* elements of this $coll, otherwise `false`.
*/
def exists(p: A => Boolean): Boolean = {
var result = false
breakable {
for (x <- this)
if (p(x)) { result = true; break }
}
result
}
/** Finds the first element of the $coll satisfying a predicate, if any.
*
* $mayNotTerminateInf
* $orderDependent
*
* @param p the predicate used to test elements.
* @return an option value containing the first element in the $coll
* that satisfies `p`, or `None` if none exists.
*/
def find(p: A => Boolean): Option[A] = {
var result: Option[A] = None
breakable {
for (x <- this)
if (p(x)) { result = Some(x); break }
}
result
}
def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
b.sizeHint(this, 1)
var acc = z
b += acc
for (x <- this) { acc = op(acc, x); b += acc }
b.result
}
@migration(2, 9,
"This scanRight definition has changed in 2.9.\n" +
"The previous behavior can be reproduced with scanRight.reverse."
)
def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
var scanned = List(z)
var acc = z
for (x <- reversed) {
acc = op(x, acc)
scanned ::= acc
}
val b = bf(repr)
for (elem <- scanned) b += elem
b.result
}
/** Selects the first element of this $coll.
* $orderDependent
* @return the first element of this $coll.
* @throws `NoSuchElementException` if the $coll is empty.
*/
def head: A = {
var result: () => A = () => throw new NoSuchElementException
breakable {
for (x <- this) {
result = () => x
break
}
}
result()
}
/** Optionally selects the first element.
* $orderDependent
* @return the first element of this $coll if it is nonempty, `None` if it is empty.
*/
def headOption: Option[A] = if (isEmpty) None else Some(head)
/** Selects all elements except the first.
* $orderDependent
* @return a $coll consisting of all elements of this $coll
* except the first one.
* @throws `UnsupportedOperationException` if the $coll is empty.
*/
override def tail: Repr = {
if (isEmpty) throw new UnsupportedOperationException("empty.tail")
drop(1)
}
/** Selects the last element.
* $orderDependent
* @return The last element of this $coll.
* @throws NoSuchElementException If the $coll is empty.
*/
def last: A = {
var lst = head
for (x <- this)
lst = x
lst
}
/** Optionally selects the last element.
* $orderDependent
* @return the last element of this $coll$ if it is nonempty, `None` if it is empty.
*/
def lastOption: Option[A] = if (isEmpty) None else Some(last)
/** Selects all elements except the last.
* $orderDependent
* @return a $coll consisting of all elements of this $coll
* except the last one.
* @throws `UnsupportedOperationException` if the $coll is empty.
*/
def init: Repr = {
if (isEmpty) throw new UnsupportedOperationException("empty.init")
var lst = head
var follow = false
val b = newBuilder
b.sizeHint(this, -1)
for (x <- this.seq) {
if (follow) b += lst
else follow = true
lst = x
}
b.result
}
def take(n: Int): Repr = slice(0, n)
def drop(n: Int): Repr =
if (n <= 0) {
val b = newBuilder
b.sizeHint(this)
b ++= thisCollection result
}
else sliceWithKnownDelta(n, Int.MaxValue, -n)
def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
// Precondition: from >= 0, until > 0, builder already configured for building.
private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
var i = 0
breakable {
for (x <- this.seq) {
if (i >= from) b += x
i += 1
if (i >= until) break
}
}
b.result
}
// Precondition: from >= 0
private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
val b = newBuilder
if (until <= from) b.result
else {
b.sizeHint(this, delta)
sliceInternal(from, until, b)
}
}
// Precondition: from >= 0
private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
val b = newBuilder
if (until <= from) b.result
else {
b.sizeHintBounded(until - from, this)
sliceInternal(from, until, b)
}
}
def takeWhile(p: A => Boolean): Repr = {
val b = newBuilder
breakable {
for (x <- this) {
if (!p(x)) break
b += x
}
}
b.result
}
def dropWhile(p: A => Boolean): Repr = {
val b = newBuilder
var go = false
for (x <- this) {
if (!p(x)) go = true
if (go) b += x
}
b.result
}
def span(p: A => Boolean): (Repr, Repr) = {
val l, r = newBuilder
var toLeft = true
for (x <- this) {
toLeft = toLeft && p(x)
(if (toLeft) l else r) += x
}
(l.result, r.result)
}
def splitAt(n: Int): (Repr, Repr) = {
val l, r = newBuilder
l.sizeHintBounded(n, this)
if (n >= 0) r.sizeHint(this, -n)
var i = 0
for (x <- this) {
(if (i < n) l else r) += x
i += 1
}
(l.result, r.result)
}
/** Iterates over the tails of this $coll. The first value will be this
* $coll and the final one will be an empty $coll, with the intervening
* values the results of successive applications of `tail`.
*
* @return an iterator over all the tails of this $coll
* @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
*/
def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
/** Iterates over the inits of this $coll. The first value will be this
* $coll and the final one will be an empty $coll, with the intervening
* values the results of successive applications of `init`.
*
* @return an iterator over all the inits of this $coll
* @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
*/
def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
/** Copies elements of this $coll to an array.
* Fills the given array `xs` with at most `len` elements of
* this $coll, starting at position `start`.
* Copying will stop once either the end of the current $coll is reached,
* or the end of the array is reached, or `len` elements have been copied.
*
* $willNotTerminateInf
*
* @param xs the array to fill.
* @param start the starting index.
* @param len the maximal number of elements to copy.
* @tparam B the type of the elements of the array.
*
*
* @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
*/
def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
var i = start
val end = (start + len) min xs.length
breakable {
for (x <- this) {
if (i >= end) break
xs(i) = x
i += 1
}
}
}
def toTraversable: Traversable[A] = thisCollection
def toIterator: Iterator[A] = toStream.iterator
def toStream: Stream[A] = toBuffer.toStream
/** Converts this $coll to a string.
*
* @return a string representation of this collection. By default this
* string consists of the `stringPrefix` of this $coll,
* followed by all elements separated by commas and enclosed in parentheses.
*/
override def toString = mkString(stringPrefix + "(", ", ", ")")
/** Defines the prefix of this object's `toString` representation.
*
* @return a string representation which starts the result of `toString`
* applied to this $coll. By default the string prefix is the
* simple name of the collection class $coll.
*/
def stringPrefix : String = {
var string = repr.asInstanceOf[AnyRef].getClass.getName
val idx1 = string.lastIndexOf('.' : Int)
if (idx1 != -1) string = string.substring(idx1 + 1)
val idx2 = string.indexOf('$')
if (idx2 != -1) string = string.substring(0, idx2)
string
}
/** Creates a non-strict view of this $coll.
*
* @return a non-strict view of this $coll.
*/
def view = new TraversableView[A, Repr] {
protected lazy val underlying = self.repr
override def foreach[U](f: A => U) = self foreach f
}
/** Creates a non-strict view of a slice of this $coll.
*
* Note: the difference between `view` and `slice` is that `view` produces
* a view of the current $coll, whereas `slice` produces a new $coll.
*
* Note: `view(from, to)` is equivalent to `view.slice(from, to)`
* $orderDependent
*
* @param from the index of the first element of the view
* @param until the index of the element following the view
* @return a non-strict view of a slice of this $coll, starting at index `from`
* and extending up to (but not including) index `until`.
*/
def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
/** Creates a non-strict filter of this $coll.
*
* Note: the difference between `c filter p` and `c withFilter p` is that
* the former creates a new collection, whereas the latter only
* restricts the domain of subsequent `map`, `flatMap`, `foreach`,
* and `withFilter` operations.
* $orderDependent
*
* @param p the predicate used to test elements.
* @return an object of class `WithFilter`, which supports
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
* All these operations apply to those elements of this $coll which
* satisfy the predicate `p`.
*/
def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
/** A class supporting filtered operations. Instances of this class are
* returned by method `withFilter`.
*/
class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
/** Builds a new collection by applying a function to all elements of the
* outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
*
* @param f the function to apply to each element.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` resulting from applying
* the given function `f` to each element of the outer $coll
* that satisfies predicate `p` and collecting the results.
*
* @usecase def map[B](f: A => B): $Coll[B]
*
* @return a new $coll resulting from applying the given function
* `f` to each element of the outer $coll that satisfies
* predicate `p` and collecting the results.
*/
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- self)
if (p(x)) b += f(x)
b.result
}
/** Builds a new collection by applying a function to all elements of the
* outer $coll containing this `WithFilter` instance that satisfy
* predicate `p` and concatenating the results.
*
* @param f the function to apply to each element.
* @tparam B the element type of the returned collection.
* @tparam That $thatinfo
* @param bf $bfinfo
* @return a new collection of type `That` resulting from applying
* the given collection-valued function `f` to each element
* of the outer $coll that satisfies predicate `p` and
* concatenating the results.
*
* @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
*
* @return a new $coll resulting from applying the given collection-valued function
* `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
*/
def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
val b = bf(repr)
for (x <- self)
if (p(x)) b ++= f(x).seq
b.result
}
/** Applies a function `f` to all elements of the outer $coll containing
* this `WithFilter` instance that satisfy predicate `p`.
*
* @param f the function that is applied for its side-effect to every element.
* The result of function `f` is discarded.
*
* @tparam U the type parameter describing the result of function `f`.
* This result will always be ignored. Typically `U` is `Unit`,
* but this is not necessary.
*
* @usecase def foreach(f: A => Unit): Unit
*/
def foreach[U](f: A => U): Unit =
for (x <- self)
if (p(x)) f(x)
/** Further refines the filter for this $coll.
*
* @param q the predicate used to test elements.
* @return an object of class `WithFilter`, which supports
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
* All these operations apply to those elements of this $coll which
* satisfy the predicate `q` in addition to the predicate `p`.
*/
def withFilter(q: A => Boolean): WithFilter =
new WithFilter(x => p(x) && q(x))
}
// A helper for tails and inits.
private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
it ++ Iterator(Nil) map (newBuilder ++= _ result)
}
}
</textarea>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
theme: "ambiance",
mode: "text/x-scala"
});
</script>
</article>

59
lib/redactor/codemirror/mode/clike/test.js vendored

@ -1,59 +0,0 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-c");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
MT("indent",
"[type void] [def foo]([type void*] [variable a], [type int] [variable b]) {",
" [type int] [variable c] [operator =] [variable b] [operator +]",
" [number 1];",
" [keyword return] [operator *][variable a];",
"}");
MT("indent_switch",
"[keyword switch] ([variable x]) {",
" [keyword case] [number 10]:",
" [keyword return] [number 20];",
" [keyword default]:",
" [variable printf]([string \"foo %c\"], [variable x]);",
"}");
MT("def",
"[type void] [def foo]() {}",
"[keyword struct] [def bar]{}",
"[type int] [type *][def baz]() {}");
MT("def_new_line",
"::[variable std]::[variable SomeTerribleType][operator <][variable T][operator >]",
"[def SomeLongMethodNameThatDoesntFitIntoOneLine]([keyword const] [variable MyType][operator &] [variable param]) {}")
MT("double_block",
"[keyword for] (;;)",
" [keyword for] (;;)",
" [variable x][operator ++];",
"[keyword return];");
MT("preprocessor",
"[meta #define FOO 3]",
"[type int] [variable foo];",
"[meta #define BAR\\]",
"[meta 4]",
"[type unsigned] [type int] [variable bar] [operator =] [number 8];",
"[meta #include <baz> ][comment // comment]")
var mode_cpp = CodeMirror.getMode({indentUnit: 2}, "text/x-c++src");
function MTCPP(name) { test.mode(name, mode_cpp, Array.prototype.slice.call(arguments, 1)); }
MTCPP("cpp14_literal",
"[number 10'000];",
"[number 0b10'000];",
"[number 0x10'000];",
"[string '100000'];");
MTCPP("ctor_dtor",
"[def Foo::Foo]() {}",
"[def Foo::~Foo]() {}");
})();

18
lib/redactor/codemirror/mode/css/css.js vendored

@ -77,9 +77,9 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
return ret("qualifier", "qualifier"); return ret("qualifier", "qualifier");
} else if (/[:;{}\[\]\(\)]/.test(ch)) { } else if (/[:;{}\[\]\(\)]/.test(ch)) {
return ret(null, ch); return ret(null, ch);
} else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) || } else if (((ch == "u" || ch == "U") && stream.match(/rl(-prefix)?\(/i)) ||
(ch == "d" && stream.match("omain(")) || ((ch == "d" || ch == "D") && stream.match("omain(", true, true)) ||
(ch == "r" && stream.match("egexp("))) { ((ch == "r" || ch == "R") && stream.match("egexp(", true, true))) {
stream.backUp(1); stream.backUp(1);
state.tokenize = tokenParenthesized; state.tokenize = tokenParenthesized;
return ret("property", "word"); return ret("property", "word");
@ -162,16 +162,16 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
return pushContext(state, stream, "block"); return pushContext(state, stream, "block");
} else if (type == "}" && state.context.prev) { } else if (type == "}" && state.context.prev) {
return popContext(state); return popContext(state);
} else if (supportsAtComponent && /@component/.test(type)) { } else if (supportsAtComponent && /@component/i.test(type)) {
return pushContext(state, stream, "atComponentBlock"); return pushContext(state, stream, "atComponentBlock");
} else if (/^@(-moz-)?document$/.test(type)) { } else if (/^@(-moz-)?document$/i.test(type)) {
return pushContext(state, stream, "documentTypes"); return pushContext(state, stream, "documentTypes");
} else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) { } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
return pushContext(state, stream, "atBlock"); return pushContext(state, stream, "atBlock");
} else if (/^@(font-face|counter-style)/.test(type)) { } else if (/^@(font-face|counter-style)/i.test(type)) {
state.stateArg = type; state.stateArg = type;
return "restricted_atBlock_before"; return "restricted_atBlock_before";
} else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
return "keyframes"; return "keyframes";
} else if (type && type.charAt(0) == "@") { } else if (type && type.charAt(0) == "@") {
return pushContext(state, stream, "at"); return pushContext(state, stream, "at");
@ -793,7 +793,7 @@ CodeMirror.defineMode("css", function(config, parserConfig) {
}, },
"@": function(stream) { "@": function(stream) {
if (stream.eat("{")) return [null, "interpolation"]; if (stream.eat("{")) return [null, "interpolation"];
if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
stream.eatWhile(/[\w\\\-]/); stream.eatWhile(/[\w\\\-]/);
if (stream.match(/^\s*:/, false)) if (stream.match(/^\s*:/, false))
return ["variable-2", "variable-definition"]; return ["variable-2", "variable-definition"];

103
lib/redactor/codemirror/mode/css/gss.html vendored

@ -1,103 +0,0 @@
<!doctype html>
<title>CodeMirror: Closure Stylesheets (GSS) mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../addon/hint/show-hint.css">
<script src="../../lib/codemirror.js"></script>
<script src="css.js"></script>
<script src="../../addon/hint/show-hint.js"></script>
<script src="../../addon/hint/css-hint.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Closure Stylesheets (GSS)</a>
</ul>
</div>
<article>
<h2>Closure Stylesheets (GSS) mode</h2>
<form><textarea id="code" name="code">
/* Some example Closure Stylesheets */
@provide 'some.styles';
@require 'other.styles';
@component {
@def FONT_FAMILY "Times New Roman", Georgia, Serif;
@def FONT_SIZE_NORMAL 15px;
@def FONT_NORMAL normal FONT_SIZE_NORMAL FONT_FAMILY;
@def BG_COLOR rgb(235, 239, 249);
@def DIALOG_BORDER_COLOR rgb(107, 144, 218);
@def DIALOG_BG_COLOR BG_COLOR;
@def LEFT_HAND_NAV_WIDTH 180px;
@def LEFT_HAND_NAV_PADDING 3px;
@defmixin size(WIDTH, HEIGHT) {
width: WIDTH;
height: HEIGHT;
}
body {
background-color: BG_COLOR;
margin: 0;
padding: 3em 6em;
font: FONT_NORMAL;
color: #000;
}
#navigation a {
font-weight: bold;
text-decoration: none !important;
}
.dialog {
background-color: DIALOG_BG_COLOR;
border: 1px solid DIALOG_BORDER_COLOR;
}
.content {
position: absolute;
margin-left: add(LEFT_HAND_NAV_PADDING, /* padding left */
LEFT_HAND_NAV_WIDTH,
LEFT_HAND_NAV_PADDING); /* padding right */
}
.logo {
@mixin size(150px, 55px);
background-image: url('http://www.google.com/images/logo_sm.gif');
}
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
extraKeys: {"Ctrl-Space": "autocomplete"},
lineNumbers: true,
matchBrackets: "text/x-less",
mode: "text/x-gss"
});
</script>
<p>A mode for <a href="https://github.com/google/closure-stylesheets">Closure Stylesheets</a> (GSS).</p>
<p><strong>MIME type defined:</strong> <code>text/x-gss</code>.</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gss_*">normal</a>, <a href="../../test/index.html#verbose,gss_*">verbose</a>.</p>
</article>

17
lib/redactor/codemirror/mode/css/gss_test.js vendored

@ -1,17 +0,0 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
"use strict";
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-gss");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "gss"); }
MT("atComponent",
"[def @component] {",
"[tag foo] {",
" [property color]: [keyword black];",
"}",
"}");
})();

75
lib/redactor/codemirror/mode/css/index.html vendored

@ -1,75 +0,0 @@
<!doctype html>
<title>CodeMirror: CSS mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="../../addon/hint/show-hint.css">
<script src="../../lib/codemirror.js"></script>
<script src="css.js"></script>
<script src="../../addon/hint/show-hint.js"></script>
<script src="../../addon/hint/css-hint.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">CSS</a>
</ul>
</div>
<article>
<h2>CSS mode</h2>
<form><textarea id="code" name="code">
/* Some example CSS */
@import url("something.css");
body {
margin: 0;
padding: 3em 6em;
font-family: tahoma, arial, sans-serif;
color: #000;
}
#navigation a {
font-weight: bold;
text-decoration: none !important;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.7em;
}
h1:before, h2:before {
content: "::";
}
code {
font-family: courier, monospace;
font-size: 80%;
color: #418A8A;
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
extraKeys: {"Ctrl-Space": "autocomplete"}
});
</script>
<p><strong>MIME types defined:</strong> <code>text/css</code>, <code>text/x-scss</code> (<a href="scss.html">demo</a>), <code>text/x-less</code> (<a href="less.html">demo</a>).</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#css_*">normal</a>, <a href="../../test/index.html#verbose,css_*">verbose</a>.</p>
</article>

152
lib/redactor/codemirror/mode/css/less.html vendored

@ -1,152 +0,0 @@
<!doctype html>
<title>CodeMirror: LESS mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../../addon/edit/matchbrackets.js"></script>
<script src="css.js"></script>
<style>.CodeMirror {border: 1px solid #ddd; line-height: 1.2;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">LESS</a>
</ul>
</div>
<article>
<h2>LESS mode</h2>
<form><textarea id="code" name="code">@media screen and (device-aspect-ratio: 16/9) { … }
@media screen and (device-aspect-ratio: 1280/720) { … }
@media screen and (device-aspect-ratio: 2560/1440) { … }
html:lang(fr-be)
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
img:nth-of-type(2n+1) { float: right; }
img:nth-of-type(2n) { float: left; }
body > h2:not(:first-of-type):not(:last-of-type)
html|*:not(:link):not(:visited)
*|*:not(:hover)
p::first-line { text-transform: uppercase }
@namespace foo url(http://www.example.com);
foo|h1 { color: blue } /* first rule */
span[hello="Ocean"][goodbye="Land"]
E[foo]{
padding:65px;
}
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5
}
button::-moz-focus-inner,
input::-moz-focus-inner { // Inner padding and border oddities in FF3/4
padding: 0;
border: 0;
}
.btn {
// reset here as of 2.0.3 due to Recess property order
border-color: #ccc;
border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);
}
fieldset span button, fieldset span input[type="file"] {
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
}
.rounded-corners (@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
@import url("something.css");
@light-blue: hsl(190, 50%, 65%);
#menu {
position: absolute;
width: 100%;
z-index: 3;
clear: both;
display: block;
background-color: @blue;
height: 42px;
border-top: 2px solid lighten(@alpha-blue, 20%);
border-bottom: 2px solid darken(@alpha-blue, 25%);
.box-shadow(0, 1px, 8px, 0.6);
-moz-box-shadow: 0 0 0 #000; // Because firefox sucks.
&.docked {
background-color: hsla(210, 60%, 40%, 0.4);
}
&:hover {
background-color: @blue;
}
#dropdown {
margin: 0 0 0 117px;
padding: 0;
padding-top: 5px;
display: none;
width: 190px;
border-top: 2px solid @medium;
color: @highlight;
border: 2px solid darken(@medium, 25%);
border-left-color: darken(@medium, 15%);
border-right-color: darken(@medium, 15%);
border-top-width: 0;
background-color: darken(@medium, 10%);
ul {
padding: 0px;
}
li {
font-size: 14px;
display: block;
text-align: left;
padding: 0;
border: 0;
a {
display: block;
padding: 0px 15px;
text-decoration: none;
color: white;
&:hover {
background-color: darken(@medium, 15%);
text-decoration: none;
}
}
}
.border-radius(5px, bottom);
.box-shadow(0, 6px, 8px, 0.5);
}
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers : true,
matchBrackets : true,
mode: "text/x-less"
});
</script>
<p>The LESS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>).</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#less_*">normal</a>, <a href="../../test/index.html#verbose,less_*">verbose</a>.</p>
</article>

54
lib/redactor/codemirror/mode/css/less_test.js vendored

@ -1,54 +0,0 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
"use strict";
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-less");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "less"); }
MT("variable",
"[variable-2 @base]: [atom #f04615];",
"[qualifier .class] {",
" [property width]: [variable percentage]([number 0.5]); [comment // returns `50%`]",
" [property color]: [variable saturate]([variable-2 @base], [number 5%]);",
"}");
MT("amp",
"[qualifier .child], [qualifier .sibling] {",
" [qualifier .parent] [atom &] {",
" [property color]: [keyword black];",
" }",
" [atom &] + [atom &] {",
" [property color]: [keyword red];",
" }",
"}");
MT("mixin",
"[qualifier .mixin] ([variable dark]; [variable-2 @color]) {",
" [property color]: [atom darken]([variable-2 @color], [number 10%]);",
"}",
"[qualifier .mixin] ([variable light]; [variable-2 @color]) {",
" [property color]: [atom lighten]([variable-2 @color], [number 10%]);",
"}",
"[qualifier .mixin] ([variable-2 @_]; [variable-2 @color]) {",
" [property display]: [atom block];",
"}",
"[variable-2 @switch]: [variable light];",
"[qualifier .class] {",
" [qualifier .mixin]([variable-2 @switch]; [atom #888]);",
"}");
MT("nest",
"[qualifier .one] {",
" [def @media] ([property width]: [number 400px]) {",
" [property font-size]: [number 1.2em];",
" [def @media] [attribute print] [keyword and] [property color] {",
" [property color]: [keyword blue];",
" }",
" }",
"}");
MT("interpolation", ".@{[variable foo]} { [property font-weight]: [atom bold]; }");
})();

157
lib/redactor/codemirror/mode/css/scss.html vendored

@ -1,157 +0,0 @@
<!doctype html>
<title>CodeMirror: SCSS mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="css.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">SCSS</a>
</ul>
</div>
<article>
<h2>SCSS mode</h2>
<form><textarea id="code" name="code">
/* Some example SCSS */
@import "compass/css3";
$variable: #333;
$blue: #3bbfce;
$margin: 16px;
.content-navigation {
#nested {
background-color: black;
}
border-color: $blue;
color:
darken($blue, 9%);
}
.border {
padding: $margin / 2;
margin: $margin / 2;
border-color: $blue;
}
@mixin table-base {
th {
text-align: center;
font-weight: bold;
}
td, th {padding: 2px}
}
table.hl {
margin: 2em 0;
td.ln {
text-align: right;
}
}
li {
font: {
family: serif;
weight: bold;
size: 1.2em;
}
}
@mixin left($dist) {
float: left;
margin-left: $dist;
}
#data {
@include left(10px);
@include table-base;
}
.source {
@include flow-into(target);
border: 10px solid green;
margin: 20px;
width: 200px; }
.new-container {
@include flow-from(target);
border: 10px solid red;
margin: 20px;
width: 200px; }
body {
margin: 0;
padding: 3em 6em;
font-family: tahoma, arial, sans-serif;
color: #000;
}
@mixin yellow() {
background: yellow;
}
.big {
font-size: 14px;
}
.nested {
@include border-radius(3px);
@extend .big;
p {
background: whitesmoke;
a {
color: red;
}
}
}
#navigation a {
font-weight: bold;
text-decoration: none !important;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.7em;
}
h1:before, h2:before {
content: "::";
}
code {
font-family: courier, monospace;
font-size: 80%;
color: #418A8A;
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-scss"
});
</script>
<p>The SCSS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>).</p>
<p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#scss_*">normal</a>, <a href="../../test/index.html#verbose,scss_*">verbose</a>.</p>
</article>

110
lib/redactor/codemirror/mode/css/scss_test.js vendored

@ -1,110 +0,0 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); }
MT('url_with_quotation',
"[tag foo] { [property background]:[atom url]([string test.jpg]) }");
MT('url_with_double_quotes',
"[tag foo] { [property background]:[atom url]([string \"test.jpg\"]) }");
MT('url_with_single_quotes',
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) }");
MT('string',
"[def @import] [string \"compass/css3\"]");
MT('important_keyword',
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) [keyword !important] }");
MT('variable',
"[variable-2 $blue]:[atom #333]");
MT('variable_as_attribute',
"[tag foo] { [property color]:[variable-2 $blue] }");
MT('numbers',
"[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }");
MT('number_percentage',
"[tag foo] { [property width]:[number 80%] }");
MT('selector',
"[builtin #hello][qualifier .world]{}");
MT('singleline_comment',
"[comment // this is a comment]");
MT('multiline_comment',
"[comment /*foobar*/]");
MT('attribute_with_hyphen',
"[tag foo] { [property font-size]:[number 10px] }");
MT('string_after_attribute',
"[tag foo] { [property content]:[string \"::\"] }");
MT('directives',
"[def @include] [qualifier .mixin]");
MT('basic_structure',
"[tag p] { [property background]:[keyword red]; }");
MT('nested_structure',
"[tag p] { [tag a] { [property color]:[keyword red]; } }");
MT('mixin',
"[def @mixin] [tag table-base] {}");
MT('number_without_semicolon',
"[tag p] {[property width]:[number 12]}",
"[tag a] {[property color]:[keyword red];}");
MT('atom_in_nested_block',
"[tag p] { [tag a] { [property color]:[atom #000]; } }");
MT('interpolation_in_property',
"[tag foo] { #{[variable-2 $hello]}:[number 2]; }");
MT('interpolation_in_selector',
"[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }");
MT('interpolation_error',
"[tag foo]#{[variable foo]} { [property color]:[atom #000]; }");
MT("divide_operator",
"[tag foo] { [property width]:[number 4] [operator /] [number 2] }");
MT('nested_structure_with_id_selector',
"[tag p] { [builtin #hello] { [property color]:[keyword red]; } }");
MT('indent_mixin',
"[def @mixin] [tag container] (",
" [variable-2 $a]: [number 10],",
" [variable-2 $b]: [number 10])",
"{}");
MT('indent_nested',
"[tag foo] {",
" [tag bar] {",
" }",
"}");
MT('indent_parentheses',
"[tag foo] {",
" [property color]: [atom darken]([variable-2 $blue],",
" [number 9%]);",
"}");
MT('indent_vardef',
"[variable-2 $name]:",
" [string 'val'];",
"[tag tag] {",
" [tag inner] {",
" [property margin]: [number 3px];",
" }",
"}");
})();

206
lib/redactor/codemirror/mode/css/test.js vendored

@ -1,206 +0,0 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "css");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
// Error, because "foobarhello" is neither a known type or property, but
// property was expected (after "and"), and it should be in parentheses.
MT("atMediaUnknownType",
"[def @media] [attribute screen] [keyword and] [error foobarhello] { }");
// Soft error, because "foobarhello" is not a known property or type.
MT("atMediaUnknownProperty",
"[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }");
// Make sure nesting works with media queries
MT("atMediaMaxWidthNested",
"[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }");
MT("atMediaFeatureValueKeyword",
"[def @media] ([property orientation]: [keyword landscape]) { }");
MT("atMediaUnknownFeatureValueKeyword",
"[def @media] ([property orientation]: [error upsidedown]) { }");
MT("tagSelector",
"[tag foo] { }");
MT("classSelector",
"[qualifier .foo-bar_hello] { }");
MT("idSelector",
"[builtin #foo] { [error #foo] }");
MT("tagSelectorUnclosed",
"[tag foo] { [property margin]: [number 0] } [tag bar] { }");
MT("tagStringNoQuotes",
"[tag foo] { [property font-family]: [variable hello] [variable world]; }");
MT("tagStringDouble",
"[tag foo] { [property font-family]: [string \"hello world\"]; }");
MT("tagStringSingle",
"[tag foo] { [property font-family]: [string 'hello world']; }");
MT("tagColorKeyword",
"[tag foo] {",
" [property color]: [keyword black];",
" [property color]: [keyword navy];",
" [property color]: [keyword yellow];",
"}");
MT("tagColorHex3",
"[tag foo] { [property background]: [atom #fff]; }");
MT("tagColorHex4",
"[tag foo] { [property background]: [atom #ffff]; }");
MT("tagColorHex6",
"[tag foo] { [property background]: [atom #ffffff]; }");
MT("tagColorHex8",
"[tag foo] { [property background]: [atom #ffffffff]; }");
MT("tagColorHex5Invalid",
"[tag foo] { [property background]: [atom&error #fffff]; }");
MT("tagColorHexInvalid",
"[tag foo] { [property background]: [atom&error #ffg]; }");
MT("tagNegativeNumber",
"[tag foo] { [property margin]: [number -5px]; }");
MT("tagPositiveNumber",
"[tag foo] { [property padding]: [number 5px]; }");
MT("tagVendor",
"[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }");
MT("tagBogusProperty",
"[tag foo] { [property&error barhelloworld]: [number 0]; }");
MT("tagTwoProperties",
"[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }");
MT("tagTwoPropertiesURL",
"[tag foo] { [property background]: [atom url]([string //example.com/foo.png]); [property padding]: [number 0]; }");
MT("indent_tagSelector",
"[tag strong], [tag em] {",
" [property background]: [atom rgba](",
" [number 255], [number 255], [number 0], [number .2]",
" );",
"}");
MT("indent_atMedia",
"[def @media] {",
" [tag foo] {",
" [property color]:",
" [keyword yellow];",
" }",
"}");
MT("indent_comma",
"[tag foo] {",
" [property font-family]: [variable verdana],",
" [atom sans-serif];",
"}");
MT("indent_parentheses",
"[tag foo]:[variable-3 before] {",
" [property background]: [atom url](",
"[string blahblah]",
"[string etc]",
"[string ]) [keyword !important];",
"}");
MT("font_face",
"[def @font-face] {",
" [property font-family]: [string 'myfont'];",
" [error nonsense]: [string 'abc'];",
" [property src]: [atom url]([string http://blah]),",
" [atom url]([string http://foo]);",
"}");
MT("empty_url",
"[def @import] [atom url]() [attribute screen];");
MT("parens",
"[qualifier .foo] {",
" [property background-image]: [variable fade]([atom #000], [number 20%]);",
" [property border-image]: [atom linear-gradient](",
" [atom to] [atom bottom],",
" [variable fade]([atom #000], [number 20%]) [number 0%],",
" [variable fade]([atom #000], [number 20%]) [number 100%]",
" );",
"}");
MT("css_variable",
":[variable-3 root] {",
" [variable-2 --main-color]: [atom #06c];",
"}",
"[tag h1][builtin #foo] {",
" [property color]: [atom var]([variable-2 --main-color]);",
"}");
MT("supports",
"[def @supports] ([keyword not] (([property text-align-last]: [atom justify]) [keyword or] ([meta -moz-][property text-align-last]: [atom justify])) {",
" [property text-align-last]: [atom justify];",
"}");
MT("document",
"[def @document] [tag url]([string http://blah]),",
" [tag url-prefix]([string https://]),",
" [tag domain]([string blah.com]),",
" [tag regexp]([string \".*blah.+\"]) {",
" [builtin #id] {",
" [property background-color]: [keyword white];",
" }",
" [tag foo] {",
" [property font-family]: [variable Verdana], [atom sans-serif];",
" }",
"}");
MT("document_url",
"[def @document] [tag url]([string http://blah]) { [qualifier .class] { } }");
MT("document_urlPrefix",
"[def @document] [tag url-prefix]([string https://]) { [builtin #id] { } }");
MT("document_domain",
"[def @document] [tag domain]([string blah.com]) { [tag foo] { } }");
MT("document_regexp",
"[def @document] [tag regexp]([string \".*blah.+\"]) { [builtin #id] { } }");
MT("counter-style",
"[def @counter-style] [variable binary] {",
" [property system]: [atom numeric];",
" [property symbols]: [number 0] [number 1];",
" [property suffix]: [string \".\"];",
" [property range]: [atom infinite];",
" [property speak-as]: [atom numeric];",
"}");
MT("counter-style-additive-symbols",
"[def @counter-style] [variable simple-roman] {",
" [property system]: [atom additive];",
" [property additive-symbols]: [number 10] [variable X], [number 5] [variable V], [number 1] [variable I];",
" [property range]: [number 1] [number 49];",
"}");
MT("counter-style-use",
"[tag ol][qualifier .roman] { [property list-style]: [variable simple-roman]; }");
MT("counter-style-symbols",
"[tag ol] { [property list-style]: [atom symbols]([atom cyclic] [string \"*\"] [string \"\\2020\"] [string \"\\2021\"] [string \"\\A7\"]); }");
MT("comment-does-not-disrupt",
"[def @font-face] [comment /* foo */] {",
" [property src]: [atom url]([string x]);",
" [property font-family]: [variable One];",
"}")
})();

9
lib/redactor/codemirror/mode/htmlembedded/htmlembedded.js vendored

@ -14,7 +14,16 @@
"use strict"; "use strict";
CodeMirror.defineMode("htmlembedded", function(config, parserConfig) { CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
var closeComment = parserConfig.closeComment || "--%>"
return CodeMirror.multiplexingMode(CodeMirror.getMode(config, "htmlmixed"), { return CodeMirror.multiplexingMode(CodeMirror.getMode(config, "htmlmixed"), {
open: parserConfig.openComment || "<%--",
close: closeComment,
delimStyle: "comment",
mode: {token: function(stream) {
stream.skipTo(closeComment) || stream.skipToEnd()
return "comment"
}}
}, {
open: parserConfig.open || parserConfig.scriptStartRegex || "<%", open: parserConfig.open || parserConfig.scriptStartRegex || "<%",
close: parserConfig.close || parserConfig.scriptEndRegex || "%>", close: parserConfig.close || parserConfig.scriptEndRegex || "%>",
mode: CodeMirror.getMode(config, parserConfig.scriptingModeSpec) mode: CodeMirror.getMode(config, parserConfig.scriptingModeSpec)

60
lib/redactor/codemirror/mode/htmlembedded/index.html vendored

@ -1,60 +0,0 @@
<!doctype html>
<title>CodeMirror: Html Embedded Scripts mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="../htmlmixed/htmlmixed.js"></script>
<script src="../../addon/mode/multiplex.js"></script>
<script src="htmlembedded.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Html Embedded Scripts</a>
</ul>
</div>
<article>
<h2>Html Embedded Scripts mode</h2>
<form><textarea id="code" name="code">
<%
function hello(who) {
return "Hello " + who;
}
%>
This is an example of EJS (embedded javascript)
<p>The program says <%= hello("world") %>.</p>
<script>
alert("And here is some normal JS code"); // also colored
</script>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "application/x-ejs",
indentUnit: 4,
indentWithTabs: true
});
</script>
<p>Mode for html embedded scripts like JSP and ASP.NET. Depends on multiplex and HtmlMixed which in turn depends on
JavaScript, CSS and XML.<br />Other dependencies include those of the scripting language chosen.</p>
<p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET),
<code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)
and <code>application/x-erb</code></p>
</article>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save