Skip to content

Instantly share code, notes, and snippets.

@Fi1osof
Last active October 23, 2017 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Fi1osof/70d5197fa7ee3fc74ff7 to your computer and use it in GitHub Desktop.
Save Fi1osof/70d5197fa7ee3fc74ff7 to your computer and use it in GitHub Desktop.
Наполняем Gallery из документов
<?php
if(!$docs = $modx->getCollection('modResource', array(
'parent' => 26
))){
return;
}
$album = 2;
$albumDir = $album.'/';
// Получаем полный путь к директории альбома
$targetDir = $modx->call('galAlbum','getFilesPath',array(&$modx)).$albumDir;
// Получаем кеш-менеджер, который к тому же используется и для работы с папками и файлами
$cacheManager = $modx->getCacheManager();
// Если нет папки, создаем ее
if (!file_exists($targetDir) || !is_dir($targetDir)) {
if (!$cacheManager->writeTree($targetDir)) {
$modx->log(xPDO::LOG_LEVEL_ERROR,'[Gallery] Could not create directory: '.$targetDir);
return $modx->toJSON(array('error' => 'Could not create directory: ' . $targetDir));
}
}
// Проверяем, чтобы была доступна для записи
if (!is_readable($targetDir) || !is_writable($targetDir)) {
$modx->log(xPDO::LOG_LEVEL_ERROR,'[Gallery] Could not write to directory: '.$targetDir);
return $modx->toJSON(array('error' => 'Could not write to directory: ' . $targetDir));
}
$r = 0; // Счетчик ранга элемента
// Проходимся по каждому элементу
foreach($docs as $doc){
$r++;
$title = $doc->get('pagetitle');
// Пытаемся найти картинку и получить путь
if(!preg_match('/src="(.+?)"/', $doc->content, $match)){
$modx->log(1, "Не было найдено изображение для документа ". $doc->id);
}
$img = $match[1];
$filenm = MODX_BASE_PATH. $img; // Абсолютный путь до картинки-источника
// Описание элемента
$desc = strip_tags($doc->content);
// Создаем новый элемент альбома
$item = $modx->newObject('galItem', array(
'name' => $doc->pagetitle,
));
// Сохраняем его, чтобы получить id (будет использован для формирования имени файла)
$item->save();
// Самый быстрый способ получить расширение файла
$extension = end(explode('.', $img));
$filename = $item->id.'.'.$extension;
$relativePath = $albumDir.$filename;
$absolutePath = $targetDir.$filename;
// Копируем картинку в папку альбома
$cacheManager->copyFile($filenm, $absolutePath );
// Набиваем конечные данные в объект элемента альбома
$item->fromArray(array(
'filename' => $albumDir.$filename,
'description' => $desc,
'active' => 1,
));
// Создаем объект Элемент-Альбом
$ai = $modx->newObject('galAlbumItem', array(
'album' => $album,
'rank' => $r,
));
// Добавляем к нему элемент, чтобы сформировалась связь при сохранении
$ai->addOne($item);
// Сохраняем
$ai->save();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment