Разработка модуля с админкой для DLE

В этой заметке будет рассмотрено создание модуля для CMS DLE с админской частью.
Модуль в DLE – это набор файлов расположенных в определённых директориях. Модуль будет состоять из 4 файлов:

1. engine/modules/aphorism.php
2. engine/data/aphorismconfig.php
3. engine/inc/aphorism.php
4. {THEME}/aphorism.php

Для подключения админки модуля в таблице префикс_admin_sections необходимо создать запись о новом стороннем модуле, запрос может выглядеть следующим образом:

INSERT INTO `префикс_admin_sections` (`name`, `title`, `descr`, `icon`, `allow_groups`) VALUES
('aphorism', 'Афоризм', 'Высказывания знаменитых людей', 'aphorism.png', '1');

Для того, что бы в шаблонах сайта распознаваля тэг {aphorism} необходимо отредактировать файл index.php внеся следующие корректировки:

после строки

require_once ROOT_DIR . '/engine/init.php';

вставляем

require_once ENGINE_DIR.'/modules/aphorism.php';

после строки

$tpl->set ( '{speedbar}', $tpl->result['speedbar'] );

вставляем

$tpl->set ( '{aphorism}', $tpl->result['aphorism'] );

Файл engine/modules/aphorism.php содержит основные функции модуля:

<?php
if( ! defined( 'DATALIFEENGINE' ) ) {
    die( "Hacking attempt!" );
}

require_once ENGINE_DIR.'/data/aphorismconfig.php';

$author  = $aphorismconfig['author'];
$text    = $aphorismconfig['text'];
$version = $aphorismconfig['version'];

$tpl->load_template('aphorism.tpl');
$tpl->set('{author}',  $author);
$tpl->set('{text}',    $text);
$tpl->set('{version}', $version);

$tpl->compile('aphorism');
$tpl->clear();

Файл engine/data/aphorismconfig.php содержит конфигурацию модуля. Содержимое файла генерируется скриптом.

Файл engine/inc/aphorism.php содержит административную часть модуля:

<?php
// конфиг
require_once (ENGINE_DIR.'/data/aphorismconfig.php');

/**
 * Сохранение настроек модуля
 */
if ($action == "dosave") {
    $find[]     = "'\r'";
    $replace[]  = "";
    $find[]     = "'\n'";
    $replace[]  = "";

    $handler = @fopen(ENGINE_DIR.'/data/aphorismconfig.php', "wb");
    fwrite ($handler, "<?php \n\n//Aphorism config
                         \n\n\$aphorismconfig = array(
                         \n\n'version' => \"v.1.0\",\n\n");

    foreach ($_POST['save_con'] as $name => $value) {
        $value = trim(stripslashes ($value));
        $value = htmlspecialchars  ($value, ENT_QUOTES);
        $value = preg_replace($find, $replace, $value);
        fwrite($handler, "'{$name}' => \"{$value}\",\n\n");
    }

    fwrite($handler, ");\n\n?>");
    fclose($handler);

    msg ("info", "Строка изменена",
        "{$lang['opt_sysok_1']}<br /><br />
      <a href=\"{$PHP_SELF}?mod=aphorism\">{$lang['db_prev']}</a>");
}

/**
 * Вывод header
 */
echoheader("Aphorism", "Админпанель модуля Афоризм");

/**
 * Вывод блока настроек
 */
opentable();
tableheader('Настройка модуля');
echo<<<HTML
<form action="" method="POST">
<table width="100%">
  <tr>
    <td class="option" style="padding:4px;">
      <b> Автор: </b><br />
      <span class="small"> например: Василий Пупкин</span>
    <td align="middle" width="400">
      <input class="edit" style="text-align:center" size="40" value="{$aphorismconfig['author']}" name="save_con[author]"></td>
  </tr>

  <tr><td background="engine/skins/images/mline.gif" height="1" colspan="2"></td></tr>

  <tr>
    <td class="option" style="padding:4px;">
       <b> Афоризм: </b><br />
       <span class="small"> например: Меньше знаешь - крепче спишь </span>
    <td align="middle" width="400">
       <input class="edit" style="text-align:center" size="40" value="{$aphorismconfig['text']}" name="save_con"></td>
  </tr>

  <tr><td background="engine/skins/images/mline.gif" height="1" colspan="2"></td></tr>

  <tr>
    <td class="option" style="padding-bottom:10px; padding-top:10px; padding-left:10px;" colspan="2">
      <input class="buttons" type="hidden" name="action" value="dosave" />
      <input class="buttons" type="submit" name="do" value=" Сохранить " /></td>
  </tr>

</table>
</form>
HTML;
closetable();

/**
 * Вывод footer
 */
echofooter();

/**
 * Элементы дизайна админпанели
 */
function opentable() {

    echo <<<HTML
<table width="100%">
    <tr>
        <td width="4"><img src="engine/skins/images/tl_lo.gif" width="4" height="4" border="0"></td>
        <td background="engine/skins/images/tl_oo.gif"><img src="engine/skins/images/tl_oo.gif" width="1" height="4" border="0"></td>
        <td width="6"><img src="engine/skins/images/tl_ro.gif" width="6" height="4" border="0"></td>
    </tr>
    <tr>
        <td background="engine/skins/images/tl_lb.gif"><img src="engine/skins/images/tl_lb.gif" width="4" height="1" border="0"></td>
        <td style="padding:5px;" bgcolor="#FFFFFF">
HTML;
}

function closetable() {
    echo <<<HTML
    </td>
        <td background="engine/skins/images/tl_rb.gif"><img src="engine/skins/images/tl_rb.gif" width="6" height="1" border="0"></td>
    </tr>
    <tr>
        <td><img src="engine/skins/images/tl_lu.gif" width="4" height="6" border="0"></td>
        <td background="engine/skins/images/tl_ub.gif"><img src="engine/skins/images/tl_ub.gif" width="1" height="6" border="0"></td>
        <td><img src="engine/skins/images/tl_ru.gif" width="6" height="6" border="0"></td>
    </tr>
</table>
HTML;
}

function tableheader($value) {
    echo <<<HTML
<table width="100%">
    <tr>
        <td bgcolor="#EFEFEF" height="29" style="padding-left:10px;">
          <div class="navigation">$value</div></td>
    </tr>
</table>
<div class="unterline"></div>
HTML;
}