Skip to content

Commit

Permalink
Merge pull request #4 from zettend/master
Browse files Browse the repository at this point in the history
Система плагинов DLE
  • Loading branch information
pafnuty authored Jul 24, 2021
2 parents 0d2ffbe + aef3329 commit 3bb772d
Show file tree
Hide file tree
Showing 10 changed files with 381 additions and 43 deletions.
Binary file added .DS_Store
Binary file not shown.
3 changes: 0 additions & 3 deletions .github/ISSUE_TEMPLATE.md

This file was deleted.

3 changes: 0 additions & 3 deletions .github/PULL_REQUEST_TEMPLATE.md

This file was deleted.

2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.DS_Store
.vscode
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# DLE-Asset
Модуль для автоматического подключения стилей и скриптов в шаблон DLE

![version](https://img.shields.io/badge/version-1.1.1-red.svg?style=flat-square "Version")
![DLE](https://img.shields.io/badge/DLE-9.x-green.svg?style=flat-square "DLE Version")
![version](https://img.shields.io/badge/version-2.0.0-red.svg?style=flat-square "Version")
![DLE](https://img.shields.io/badge/DLE-14.x-green.svg?style=flat-square "DLE Version")
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/pafnuty/DLE-Asset/blob/master/LICENSE)

## Назнчение
Expand All @@ -15,14 +15,17 @@


## Установка
- Распаковать содержимое папки **upload** в корень сайта.
### DLE 14
- Загрузить через систему плагинов файл dle-asset.xml
- В **main.tpl**, в нужном месте прописать строку подключения модуля:
```smarty

Вот так:
```smarty
{include file="engine/modules/asset/add.php?folder={THEME}/css/"}
{include file="engine/modules/asset/add.php?folder={THEME}/js/"}
```
Или так:
```
{include file="engine/modules/asset/add.php?folder={THEME}/css/,{THEME}/js/&ignore=main"}
```

Expand Down
312 changes: 312 additions & 0 deletions dle-asset.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,312 @@
<?xml version="1.0" encoding="utf-8"?>
<dleplugin>
<name>DLE-Asset</name>
<description>Модуль для автоматического подключения стилей и скриптов в шаблон</description>
<icon></icon>
<version>2.0.0</version>
<dleversion>14.0</dleversion>
<versioncompare>greater</versioncompare>
<upgradeurl>https://raw.githubusercontent.com/zettend/DLE-Asset/master/update.json</upgradeurl>
<filedelete>0</filedelete>
<needplugin></needplugin>
<mnotice>0</mnotice>
<mysqlinstall><![CDATA[]]></mysqlinstall>
<mysqlupgrade><![CDATA[]]></mysqlupgrade>
<mysqlenable><![CDATA[]]></mysqlenable>
<mysqldisable><![CDATA[]]></mysqldisable>
<mysqldelete><![CDATA[]]></mysqldelete>
<phpinstall><![CDATA[]]></phpinstall>
<phpupgrade><![CDATA[]]></phpupgrade>
<phpenable><![CDATA[]]></phpenable>
<phpdisable><![CDATA[]]></phpdisable>
<phpdelete><![CDATA[]]></phpdelete>
<notice><![CDATA[В main.tpl, в нужном месте прописать строку подключения модуля:
Вот так:
{include file="engine/modules/asset/add.php?folder={THEME}/css/"}
{include file="engine/modules/asset/add.php?folder={THEME}/js/"}
Или так:
{include file="engine/modules/asset/add.php?folder={THEME}/css/,{THEME}/js/&ignore=main"}
Добавление отдельного файла:
{include file="engine/modules/asset/addFile.php?file={THEME}/js/main.js"}]]></notice>
<file name="engine/modules/asset/add.php">
<operation action="create">
<replacecode><![CDATA[<?php
/*
=============================================================================
DLE-Asset — автозагрузка стилей и скриптов для DLE
=============================================================================
Автор: ПафНутиЙ
URL: http://pafnuty.name/
twitter: https://twitter.com/pafnuty_name
email: [email protected]
=============================================================================
=============================================================================
Портировал на DLE 14+ zettend. На версиях ниже не проверялось.
=============================================================================
Автор: zettend
URL: https://zettend.ru/
Telegram: https://t.me/zettend
email: [email protected]
=============================================================================
*/
if( !defined('DATALIFEENGINE') ) {
die("Hacking attempt!");
}
$assetFolder = !empty($folder) ? str_replace('{THEME}', '/templates/' . $config['skin'], $folder) : false;
$assetIgnore = !empty($ignore) ? str_replace('{THEME}', '/templates/' . $config['skin'], $ignore) : '';
if ($assetFolder) {
include_once (DLEPlugins::Check(ENGINE_DIR . '/modules/asset/asset.php'));
$compress = $config['js_min'];
dleAsset::add(
explode(',', $assetFolder),
explode(',', $assetIgnore),
$compress
);
}
]]></replacecode>
</operation>
</file>
<file name="engine/modules/asset/addFile.php">
<operation action="create">
<replacecode><![CDATA[<?php
/*
=============================================================================
DLE-Asset — автозагрузка стилей и скриптов для DLE
=============================================================================
Автор: ПафНутиЙ
URL: http://pafnuty.name/
twitter: https://twitter.com/pafnuty_name
email: [email protected]
=============================================================================
=============================================================================
Портировал на DLE 14+ zettend. На версиях ниже не проверялось.
=============================================================================
Автор: zettend
URL: https://zettend.ru/
Telegram: https://t.me/zettend
email: [email protected]
=============================================================================
*/
if( !defined('DATALIFEENGINE') ) {
die("Hacking attempt!");
}
$assetFile = !empty($file) ? str_replace('{THEME}', '/templates/' . $config['skin'], $file) : false;
if ($assetFile) {
include_once (DLEPlugins::Check(ENGINE_DIR . '/modules/asset/asset.php'));
$compress = $config['js_min'];
dleAsset::addFile($assetFile, $compress);
}]]></replacecode>
</operation>
</file>
<file name="engine/modules/asset/asset.php">
<operation action="create">
<replacecode><![CDATA[<?php
/*
=============================================================================
DLE-Asset — автозагрузка стилей и скриптов для DLE
=============================================================================
Автор: ПафНутиЙ
URL: http://pafnuty.name/
twitter: https://twitter.com/pafnuty_name
email: [email protected]
=============================================================================
=============================================================================
Портировал на DLE 14+ zettend. На версиях ниже не проверялось.
=============================================================================
Автор: zettend
URL: https://zettend.ru/
Telegram: https://t.me/zettend
email: [email protected]
=============================================================================
*/
class dleAsset {
/**
* @param array $folders
* @param array $excludes
* @param boolean $compress
*/
public static function add($folders, $excludes = array('-', '_'), $compress = false) {
// Дополняем переданные префиксы префиксами по умолчанию
$excludes = array_merge($excludes, array('-', '_'));
// Получаем реальные пути к папкам
$folders = self::getRealPath($folders);
// Проверяем включено ли сжатие
$isMin = $compress;
// Добавляем скрипты и стили
self::addAssets($folders, $excludes, $isMin);
}
/**
* [addFile description]
* @param [type] $filePath [description]
* @param boolean $isMin [description]
*/
public static function addFile($filePath, $isMin = false) {
$path = self::getRealPath(array($filePath));
$arMin = array();
$arMin = self::processFile($path[0], false, $isMin, $arMin);
// Если сжатие включено — воспользуемся этой хорошей возможностью.
if ($isMin) {
self::echoCompressed($arMin);
}
}
/**
* @param array $arPath
* @param array $excludes
* @param bool $isMin
*/
public static function addAssets($arPath, $excludes, $isMin) {
foreach ($arPath as $folder) {
// Сканируем папку
$f = scandir($folder);
// Пробегаем по массиву файлов
$arMin = array();
foreach ($f as $file) {
// Берём только те файлы, у которых нет исключающего префикса
if (!self::strposArr($file, $excludes)) {
// Обрабатываем файлы
$arMin = self::processFile($file, $folder, $isMin, $arMin);
}
}
// Если сжатие включено — воспользуемся этой хорошей возможностью.
if ($isMin) {
self::echoCompressed($arMin);
}
}
}
/**
* [processFile description]
* @param string $file [description]
* @param string $folder [description]
* @param boolean $isMin [description]
* @param array $arMin [description]
* @return [type] [description]
*/
public static function processFile($file = '', $folder = '', $isMin = false, $arMin = array()) {
if (!is_array($arMin)) {
$arMin = array();
}
// Получаем путь к файлам
if ($folder != '') {
$localFolder = str_replace($_SERVER['DOCUMENT_ROOT'], '', $folder);
} else {
$_sf = $file;
$file = basename($file);
$localFolder = str_replace(array($_SERVER['DOCUMENT_ROOT'], $file), '', $_sf);
$folder = $_SERVER['DOCUMENT_ROOT'] . $localFolder;
}
// Берём только css и js файлы
if (preg_match("/(.*?)\.(css|js)$/im", $file, $matches)) {
// Добавляем параметр, если нужно т.к. файлы кешируются браузером
$v = (!$isMin) ? fileatime($folder . $file) : 1;
$fileToShow = $localFolder . $matches[0];
switch ($matches[2]) {
case 'css':
// добавляем css-файл
if ($isMin) {
$arMin['css'][] = $fileToShow;
} else {
echo '<link rel="stylesheet" href="' . $fileToShow . '?v=' . $v . '" />';
echo "\n\t\t";
}
break;
case 'js':
// добавляем js-файл
if ($isMin) {
$arMin['js'][] = $fileToShow;
} else {
echo '<script src="' . $fileToShow . '?v=' . $v . '"></script>';
echo "\n\t\t";
}
break;
}
}
return $arMin;
}
/**
* [echoCompressed description]
* @param array $arMin [description]
* @return [type] [description]
*/
public static function echoCompressed($arMin = array()) {
if (isset($arMin['css']) && !empty($arMin['css'])) {
echo '<link rel="stylesheet" href="/engine/classes/min/index.php?charset=utf-8&amp;f=' . implode(',', $arMin['css']) . '" />';
}
if (isset($arMin['js']) && !empty($arMin['js'])) {
echo '<script src="/engine/classes/min/index.php?charset=utf-8&amp;f=' . implode(',', $arMin['js']) . '"></script>';
}
}
/**
* @param array $array
*
* @return array
*/
protected static function getRealPath($array) {
foreach ($array as $k => $path) {
$array[$k] = $_SERVER['DOCUMENT_ROOT'] . $path;
}
return $array;
}
/**
* Небольшое улучшение strpos()
*
* @param string $str - строка в кторой будем искать
* @param array $arr - массив, совпадения с которым ищем.
*
* @return bool
*/
protected static function strposArr($str, $arr) {
foreach ($arr as $v) {
if (($pos = strpos($str, $v)) !== false && $pos == '0') {
return true;
}
}
return false;
}
private function __construct() {
}
}]]></replacecode>
</operation>
</file>
</dleplugin>
4 changes: 4 additions & 0 deletions update.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"version": "2.0.0",
"url": "https://github.com/zettend/DLE-Asset/releases/latest"
}
Loading

0 comments on commit 3bb772d

Please sign in to comment.