Skip to content

Instantly share code, notes, and snippets.

@pavel-one
Created November 26, 2018 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavel-one/17db1b5cff8c2713f28976439e05f945 to your computer and use it in GitHub Desktop.
Save pavel-one/17db1b5cff8c2713f28976439e05f945 to your computer and use it in GitHub Desktop.
Транслитерация файлов файлов при загрузке. Уменьшает загружаемое изображение до 1200px по ширине. Из поля content достает все img, вырезает у них атрибуты width и height, вместо них подставляет класс img-thumbnail
<?php
switch ($modx->event->name) {
//Работа с контентом
case 'OnLoadWebDocument':
$content = $modx->resource->content;
$content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'); //исправляем ошибки кодировки
$dom = new DOMDocument;
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imgs = $dom->getElementsByTagName('img'); //ищем все изображения
foreach ($imgs as $img) {
//убираем атрибуты width и height, добавляем класс
$img->removeAttribute('width');
$img->removeAttribute('height');
$img->setAttribute('class', 'img-thumbnail');
}
//компилируем html и устанавливаем
$html = $dom->saveHTML();
$modx->resource->set('content', $html);
break;
case 'OnFileManagerBeforeUpload':
setlocale(LC_ALL, 'ru_RU.utf8'); //фикс для неправильных серверов, иначе не будет работать patchinfo с кириллицей
$fullPath = $source->getBases()['pathAbsolute'].$directory; //получаем абсолютную дирректорию
$dir = scandir($fullPath);
foreach ($files as $key => $file) {
$info = pathinfo($file['name']);
$name = $info['filename'];
$name = modResource::filterPathSegment($modx, $name); //транслитерация
$extension = $info['extension'];
$fullname = $name.'.'.$extension;
//ищем файлы с таким же названием в этой директории
if (!in_array($fullname, $dir)) {
$newFullName = $fullname;
} else {
$newFullName = $name.'_'.rand(1,999999).'.'.$extension;
}
$file['name'] = $newFullName;
$modx->event->params['file'] = $file; //отдаем изменненную переменную file
$files[$key] = $file;
}
$modx->event->params['files'] = $files; //отдаем изменненную переменную files
break;
case 'OnFileManagerUpload':
$fullPath = $source->getBases()['pathAbsolute'].$directory;
foreach ($files as $file) {
if(strripos($file['type'], 'image') === false) { //если не изображение, не запускаем phpThumb
return ;
}
$name = $file['name'];
$pathToImage = $fullPath.$name;
//Массив параметров для phpThumb
$params = array(
'w' => 1200 ,
);
$phpThumb = $modx->getService('modphpthumb','modPhpThumb', MODX_CORE_PATH . 'model/phpthumb/', array()); //Подключаем класс phpThumb
$phpThumb->setSourceFilename($pathToImage);
foreach ($params as $k => $v) {
$phpThumb->setParameter($k, $v);
}
if ($phpThumb->GenerateThumbnail()) {
if (!$phpThumb->renderToFile($pathToImage)) {
$modx->log(1, 'Не сохранено изображение в ['.$pathToImage.']');
}
}
else {
$modx->log(1, print_r($phpThumb->debugmessages, 1));
}
}
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment