1

Тема: Создание Галерей на Strawberry1.1.1

Начинаю работу над галереями.
Какую структуру таблицы cute_gallery посоветуйте ?

Re: Создание Галерей на Strawberry1.1.1

YurySpoloh, например:

// gallery
'gallery'     => array(
'date'     => array('type' => 'int'), //Дата публикации
'author'   => array('type' => 'string'), //Кто опубликовал
'title'    => array('type' => 'string'), //Подпись к картинке
'thumb'    => array('type' => 'string'), //Имя файла уменьшенной картинки
'image'     => array('type' => 'string'), //Имя файла полной картинки
'url'      => array('type' => 'string'), //УРЛ имени картинки (может понадобиться для ЧПУ)
'id'       => array(  //id-номер картинки
           'type' => 'int',
           'auto_increment' => 1,
           'primary' => 1
           ), 
'views'    => array('type' => 'int', 'default' => 0), //Количество просмотров
'comments' => array('type' => 'int', 'default' => 0), //*Комментарии
'keywords'   => array('type' => 'string'), //**Ключевые слова
),

Вроде бы ничего не забыл.

*Для комментариев понадобится еще одна таблица, например cute_gallery_comments, делаем её по образу и подобию cute_comments.

**Ключевые слова могут понадобиться для поиска по галереям, так что предусмотрите таблицу cute_gallery_keywords (по аналогичной таблице). Впрочем, ключевые слова для картинок могут быть взяты и из "стандартной" таблицы cute_keywords.

Ну и не забудьте про рейтинг и прочие "приятные мелочи", которые вначале вроде бы не нужны, но потом обязательно понадобятся!

Re: Создание Галерей на Strawberry1.1.1

я бы добавил высоту, ширину, описание картинки (расширенный текст), превью (1, 0 - есть, нет).
А еще если будут категории в фотоальбоме (а они будут) - нужно указать номер категории.
по ходу будет видно...

Здесь молодость бродит крылато, и старость не клонит голов...
Демо площадка Strawberry 1.2 - заходим и тестируем!

4

Re: Создание Галерей на Strawberry1.1.1

Sehr Gut.

Только наверное :

'title'    => array('type' => 'string'), //Название галереи
'descriotion'    => array('type' => 'text'), //Подпись к картинке

'thumb'   - будет по умолчанию. В Двиге есть это уже.

Далее: попытаюсь сделать еще $type, по аналогии с гостевой

'album'    => array('type' => 'string'), //либо пост , либо альбом пользователя. $id = ($post ? $post['id'] : $user);

И того получилось:

// gallery
'gallery'     => array(
'date'     => array('type' => 'int'), //Дата публикации
'author'   => array('type' => 'string'), //Кто опубликовал
'title'    => array('type' => 'string'), //Подпись к картинке
'width'    => array('type' => 'string'), //Понятно
'height'    => array('type' => 'string'), //Понятно
'album'    => array('type' => 'string'), //Либо пост, либо албом пользователя, либо галерея.
'image'     => array('type' => 'string'), //Имя файла полной картинки
'url'      => array('type' => 'string'), //УРЛ имени картинки (может понадобиться для ЧПУ)
'id'       => array(  //id-номер картинки
           'type' => 'int',
           'auto_increment' => 1,
           'primary' => 1
           ), 
'views'    => array('type' => 'int', 'default' => 0), //Количество просмотров
'publication'    => array('type' => 'int'), //(1, 0 - включена, отключена).
'comments' => array('type' => 'int', 'default' => 0), //*Комментарии
'keywords'   => array('type' => 'string'), //**Ключевые слова
'rating'   => array('type' => 'string'), //**Ключевые слова
),

Это пока еще сырой модуль, читает картинки из папок $gallery .= '/'.$id;

include_once 'head.php'; 

$gallery = cute_parse_url($config['path_image_upload']);
$gallery = $gallery['abs'];
$id = ($post ? $post['id'] : $user);

if(isset($id)){

  $gallery .= '/'.$id;
  $imgpage = ($_GET['pic'] ? '1' : '25');
  $handle = opendir($gallery);
  while ($file = readdir($handle)){
    if (in_array(strtolower(end(explode('.', $file))), $allowed_extensions)){
       $files[$file] = filemtime($gallery.'/'.$file);
     }
  }

   if (count($files)){
       arsort($files);

    $image_per_page = ($image_per_page ? $image_per_page : $imgpage);
    $start_from = ($start_from ? $start_from : '');
    $i = $start_from;
    $j = 0;
    foreach ($files as $file => $time){
        if ($j < $start_from){
            $j++;
            continue;
        }

        $i++;
         //if ($_GET['pic']) {
          //echo '<img src="'.$gallery.'/'.$_GET['pic'].'">';
          //} else {
          
           //echo '<div class="thumb"><a href="example.php?pic='.$file.'"><img src="'.$gallery.'/thumbs/'.$file.'" alt="'.$i.'"></a></div> ';
           
            echo '<div class="thumb"><a href="'.$config['path_image_upload'].'/'.$id.'/'.$file.'" class="highslide" onclick="return hs.expand(this)"><img src="'.$config['path_image_upload'].'/'.$id.'/thumbs/'.$file.'" alt="'.$i.'"></a></div> ';
           //}
        if ($i >= $image_per_page + $start_from){
            break;
        }
    }

    if ($start_from > 0){
        $previous = $start_from - $image_per_page;
        $npp_nav .= '<a href="?id='.$id.'&start_from='.$previous.'">&lt;&lt;</a> ';
    }

    if (count($files) > $image_per_page){
        $enpages_count = @ceil(count($files) / $image_per_page);
        $enpages_start_from = 0;
        $enpages = '';

        for ($j = 1; $j <= $enpages_count; $j++){
            if ($enpages_start_from != $start_from){
                $enpages .= '<a href="?id='.$id.'&start_from='.$enpages_start_from.'">'.$j.'</a> ';
            } else {
                $enpages .= ' <b> <u>'.$j.'</u> </b> ';
            }

                $enpages_start_from += $image_per_page;
        }
               $npp_nav .= $enpages;
    }

    if (count($files) > $i){
               $npp_nav .= '<a href="?id='.$id.'&start_from='.$i.'"> &gt;&gt;</a>';
    }

   echo '<div id="pages">'.(!$_GET['pic'] ? $npp_nav : '').'</div>';
   } 
 }

PS Кто разбираетя с мульти-загрузчиками.?

Отредактировано YurySpoloh (18 Oct 2009 17:57:28)

Re: Создание Галерей на Strawberry1.1.1

YurySpoloh, а зачем вам

$handle = opendir($gallery);
  while ($file = readdir($handle)){
    if (in_array(strtolower(end(explode('.', $file))), $allowed_extensions)){
       $files[$file] = filemtime($gallery.'/'.$file);
...

если есть

'date'     => array('type' => 'int'), //Дата публикации
...
'thumb'    => array('type' => 'string'), //Имя файла уменьшенной картинки
'image'     => array('type' => 'string'), //Имя файла полной картинки

? Лишняя нагрузка на сервер при неиспользуемой базе данных. У нас ведь все данные (имя тумбочки, имя полной картинки, дата создания, принадлежность к альбому или категории и т.д.) уже хранятся в БД. Остаётся только достать их из папки с картинками и оформить вывод на экран.

Вот простой пример:

//Вывод картинки по id
foreach ($sql->select(array('table' => 'gallery', 'where' => array("id = $id", 'or', "url = $id"))) as $row) {

echo '<div class="thumb"><a href="'.$config['path_image_upload'].'/'.$row['image'].'" class="highslide" onclick="return hs.expand(this)"><img src="'.$config['path_image_upload'].'/thumbs/'.$row['thumbs'].'" alt="'.$row['title'].'"></a></div> ';
}

или ещё пример:

//Вывод всех картинок из альбома album
foreach ($sql->select(array('table' => 'gallery', 'where' => array("album = $album"))) as $row) {

echo '<div class="thumb"><a href="'.$config['path_image_upload'].'/'.$row['image'].'" class="highslide" onclick="return hs.expand(this)"><img src="'.$config['path_image_upload'].'/thumbs/'.$row['thumbs'].'" alt="'.$row['title'].'"></a></div> ';
}

и ещё один:

//Вывод картинок по ключевому слову keywords
foreach ($sql->select(array('table' => 'gallery', 'where' => array("keywords ? $keywords"))) as $row) {

echo '<div class="thumb"><a href="'.$config['path_image_upload'].'/'.$row['image'].'" class="highslide" onclick="return hs.expand(this)"><img src="'.$config['path_image_upload'].'/thumbs/'.$row['thumbs'].'" alt="'.$row['title'].'"></a></div> ';
}

А что вы подразумеваете под словом "мульти-загрузчик"?

Re: Создание Галерей на Strawberry1.1.1

Ну типа на аяксе чтоб все типы файлов загружались в нужный каталог. как то так...

Здесь молодость бродит крылато, и старость не клонит голов...
Демо площадка Strawberry 1.2 - заходим и тестируем!

7

Re: Создание Галерей на Strawberry1.1.1

Подскажите , как в этой конструкции:

function get_subfolders(){
$base_folder = 'upimages/';
$dir = @opendir($base_folder);
$all_subfolders = array();
$all_subfolders['base'] = t('Корневая директория -->');
while (false != ($subfolder = @readdir($dir))){

if (is_dir($base_folder) and $subfolder != "." and $subfolder != ".." and $subfolder != "thumbs"){
       $all_subfolders[$subfolder] = '- '.$subfolder;
      }
 }
@closedir($dir);
return $all_subfolders;
}

сделать чтение толь лижь директорий , а не всех файлов?

PS. Мультизагрузчик - это флешевая штука , которая позволяет загружать до 100 картинок одновременно.
Его работу можно увидеть ВКОНТАКТЕ , либо на Gallery.ru.
Ну оч удобная штука.

Re: Создание Галерей на Strawberry1.1.1

YurySpoloh,

Чтение только списка директорий. 8-я строка вашего кода:

if ((is_dir($base_folder)) and (is_dir($subfolder)) and ($subfolder != ".") and ($subfolder != "..") and ($subfolder != "thumbs")){

Мой вариант чтения списка директорий (в продолжение темы поста #5). Может быть я слишком навязчив, но зачем вы всё время пытаетесь читать папки и файлы с сервера (страшно объёмная файловая операция), если у вас все данные о файлах/папках уже есть в базе данных?! Открытие папки, чтение файлов/директорий, сложное условие отбора в цикле, закрытие папки... А между тем, база данных, в которой уже есть сведения об альбоме:

'album'    => array('type' => 'string'), //Либо пост, либо албом пользователя, либо галерея.

никак не используется! Посмотрите, насколько более компактен и производителен мой код, выполняющий ту же самую работу (путём всего одного запроса к базе данных):

//Вывод списка альбомов (директорий)
function get_subfolders(){
global $sql;

$all_subfolders = array();
$all_subfolders['base'] = t('Корневая директория -->');
$folders = $sql->select(array('table' => 'gallery', 'select' => array('album')));

    for ($i=0; $i<count($folders); $i++) {
        $all_subfolders[$folders[$i]['album']] .= '- '.$folders[$i]['album'];
    }

return $all_subfolders;
}

Мультизагрузчик. Это смотря для каких целей вы будете его использовать? На "ВКОНТАКТЕ" лезть не стал, а на Gallery.ru увидел только одновременную загрузку тумбочек над основной фотографией. Это то, что вы имели в виду?

Ну насчёт флэш ничем помочь не могу, а вот на яве могу нечто подобное подсказать. Перед тегом </head> пишем функцию предзагрузки:

<script language="JavaScript" type="text/JavaScript">
<!--
function MM_preloadImages() {
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
//-->
</script>

Внутри тега <body> вызываем функцию предзагрузки со списком (например из шести) файлов:

<body onLoad="MM_preloadImages('images/image_example1.gif','images/image_example2.gif','images/image_example3.gif','images/image_example4.gif','images/image_example5.gif','images/image_example6.gif')">

Кстати, формирование списка для функции MM_preloadImages можно запросто организовать на PHP:

<body onLoad="MM_preloadImages(<?=формируем_список;?>)">

После этого у вас появятся предзагруженные картинки с именами name="Image1" ... name="Image6". Можете делать с ними всё, что хотите (но в пределах функций javascript), например:

<img border="0" src="images/image_example1.gif" name="Image1" onMouseOver="функция('Image1','Image2')" onMouseOut="функция('Image2','Image1')">

(в этом примере гипотетическая javascript-функция функция('Image1','Image2') меняет при наведении мыши на рисунок - Image1 на Image2, и при уходе мыши с рисунка -  Image2 на Image1)

И даже просто вывод картинки с именем name="Image1":

<img border="0" src="images/image_example1.gif" name="Image1">

приведёт к моментальному выводу этой картинки на экран, поскольку она уже предзагружена.

Можете предзагружать столько картинок, сколько вам нужно, страница начнёт выводится только тогда, когда функция MM_preloadImages отработает до конца, поскольку она расположена в теге <body>.

Может быть немного не то, но это всё, что умею wink

Re: Создание Галерей на Strawberry1.1.1

Имелось в виду загружать картинки на сервер (как в файловом загрузчике, только выбрать сразу несколько файлов для закачки в одном окне с фалами, а не каждый раз для нового поля ввода выбирать отдельную картинку (как в моде image.mdu)).

Здесь молодость бродит крылато, и старость не клонит голов...
Демо площадка Strawberry 1.2 - заходим и тестируем!

10

Re: Создание Галерей на Strawberry1.1.1

ANT-Soft
Ваша конструкция не сработала.
У меня получилась так

function get_subfolders(){
global $base_folder, $allowed_extensions, $media_extensions;

$dir = @opendir($base_folder);
$all_subfolders = array();
$all_subfolders['base'] = t('Корневая директория -->');
while ($subfolder = @readdir($dir)){

if (!in_array(strtolower(end(explode('.', $subfolder))), $allowed_extensions)){// условие для вывода только директорий
      if (is_dir($base_folder) and ($subfolder != '.') and ($subfolder != '..') and ($subfolder != 'thumbs') and ($subfolder != '.htaccess')){
        $all_subfolders[$subfolder] = '- '.$subfolder;
      }
    }
 }
@closedir($dir);
return $all_subfolders;
}

Далее : я просто дорабатываю стандартные моды по картинкам (images.mdu) , делая его в соответствии с описанным ранее постом. Это всё пока не на мускуле.

Кому интересно , вот  что получилось:

<?php

if ($member['usergroup'] > 2 and ($action == 'remove' or $action == 'rename')){
    $action = '';
}

if ($config['use_images_uf'] or $member['usergroup'] < 3 and $user){
    $user = (($member['usergroup'] < 3 and $user) ? totranslit($user) : totranslit($member['username']));
}

$query_string = cute_query_string($QUERY_STRING, array('action', 'mod', 'image', 'name', 'start_from', 'align', 'sortby', 'subfolder', 'act'));
$PHP_SELF .= '?mod=images'.$query_string;
$allowed_upload = false;

$settings = new PluginSettings('image_manager'); //Configuration
    
    if(!is_array($settings -> settings)){
            $settings -> settings = array(
                'align'                =>'none',
                'popup'                => '0',
                'update'            => '0',
                'replace'            => '0',
                'replace_template'    => '<i>{date:d.m.Y}: <b>{image}</b> was removed.</i>',
                'video_width'        => '320',
                'video_height'        => '240',
                'auto_start'        => 'yes',
                'uimode'            => 'full',
                'media_extensions'    => 'avi,mpg'
            );
            
            $settings -> save();
    }
    
    if($settings -> settings['align'] == 'left') $default_align = 'align="left"';
    if($settings -> settings['align'] == 'right') $default_align = 'align="right"';
    if($settings -> settings['align'] == 'none') $default_align = '';
    
    if($settings -> settings['popup'] == '1') $popup = true;
    if($settings -> settings['popup'] == '0') $popup = false;
    
    if($settings -> settings['update'] == '1') $update = true;
    if($settings -> settings['update'] == '0') $update = false;
    
    if($settings -> settings['replace'] == '1') $replace = true;
    if($settings -> settings['replace'] == '0') $replace = false;
    
    $replace_template = $settings -> settings['replace_template'];
    
    $media_extensions = explode(",", $settings -> settings['media_extensions']);
    
if($_GET['act'] == "configuration" and !$area){ //Show configuration
   echoheader('images', t('Управление картинками'));

        echo     '<b>configuration</b><br />'.
                '<form method="post" action="'.$PHP_SELF.'">'.
                '<table>'.
                '<tr><td>align<td><label for="aleft">alignLeft</label><td><input id="aleft" type="radio" name="align1" value="left" '.($settings -> settings['align'] == 'left' ? 'checked' : '').'>'.            
                '<tr><td><td><label for="aright">alignRight</label><td><input id="aright" type="radio" name="align1" value="right" '.($settings -> settings['align'] == 'right' ? 'checked' : '').'>'.                
                '<tr><td><td><label for="anone">alignNone</label><td><input id="anone" type="radio" name="align1" value="none" '.($settings -> settings['align'] == 'none' ? 'checked' : '').'>'.    
                '<tr><td><label title="updateTitle" for="update">'.$echo['update'].'</label></td><td><input id="update" type="checkbox" name="update1" value="1" '.($settings -> settings['update'] == '1' ? 'checked' : '').'>'.            
                '<tr><td><label title="replaceTitle" for="replace">replace</label><td><input onClick="javascript:ShowOrHide(\'show_template\')" id="replace" type="checkbox" name="replace1" value="1" '.($settings -> settings['replace'] == '1' ? 'checked' : '').'><td><div style="display:'.($settings -> settings['replace'] == '1' ? 'block' : 'none').'"id="show_template"><input type="text" name="replace_template1" value="'.$settings -> settings['replace_template'].'" size="40" /><br />'.$settings -> settings['replace_template'].'</div>'.        
                '<tr><td>extensions<td><input type="text" name="media_extensions1" value="'.$settings -> settings['media_extensions'].'" />'.                
                '<tr><td>playerWidth<td><input type="text" name="video_width1" value="'.$settings -> settings['video_width'].'" />'.                
                '<tr><td>playerHeight<td><input type="text" name="video_height1" value="'.$settings -> settings['video_height'].'" />'.
                '<tr><td>playerMode<td>'.makeDropDown(array('none' => 'non', 'mini' => 'mini', 'full' => 'full'), 'uimode1', $settings -> settings['uimode']).            
                '<tr><td>'.$echo['autostart'].'<td>'.makeDropDown(array('yes' => 'sayyes', 'no' => 'sayno'), 'auto_start1', $settings -> settings['auto_start']).'</td></tr>'.
                
                '<tr><td><label title="'.$echo['popupTitle'].'" for="popup">'.$echo['popup'].'</label></td><td><input id="popup" type="checkbox" onclick="javascript:ShowOrHide(\'show_help\')" name="popup1" value="1" '.($settings -> settings['popup'] == '1' ? 'checked' : '').'>'.
                '</table>'.
                '<span id="show_help" style="display:'.($settings -> settings['popup'] == '1' ? 'block' : 'none').'">'.
                '1. Copy popup.js in the same folder as your news page.<br />'.
                '2. Put this code in the &lt;head&gt; tag of your news page:<br />'.
                '<div class="code">&lt;script type="text/javascript" src="./popup.js"&gt;&lt;/script&gt;</div>'.
                '</span><br />'.
                '<input type="hidden" name="act" value="save_config">'.
                '<input type="submit" value="ok">'.
                '</form>';
                
                echofooter();
                exit;
}

if($_POST['act'] == "save_config"){ //Save the config    
              $settings -> settings = array(
                'align'             => $_POST['align1'],
                'popup'             => ($_POST['popup1'] == "1" ? '1' : '0'),
                'update'            => ($_POST['update1'] == "1" ? '1' : '0'),
                'replace'           => ($_POST['replace1'] == "1" ? '1' : '0'),
                'replace_template'  => $_POST['replace_template1'],
                'video_width'        => $_POST['video_width1'],
                'video_height'        => $_POST['video_height1'],
                'auto_start'        => $_POST['auto_start1'],
                'uimode'            => $_POST['uimode1'],
                'media_extensions'    => $_POST['media_extensions1']
             );
            
             $settings -> save();            
    }

$folder = end($folder = cute_parse_url($config['path_image_upload']));
if(!file_exists($folder))
@mkdir($folder, chmod);


if ($config['use_images_uf'] or $user){
    $folder .= '/'.$user;
    $config['path_image_upload'] .= '/'.$user;
    if(!file_exists($folder))
    @mkdir($folder, chmod);
    if(!file_exists($folder.'/thumbs'))
    @mkdir($folder.'/thumbs', chmod);
}

$base_folder = $folder;

if(!file_exists($folder))
@mkdir($folder, chmod);

if(!file_exists($folder.'/thumbs'))
@mkdir($folder.'/thumbs', chmod);


if($_POST['subfolder'] == 'base' or $_GET['subfolder'] == 'base'){

} elseif($_POST['subfolder'] and $_POST['subfolder'] != ''){ // создание суб галерей
       $subfolder = $_POST['subfolder'];
       $folder .= '/'.$subfolder;
       $config['path_image_upload'] .= '/'.$subfolder;
    
       if(!file_exists($folder.'/thumbs'))
       @mkdir($folder.'/thumbs', chmod);
       
} elseif($_GET['subfolder'] and $_GET['subfolder'] != ''){ // редактура суб галерей
       $subfolder = $_GET['subfolder'];
       $folder .= '/'.$subfolder;
       $config['path_image_upload'] .= '/'.$subfolder;
    
       if(!file_exists($folder.'/thumbs'))
       @mkdir($folder.'/thumbs', chmod);
}

if ($action == 'rename' and $image and $name){ //Rename image
    @rename($folder.'/'.$image, $folder.'/'.$name);
    @rename($folder.'/thumbs/'.$image, $folder.'/thumbs/'.$name);
    if($update){
        $old = array('/'.$image, '/thumbs/'.$image, $image);
        $new = array('/'.$name, '/thumbs/'.$name, $name);
        update_stories($old, $new);
    }
        header('Location: '.$PHP_SELF);
}

if ($action == 'remove' and $image){ //Remove image
    @unlink($folder.'/'.$image);
    @unlink($folder.'/thumbs/'.$image);
    if($update and $replace){
        $old = array('#<a (.*)'.$_GET['subfolder'].'\/'.$image.'(.*)<\/a>#i', '#<img (.*)'.$_GET['subfolder'].'\/'.$image.'(.*)\/>#i', '#<OBJECT (.*)'.$_GET['subfolder'].'\/'.$image.'(.*)<\/OBJECT>#i');
        $new_tmp = str_replace('{image}', $image, $replace_template);
        $new_tmp = preg_replace('/{date:(.*?)}/ie', "langdate('\\1', time())", $new_tmp);
        $new = array($new_tmp, $new_tmp, $new_tmp);
        update_stories($old, $new, true);
    }
        header('Location: '.$PHP_SELF);
}

if ($action == 'add_folder' and (!file_exists($folder.'/'.$_POST['new_folder']))){ //Add subfolder
    @mkdir($folder.'/'.$_POST['new_folder'], chmod);
    @mkdir($folder.'/'.$_POST['new_folder'].'/thumbs', chmod);
    
    header('Location: '.$PHP_SELF);
}

if($action == 'rename_subfolders'){ //Rename subfolder
    @rename($base_folder.'/'.$old_folder, $base_folder.'/'.$selected_folder);//
    if($update){
        $old = $old_folder;
        $new = $selected_folder;
        update_stories($old, $new);
    }
    header('Location: '.$PHP_SELF);
}

if($action == 'delete_folder'){ //Delete subfolder
    @rmdir($base_folder.'/'.$selected_folder.'/thumbs');
    @rmdir($base_folder.'/'.$selected_folder);
    header('Location: '.$PHP_SELF);
}

if($action == 'move_file'){ //Move image to another folder
    if(!file_exists($base_folder.($new_path == 'base' ? '' : '/'.$new_path).'/'.$image)){
        @copy($folder.'/'.$image, $base_folder.($new_path == 'base' ? '' : '/'.$new_path).'/'.$image);
        @copy($folder.'/thumbs/'.$image, $base_folder.($new_path == 'base' ? '/thumbs/' : '/'.$new_path.'/thumbs/').$image);
        if($update){
            if($subfolder == ''){
                $old = array('}/'.($user ? $user.'/' : '').$image, '/thumbs/'.$image);
                $new = array('}/'.($user ? $user.'/' : '').'/'.$new_path.'/'.$image, '/'.$new_path.'/thumbs/'.$image);
            
            } elseif($new_path != 'base'){
                $old = array('/'.$subfolder.'/'.$image, '/'.$subfolder.'/thumbs/'.$image);
                $new = array('/'.$new_path.'/'.$image, '/'.$new_path.'/thumbs/'.$image);
            
            } else {
                $old = array('/'.$subfolder.'/'.$image, '/'.$subfolder.'/thumbs/'.$image);
                $new = array('/'.$image, '/thumbs/'.$image);
            }
            update_stories($old, $new);
        }
            @unlink($folder.'/'.$image);
            @unlink($folder.'/thumbs/'.$image);
    }
            header('Location: '.$PHP_SELF);
}

if ($_FILES['image']['name']){
    for ($i = 0; $i < count($_FILES['image']['name']); $i++){
        $ext   = end($ext = explode('.', $_FILES['image']['name'][$i]));
        $type  = end($type = explode('/', $_FILES['image']['type'][$i]));
        $image = preg_replace('/(.*?).'.$ext.'$/ie', "totranslit('\\1')", $_FILES['image']['name'][$i]).'.'.$ext;

        foreach ($allowed_extensions as $allow){
            if (substr($type, -strlen($allow)) == $allow){
                $allowed_upload = true;
            }
        }
        
        foreach($media_extensions as $allow){
            if(strtolower($ext) == $allow){
                $allowed_upload = true;
            }
        }
                
        if ((file_exists($folder.'/'.$image) and $overwrite) or $allowed_upload){
            move_uploaded_file($_FILES['image']['tmp_name'][$i], $folder.'/'.$image);
            
                if ($resize_image and $resize_pic){ //Resize image
                    if ($resize_pic < 1 or $resize_pic == "") {$resize_pic = 640;}              
                        $squarepic = ($square_pic ? 'square' : 'normal');
                        @img_resize($folder.'/'.$image, $folder.'/'.$image, $resize_pic, $squarepic);
        
                    if ($shadow_pic){
                        @make_shadow($folder.'/'.$image);
                    }
                }
            
                if ($watermark and $watermark_text != "") {  //Add watermark (text)
                    if($watermark_font == "none") {
                    @add_watermark($folder.'/'.$image, $watermark_text, $hotspot1, ($textcolor ? $textcolor : 'FFFFFF'), ($textsize ? $textsize : '12'));
                    } else {
                      @add_watermark($folder.'/'.$image, $watermark_text, $hotspot1, ($textcolor ? $textcolor : 'FFFFFF'), ($textsize ? $textsize : '12'), 'data/watermark/'.$watermark_font);
                    }
                }

                if ($merge) { //Add watermark (image)
                     @mergePix($folder.'/'.$image, 'data/watermark/'.$watermark_image, $folder.'/'.$image, $hotspot2, ($merge_transition ? $merge_transition : '40'));
                }
                
                if ($thumb and $make_thumb){ //Create thumb
                   if ($make_thumb < 1 or $make_thumb == "") {$make_thumb = $config['newsicon'];}
                      $kadr = ($square ? 'square' : 'normal');      
                      @img_resize($folder.'/'.$image, $folder.'/thumbs/'.$image, $make_thumb, $kadr);
                  if ($shadow) {
                    @make_shadow($folder.'/thumbs/'.$image);
                }
            }
        }
    }
         header('Location: '.$PHP_SELF);
}
if ($area){
?>

<link href="skins/default.css" rel="stylesheet" type="text/css" media="screen">
<script language="javascript" type="text/javascript" src="skins/cute.js"></script>
<script language="javascript" type="text/javascript">
<!--
function insertimage(text){
    text = ' ' + text + ' ';
    opener.document.forms['addnews'].<?=$area; ?>_story.focus();
    opener.document.forms['addnews'].<?=$area; ?>_story.value  += text;
    opener.document.forms['addnews'].<?=$area; ?>_story.focus();
}
//-->
</script>

<?
} else {
    echoheader('images', t('Управление картинками'));
     echo '<a href="'.$PHP_SELF.'&act=configuration">configuration</a>';
}
?>

<table class="panel" width="500">
<tr><td>
<form action="<?=$PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<b><?=t('Загрузить файл'); ?></b> 
<? if(!$area) { ?>
<label for="manage_folders"><input type="checkbox" name="manage_folders" id="manage_folders" onclick="javascript:ShowOrHide('show_folders')"><b><?=t('Управление директорями'); ?></b></label>
<? } ?>
<table border="0" cellpading="0" cellspacing="0" width="250" class="panel">
 <tr>
  <td>

<script language="javascript">
f = 0
function file_uploader(which){
if (which < f) return
    f ++
    d = $('image_'+f)
    d.innerHTML = '<input type="file" size="40" name="image['+f+']" id="image_'+f+'" value="" onchange="file_uploader('+f+');" /><br /><span id="image_'+(f+1)+'">'
}
document.writeln('<input type="file" size="40" name="image[0]" value="" onchange="file_uploader(0);" /><br />')
document.writeln('<span id="image_1"></span>')
</script>

<?=t('Сохранить в').' '; ?>
<?=makeDropDown(get_subfolders(), 'subfolder', ($_POST['subfolder'] ? $_POST['subfolder'] : ($_GET['subfolder'] ? $_GET['subfolder'] : t('База')))); ?>
<br />

   <label for="overwrite"><input type="checkbox" name="overwrite" id="overwrite"><?=t('Переписать если файл существует'); ?></label><br />
   
   <label for="thumb"><input type="checkbox" name="thumb" id="thumb" onclick="javascript:ShowOrHide('make_thumb')"<?=(!extension_loaded('gd') ? ' disabled' : ''); ?>><?=t('Уменьшанная копия'); ?></label><br />
   <span id="make_thumb" style="display: none;">
   <ul style="list-style-type:none">
   <li><input type="text" name="make_thumb" size="1" value="<?=$config['newsicon']; ?>"> <?=t('Размер для превью'); ?></li>
   <li><input type="checkbox" name="square" id="square"><label for="square"><?=t('Кадрировать'); ?></label></li>
   <li><input type="checkbox" name="shadow" id="shadow"><label for="shadow"><?=t('Наложить тень'); ?></label></li>
   </ul>
   </span>
   
   <label for="resize_image"><input type="checkbox" name="resize_image" id="resize_image" onclick="javascript:ShowOrHide('show_resize')"<?=(!extension_loaded('gd') ? ' disabled' : ''); ?>><?=t('Выставить размер'); ?></label><br />
   <span id="show_resize" style="display: none;">
   <ul style="list-style-type:none">
   <li><input type="text" name="resize_pic" size="1" value="640"> <?=t('Размер по ширине'); ?></li>
   <li><input type="checkbox" name="square_pic" id="square_pic" value="yes"><label title="resizeCrop" for="square_pic"> <?=t('Кадрировать'); ?></label></li>
   <li><input type="checkbox" name="shadow_pic" id="shadow_pic"><label for="shadow_pic"> <?=t('Наложить тень'); ?></label></li>
   </ul>
   </span>   
<?
     $dir = opendir("data/watermark");
     while ($single_file = readdir($dir)){
        $file_ending = strtolower(end(explode('.', $single_file)));
         if ($file_ending == "jpg" or $file_ending == "jpeg" or $file_ending == "gif" or $file_ending == "png"){
           $watermarks[] = $single_file;
         }
         if ($file_ending == "ttf"){
           $fonts[] = $single_file;
        }
}
?>
   <label for="watermark"><input type="checkbox" name="watermark" id="watermark" onclick="javascript:ShowOrHide('make_watermark')"<?=(!extension_loaded('gd') ? ' disabled' : ''); ?>><?=t('Наложить Watermark'); ?></label><br />
   <span id="make_watermark" style="display: none;">
   <table width="200" align="center">
   <tr>
   <td><?=t('Текст'); ?></td><td><?=t('Цвет'); ?></td><td><?=t('Размер'); ?></td>
   </tr>
   <tr>
   <td><input type="text" name="watermark_text" size="10" value="Ваша надпись">
   <td><input type="text" name="textcolor" maxlength="6" size="4" value="FFFFFF">
   <td><input type="text" name="textsize" maxlength="2" size="1" value="12">
   </tr>
   <tr><td>
   <tr>
   <td><?=t('Позиция'); ?></td><td><?=t('Шрифт'); ?>
   <tr>
   <td><input type="radio" name="hotspot1" value="1"> <input type="radio" name="hotspot1" value="2"> <input type="radio" name="hotspot1" value="3"><br />
   <input type="radio" name="hotspot1" value="4"> <input type="radio" name="hotspot1" value="5" checked> <input type="radio" name="hotspot1" value="6"><br />
   <input type="radio" name="hotspot1" value="7"> <input type="radio" name="hotspot1" value="8"> <input type="radio" name="hotspot1" value="9">
   <td valign="top">
   <? if($fonts) { ?>
   <select name="watermark_font">
   <option value="none">Select</option>
   <? foreach($fonts as $font) {
   echo '<option value="'.$font.'">'.$font.'</option>';
   }
   ?>
   </select>
   <? } else {echo 'emptyFont';} ?>
   </table>
   <br /></span>
   
   <label for="merge"><input type="checkbox" name="merge" id="merge" onclick="javascript:ShowOrHide('make_merge')"<?=(!extension_loaded('gd') ? ' disabled' : ''); ?>><?=t('Наложить штамп'); ?></label><br />
   <span id="make_merge" style="display: none;">
   <table width="200" align="center">
   <tr>
   <td><?=t('Прозрачность'); ?>
   <tr>
   <td><input type="text" name="merge_transition" maxlength="2" size="1" value="40">
   <td>explanationTransition
   <tr><td>
   <tr>
    <td><?=t('Позиция'); ?></td><td>watermark
   <tr>
   <td width="50%"><input type="radio" name="hotspot2" value="1"> <input type="radio" name="hotspot2" value="5"> <input type="radio" name="hotspot2" value="2"><br />
   <input type="radio" name="hotspot2" value="8"> <input type="radio" name="hotspot2" value="0" checked> <input type="radio" name="hotspot2" value="6"><br />
   <input type="radio" name="hotspot2" value="4"> <input type="radio" name="hotspot2" value="7"> <input type="radio" name="hotspot2" value="3">
   <td width="50%" valign="top">
   <? if($watermarks) { ?>
   <select onchange="showpreview('data/watermark/'+this.options[this.selectedIndex].value, 'previewimage')" name="watermark_image">
   <? foreach($watermarks as $watermark_image) {
         echo '<option value="'.$watermark_image.'">'.$watermark_image.'</option>';
    }
   ?>
   </select><br />
   <img name="previewimage" width="100px" src="data/watermark/<?=$watermarks[0]; ?>" align="left" style="margin: 5px;">
   <? } else { echo $echo['emptyWatermark']; }
   ?>
   
   </table>
   <br /></span>
   
      <input type="submit" value="  <?=t('Загрузить'); ?>  ">
</table>
</form>

<td>
    <span id="show_folders" style="display: none;">
    <script type="text/javascript">
    function insert_folder(){
        myform = document.subfolder_form;
        if(myform.dropfolder.selectedIndex == 0){
            myform.selected_folder.disabled = true;
            myform.rename_folder.disabled = true;
            myform.delete_folder.disabled = true;
        }
        else{
            myform.selected_folder.disabled = false;
            myform.rename_folder.disabled = false;
            myform.delete_folder.disabled = false;
        }
        
        myform.selected_folder.value = myform.dropfolder.options[myform.dropfolder.selectedIndex].value;
        myform.old_folder.value = myform.dropfolder.options[myform.dropfolder.selectedIndex].value;
    }
    </script>
    <form method="post" action="">
   <b><?=t('Новая директория'); ?></b><br />
   <input type="text" name="new_folder" />
   <input type="submit" value="<?=t('Создать новую директорию'); ?>" />
   <input type="hidden" name="action" value="add_folder" />
   </form>
   
   <br /><b><?=t('Редактировать'); ?></b><br />
   <form method="post" name="subfolder_form" action="">
   <?=makeDropDown(get_subfolders(), 'dropfolder"  onChange="insert_folder();', t('Базы папок')); ?><br />
   <input type="text" name="selected_folder" value="" disabled />
   <input type="hidden" name="old_folder" value="" />
   <input type="submit" id="rename_folder" value="<?=t('Переименовать директорию'); ?>" disabled />
   <input type="submit" id="delete_folder" value="<?=t('Удалить директорию'); ?>" onclick="confirmDelete('<?=$PHP_SELF; ?>&action=delete_folder')" disabled />
   <input type="hidden" name="action" value="rename_subfolders" />
   </form>
    </span>
  </table>

<br /><br />

<? if($area) { ?>
<table width="200" border="0" cellspacing="2" cellpadding="0" align="center">
<tr>
<td>
align: <select onchange="window.location=this.options[this.selectedIndex].value">
<option value="<?=$config_http_script_dir.'/index.php?mod=images&area='.$_GET['area'].'&sortby='.$_GET['sortby'].'&start_from='.$_GET['start_from'].'&align=left'; ?>" <?=($_GET['align'] == 'left' ? 'selected' : '') ?>><?=$echo['alignLeft']; ?></option>
<option value="<?=$config_http_script_dir.'/index.php?mod=images&area='.$_GET['area'].'&sortby='.$_GET['sortby'].'&start_from='.$_GET['start_from'].'&align=right'; ?>" <?=(!$_GET['align'] ? ($default_align == 'align="right"' ? 'selected' : '') : ($_GET['align'] == 'right' ? 'selected' : '')) ?>><?=$echo['alignRight']; ?></option>
<option value="<?=$config_http_script_dir.'/index.php?mod=images&area='.$_GET['area'].'&sortby='.$_GET['sortby'].'&start_from='.$_GET['start_from'].'&align=none'; ?>" <?=(!$_GET['align'] ? ($default_align == '' ? 'selected' : '') : ($_GET['align'] == 'none' ? 'selected' : '')) ?>><?=$echo['alignNone']; ?></option>
</select>
</table>
<? } ?>

<table width="100%" border="0" cellspacing="2" cellpadding="0" align="center">
<tr><td>
<form method="post" name="current_folder" action="">
<?=t('Выделить директорию'); ?> <?=makeDropDown(get_subfolders(), 'subfolder"  onChange="document.current_folder.submit();', ($_POST['subfolder'] ? $_POST['subfolder'] : ($_GET['subfolder'] ? $_GET['subfolder'] : 'Main'))); ?>
<input type="hidden" name="start_from" value="" />
</form>

<tr><td><?=(($_GET['sortby'] == "time") ? "<a href='".$config['http_script_dir']."/index.php?mod=images&area=".$_GET['area']."&sortby=name&start_from=".$_GET['start_from']."&subfolder=".($_POST['subfolder'] ? $_POST['subfolder'] : $_GET['subfolder']).($area ? '&amp;align='.$_GET['align'] : '')."'>sortbyName</a>" : "<a href='".$config['http_script_dir']."/index.php?mod=images&area=".$_GET['area']."&sortby=time&start_from=".$_GET['start_from']."&subfolder=".($_POST['subfolder'] ? $_POST['subfolder'] : $_GET['subfolder']).($area ? '&amp;align='.$_GET['align'] : '')."'>sortbyTime</a>"); ?>

<?
$handle = opendir($folder);
while ($file = readdir($handle)){
    if (in_array(strtolower(end(explode('.', $file))), $allowed_extensions) or in_array(strtolower(end(explode('.', $file))), $media_extensions)){
        $files[$file] = filemtime($folder.'/'.$file);
    }
}

if (count($files)){
   (($_GET['sortby'] == "time") ? arsort($files) : ksort($files));

      foreach ($files as $file => $time){
      $all_images += filesize($folder.'/'.$file);
}

    $subfolder = end($dummy = explode("/", $folder));
    if($subfolder == 'upimages' or $subfolder == $user){
        $subfolder = false;
    }
    
    $image_per_page = ($image_per_page ? $image_per_page : 21);
    $start_from = ($start_from ? $start_from : '');
    $i = $start_from;
    $j = 0;
    foreach ($files as $file => $time){
    
    $info = array();
    $info_pic = array();
    
        if ($j < $start_from){
            $j++;
            continue;
        }

        $i++;
        $total += filesize($folder.'/'.$file);
        
        if(!in_array(strtolower(end(explode('.', $file))), $media_extensions)){
        
            $info_pic = getimagesize($config['path_image_upload'].(file_exists($folder.'/thumbs/'.$file) ? '/thumbs/' : '/').$file);
            $info = getimagesize($config['path_image_upload'].'/'.$file);
        }

        if (file_exists($folder.'/thumbs/'.$file)){
            if($popup){
                  $insert = '<a href="javascript:popupMedia(\\\''.$config['path_image_upload'].'/'.($user ? $user.'/' : '').($subfolder ? '/'.$subfolder.'/' : '').$file.'\\\', \\\''.$info_pic[0].'\\\', \\\''.$info_pic[1].'\\\')"><img '.($_GET['align'] == 'left' ? 'align="left"' : ($_GET['align'] == 'right' ? 'align="right"' : ($_GET['align'] == 'none' ? '' : $default_align))).' src="{imagepath}/'.($user ? $user.'/' : '').($subfolder ? 'subfolders/'.$subfolder.'/' : '').'thumbs/'.$file.'" alt="'.$file.'" border="0" '.$info[3].' /></a>';
              } else{
                  $insert = '<a target="_blank" href="{imagepath}/'.($user ? $user.'/' : '').($subfolder ? '/'.$subfolder.'/' : '').$file.'"><img '.($_GET['align'] == 'left' ? 'align="left"' : ($_GET['align'] == 'right' ? 'align="right"' : ($_GET['align'] == 'none' ? '' : $default_align))).' src="{imagepath}/'.($user ? $user.'/' : '').($subfolder ? 'subfolders/'.$subfolder.'/' : '').'thumbs/'.$file.'" alt="'.$file.'" border="0" '.$info[3].' /></a>';
            }
        } 
        
        else {
            $insert = '<img '.($_GET['align'] == 'left' ? 'align="left"' : ($_GET['align'] == 'right' ? 'align="right"' : ($_GET['align'] == 'none' ? '' : $default_align))).' src="{imagepath}/'.($user ? $user.'/' : '').($subfolder ? 'subfolders/'.$subfolder.'/' : '').$file.'" alt="'.$file.'" border="0" '.$info[3].' />';
            
            $media_embed = '<OBJECT id="VIDEO" width="'.$settings -> settings['video_width'].
                            '" height="'.$settings -> settings['video_height'].'" '.
                            'CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="application/x-oleobject"> '.
                            '<PARAM NAME="URL" VALUE="{imagepath}/'.($user ? $user.'/' : '').
                            ($subfolder ? 'subfolders/'.$subfolder.'/' : '').$file.'"> '.
                            '<PARAM NAME="AutoStart" VALUE="'.($settings -> settings['auto_start'] == 'yes' ? 'True' : 'False').'"> '.
                            '<PARAM NAME="uiMode" VALUE="'.$settings -> settings['uimode'].'"></OBJECT>';
                            
            $media_download = '<a href="{imagepath}/'.($user ? $user.'/' : '').
                            ($subfolder ? '/'.$subfolder.'/' : '').$file.'">Download this video.</a>';
            
        }

        if(in_array(strtolower(end(explode('.', $file))), $allowed_extensions)){
            $insert = ($area ? '<a '.(file_exists($folder.'/thumbs/'.$file) ? 'title="'.sprintf($echo['insertThumbTitle'], $area).'"' : 'title="'.sprintf($echo['insertImageTitle'], $area).'"').'href="javascript:insertimage(\''.htmlspecialchars($insert).'\')">'.$echo['insert'].'</a>' : '&nbsp;');
        }
        elseif(in_array(strtolower(end(explode('.', $file))), $media_extensions)){
            $insert = ($area ? '<a href="javascript:insertimage(\''.htmlspecialchars($media_embed).'\')">'.$echo['embed'].'</a>' : '&nbsp;');
            $insert .= ($area ? '<br /><a href="javascript:insertimage(\''.htmlspecialchars($media_download).'\')">insertLink</a>' : '&nbsp;');
        }
?>

 <tr <?=cute_that(); ?> align="center">
 
 <? if(in_array(strtolower(end(explode('.', $file))), $media_extensions)){ ?>
    <td>mediaFile</td>
    <td><?=$file; ?></td>
 <? } else { ?>
 
 <td width="120"><?=(file_exists($folder.'/thumbs/'.$file) ? '<a target="_blank" title="thumbTitle" href="'.$config['path_image_upload'].'/thumbs/'.$file.'"><img src="'.$config['path_image_upload'].'/thumbs/'.$file.'" width="120"></a>' : '<img src="'.$config['path_image_upload'].'/'.$file.'" width="120">'); ?>
  <td height="17"><a href="javascript:popupMedia('<?=($config['path_image_upload'].'/'.$file); ?>', '<?=$info[0]?>', '<?=$info[1]?>')"><?=$file; ?></a>  
  <? } ?>
 
  <td><a href="?mod=images&amp;action=rename<?=($_POST['subfolder'] ? '&amp;subfolder='.$_POST['subfolder'] : ($_GET['subfolder'] ? '&amp;subfolder='.$_GET['subfolder'] : '')); ?>&amp;image=<?=$file.$query_string; ?>" onclick="if (ren=window.prompt('', '<?=$file; ?>')){window.location.href=this.href+'&name='+ren;}return false;"><?=t('Переименовать'); ?></a>
  <td><a href="javascript:confirmDelete('?mod=images&amp;action=remove<?=($_POST['subfolder'] ? '&amp;subfolder='.$_POST['subfolder'] : ($_GET['subfolder'] ? '&amp;subfolder='.$_GET['subfolder'] : '')); ?>&amp;image=<?=$file.$query_string; ?>')"><?=t('Удалить'); ?></a>
  
  <? if(!$area){ ?>
  <td>moveTo<br />
  <form method="post" name="move_file_form_<?=$i; ?>" action="">
  <?=makeDropDown(get_subfolders(), 'new_path"  onChange="document.move_file_form_'.$i.'.submit();', ($_POST['subfolder'] ? $_POST['subfolder'] : ($_GET['subfolder'] ? $_GET['subfolder'] : 'baseFolder'))); ?>
  <input type="hidden" name="action" value="move_file" />
  <input type="hidden" name="image" value="<?=$file; ?>" />
  <? if(!$_GET['subfolder'] or $_GET['subfolder'] == ''){ ?>
  <input type="hidden" name="subfolder" value="<?=$subfolder; ?>" />
  <? } ?>
  </form>
  <? } ?>
  
  <td><?=$info[0]?>x<?=$info[1]?> <?=formatsize(filesize($folder.'/'.$file)); ?>

<?
        if ($i >= $image_per_page + $start_from){
            break;
        }
    }

    if ($start_from > 0){
        $previous = $start_from - $image_per_page;
        $npp_nav .= '<a href="'.$PHP_SELF.'&amp;start_from='.$previous.'&amp;subfolder='.($_POST['subfolder'] ? $_POST['subfolder'] : $_GET['subfolder']).($area ? '&amp;align='.$_GET['align'] : '').'">&lt;&lt;</a>';
    }

    if (count($files) > $image_per_page){
        $npp_nav .= ' [ ';
        $enpages_count = @ceil(count($files) / $image_per_page);
        $enpages_start_from = 0;
        $enpages = '';

        for ($j = 1; $j <= $enpages_count; $j++){
            if ($enpages_start_from != $start_from){
                $enpages .= '<a href="'.$PHP_SELF.'&amp;start_from='.$enpages_start_from.'&amp;subfolder='.($_POST['subfolder'] ? $_POST['subfolder'] : $_GET['subfolder']).($area ? '&amp;align='.$_GET['align'] : '').'">'.$j.'</a> ';
            } else {
                $enpages .= ' <b> <u>'.$j.'</u> </b> ';
            }

            $enpages_start_from += $image_per_page;
        }

        $npp_nav .= $enpages;
        $npp_nav .= ' ] ';
    }

    if (count($files) > $i){
        $npp_nav .= '<a href="'.$PHP_SELF.'&amp;start_from='.$i.'&amp;subfolder='.($_POST['subfolder'] ? $_POST['subfolder'] : $_GET['subfolder']).($area ? '&amp;align='.$_GET['align'] : '').'">&gt;&gt;</a>';
    }
?>

<tr>
 <td><br /><br /><?=$npp_nav; ?>
 <td align="right" colspan="5"><br /><br /><?=sprintf('total', formatsize($total)); 

if (count($files) > $image_per_page){
    echo '<tr><td align="right" colspan="6">'.sprintf('allimages', formatsize($all_images));
}
?>

</table>

<?
}

if (!$area){
    echofooter();
}

function get_subfolders(){
global $base_folder, $allowed_extensions, $media_extensions;

$dir = @opendir($base_folder);
$all_subfolders = array();
$all_subfolders['base'] = t('Корневая директория -->');
while ($subfolder = @readdir($dir)){

if (!in_array(strtolower(end(explode('.', $subfolder))), $allowed_extensions)){
      if (is_dir($base_folder) and ($subfolder != '.') and ($subfolder != '..') and ($subfolder != 'thumbs') and ($subfolder != '.htaccess')){
        $all_subfolders[$subfolder] = '- '.$subfolder;
      }
    }
 }
@closedir($dir);
return $all_subfolders;
}

function dir_is_empty($path){
$dir = opendir($path);
$i = 0;
while ($files_in_subfolder = readdir($dir)) {
if($files_in_subfolder != "." and $files_in_subfolder != ".." and $files_in_subfolder != "thumbs" and $files_in_subfolder != ".htaccess"){
$i++;
        }
    }
    if($i == 0) return true;
    else return false;
}
?>

Там есть создание новых директорий , сортировка по ним , перемещение картинок по директориям, модуль настройки медиа файлов (с небходмостью перекочует в плагин Adepto Fastload), ватермарки (текс или картинка jpg/ png - der Beste Gruess fuer Mr. Miksar), возможность кадрирования картино (например для иконок - об этом позже)

Мультизагрузчик можно посмотреть здесь

Необходиме функции (в functions.inc.php)

///////////////////Function image resize/////////////////

function img_resize($src, $dest, $new_size, $way){
        $size = getimagesize($src);
        $img_width = $size[0];
        $img_height = $size[1];
        
        if(($img_width > $new_size) or ($img_height > $new_size)){ //Keep dimensions
            if($way == "normal"){
                $ratio = $new_size/$img_width;
                $new_width = $new_size;
                $new_height = $img_height*$ratio;
                $off_w = 0;
                $off_h = 0;
                } else { //Crop
                if($img_width > $img_height){
                    $new_width = $new_size;
                    $new_height = $new_size;
                    $off_w = ($img_width-$img_height)/2;
                    $off_h = 0;
                    $img_width = $img_height;
                }else if ($img_height > $img_width){
                    $new_width = $new_size;
                    $new_height = $new_size;
                    $off_w = 0;
                    $off_h = ($img_height - $img_width)/2;
                    $img_height = $img_width;
                }else{
                      $new_width = $new_size;
                      $new_height = $new_size;
                      $off_w = 0;
                      $off_h = 0;
                  }
              }
            
        switch (strtolower(end(explode('.', $src)))){
        case 'gif':
            $im_in = @imagecreatefromgif($src);
            break;
        case 'jpg':
            $im_in = @imagecreatefromjpeg($src);
            break;
        case 'png':
            $im_in = @imagecreatefrompng($src);
            break;
    }

            $im_out = @imagecreatetruecolor($new_width, $new_height);
            @imagecopyresampled($im_out, $im_in, 0, 0, $off_w, $off_h, $new_width, $new_height, $img_width, $img_height);
        } else {
            @copy($src, $dest);
        }

     switch (strtolower(end(explode('.', $src)))){
        case 'gif':
            @imagegif($im_out, $dest);
            break;
        case 'jpg':
            @imagejpeg($im_out, $dest);
            break;
        case 'png':
            @imagepng($im_out, $dest);
            break;
    }
}
////////////////////Function mergePix///////////////////////

function mergePix($sourcefile, $insertfile, $targetfile, $pos=0, $transition=100){

$suffx=substr($sourcefile,strlen($sourcefile)-4,4);
$suffx = strtolower($suffx);

if ($suffx=='.jpg' || $suffx=='jpeg') {
     $sourcefile_id = imagecreatefromjpeg($sourcefile);
 }
if ($suffx=='.png') {
$sourcefile_id = imagecreatefrompng($sourcefile);
}
if ($suffx == '.gif') {
$sourcefile_id = imagecreatefromgif($sourcefile);
}

$insuffx=substr($insertfile,strlen($insertfile)-4,4);
$insuffx = strtolower($insuffx);

if ($insuffx=='.jpg' || $insuffx=='jpeg') {
$insertfile_id = imagecreatefromjpeg($insertfile);
}
if ($insuffx=='.png') {
$insertfile_id = imagecreatefrompng($insertfile);
}
if ($insuffx == '.gif') {
$insertfile_id = imagecreatefromgif($insertfile);
}

        //Get the sizes of both pix
        $sourcefile_width=imageSX($sourcefile_id);
        $sourcefile_height=imageSY($sourcefile_id);
        $insertfile_width=imageSX($insertfile_id);
        $insertfile_height=imageSY($insertfile_id);

        if( $pos == 0 ){ //middle
                $dest_x = ( $sourcefile_width / 2 ) - ( $insertfile_width / 2 );
                $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
        }

        if( $pos == 1 ){ //top left
                $dest_x = 10;
                $dest_y = 10;
        }

        if( $pos == 2 ){ //top right
                $dest_x = $sourcefile_width - $insertfile_width - 10;
                $dest_y = 10;
        }

        if( $pos == 3 ){ //bottom right       
                $dest_x = $sourcefile_width - $insertfile_width - 10;
                $dest_y = $sourcefile_height - $insertfile_height - 10;
        }

        if( $pos == 4 ){ //bottom left
                $dest_x = 10;
                $dest_y = $sourcefile_height - $insertfile_height - 10;
        }

        if( $pos == 5 ){ //top middle
                $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
                $dest_y = 10;
        }

        if( $pos == 6 ){ //middle right
                $dest_x = $sourcefile_width - $insertfile_width - 10;
                $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
        }

        if( $pos == 7 ){ //bottom middle
                $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
                $dest_y = $sourcefile_height - $insertfile_height - 10;
        }

        if( $pos == 8 ) { //middle left
                $dest_x = 10;
                $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
        }

imagealphablending($sourcefile_id, TRUE);
imagealphablending($insertfile_id, TRUE);
imagealphablending($targetfile, TRUE);

//The main thing : merge the two pix
#imageCopyMerge($sourcefile_id, $insertfile_id, $dest_x, $dest_y, 0, 0, $insertfile_width, $insertfile_height, $transition);
imagecopy($sourcefile_id, $insertfile_id, $dest_x, $dest_y, 0, 0,$insertfile_width, $insertfile_height);

if ($suffx=='.jpg' || $suffx=='jpeg') {
imagejpeg($sourcefile_id, $targetfile);
}
if ($suffx=='.png') {
imagepng($sourcefile_id, $targetfile);
}
if ($suffx == '.gif') {
imagegif($sourcefile_id, $targetfile);
}

imagedestroy($targetfile);
imagedestroy($sourcefile_id);
imagedestroy($insertfile_id);
}
/////////////////// Function Watermark /////////////////////

function add_watermark($thumb_in,$text="[date]",$hotspot=8,$rgbtext="FFFFFF",$font_size=12,$font="Arial.TTF",$datfmt="d-m-Y",$rgbtsdw="000000",$txp=15,$typ=5,$sxp=1,$syp=1) {

 $suffx=substr($thumb_in,strlen($thumb_in)-4,4);
 $suffx = strtolower($suffx);
 if ($suffx==".jpg" || $suffx=="jpeg" || $suffx==".png" || $suffx==".gif") {
 #$text=str_replace("[date]",date($datfmt),$text);

 if ($suffx==".jpg" || $suffx=="jpeg") {
      $image=imagecreatefromjpeg($thumb_in);
}
 if ($suffx==".png") {
     $image=imagecreatefrompng($thumb_in);
}
 if ($suffx == ".gif") {
$image=imagecreatefromgif($thumb_in);
 }

$rgbtext=HexDec($rgbtext);
$txtr=floor($rgbtext/pow(256,2));
$txtg=floor(($rgbtext%pow(256,2))/pow(256,1));
$txtb=floor((($rgbtext%pow(256,2))%pow(256,1))/pow(256,0));

$rgbtsdw=HexDec($rgbtsdw);
$tsdr=floor($rgbtsdw/pow(256,2));
$tsdg=floor(($rgbtsdw%pow(256,2))/pow(256,1));
$tsdb=floor((($rgbtsdw%pow(256,2))%pow(256,1))/pow(256,0));

$coltext = imagecolorallocate($image,$txtr,$txtg,$txtb);
$coltsdw = imagecolorallocate($image,$tsdr,$tsdg,$tsdb);

if ($hotspot!=0) {
$ix=imagesx($image); $iy=imagesy($image); $tsw=strlen($text)*$font_size/imagefontwidth($font)*3; $tsh=$font_size/imagefontheight($font);
switch ($hotspot) {
case 1:
$txp=$txp; $typ=$tsh*$tsh+imagefontheight($font)*2+$typ;
break;
case 2:
$txp=floor(($ix-$tsw)/2); $typ=$tsh*$tsh+imagefontheight($font)*2+$typ;
break;
case 3:
$txp=$ix-$tsw-$txp; $typ=$tsh*$tsh+imagefontheight($font)*2+$typ;
break;
case 4:
$txp=$txp; $typ=floor(($iy-$tsh)/2);
break;
case 5:
$txp=floor(($ix-$tsw)/2); $typ=floor(($iy-$tsh)/2);
break;
case 6:
$txp=$ix-$tsw-$txp; $typ=floor(($iy-$tsh)/2);
break;
case 7:
$txp=$txp; $typ=$iy-$tsh-$typ;
break;
case 8:
$txp=floor(($ix-$tsw)/2); $typ=$iy-$tsh-$typ;
break;
case 9:
$txp=$ix-$tsw-$txp; $typ=$iy-$tsh-$typ;
break;
   }
}

ImageTTFText($image,$font_size,0,$txp+$sxp,$typ+$syp,$coltsdw,$font,$text);
ImageTTFText($image,$font_size,0,$txp,$typ,$coltext,$font,$text);

  if ($suffx==".jpg" || $suffx=="jpeg") {
        imagejpeg($image, $thumb_in);
}
  if ($suffx==".png") {
       imagepng($image, $thumb_in);
}
  if ($suffx == ".gif") {
       imagegif($image, $thumb_in);
      } 
   }
}

///////////////////////////
//Function dropshadow
//Adds a dropshadow to the thumb
//Code taken from http://codewalkers.com/tutorials/83/1.html
//////////////////////////////////
function make_shadow($thumb_in) {

define("DS_OFFSET",     5);
define("DS_STEPS", 10);
define("DS_SPREAD", 1);

$background = array("r" => 255, "g" => 255, "b" => 255);
list($o_width, $o_height) = getimagesize($thumb_in);

$width    = $o_width + DS_OFFSET;
$height = $o_height + DS_OFFSET;
$image_sh = @imagecreatetruecolor($width, $height);

$step_offset = array("r" => ($background["r"] / DS_STEPS), "g" => ($background["g"] / DS_STEPS), "b" => ($background["b"] / DS_STEPS));

$current_color = $background;
for ($i = 0; $i <= DS_STEPS; $i++) {
    $colors[$i] = @imagecolorallocate($image_sh, round($current_color["r"]), round($current_color["g"]), round($current_color["b"]));

    $current_color["r"] -= $step_offset["r"];
    $current_color["g"] -= $step_offset["g"];
    $current_color["b"] -= $step_offset["b"];
}
@imagefilledrectangle($image_sh, 0,0, $width, $height, $colors[0]);

for ($i = 0; $i < count($colors); $i++) {
    @imagefilledrectangle($image_sh, DS_OFFSET, DS_OFFSET, $width, $height, $colors[$i]);
    $width -= DS_SPREAD;
    $height -= DS_SPREAD;
}

switch (strtolower(end(explode('.', $thumb_in))))
    {
        case 'gif':
            $original_image = imageCreateFromGIF($thumb_in);
            break;
        case 'jpg':
            $original_image = imageCreateFromJPEG($thumb_in);
            break;
        case 'png':
            $original_image = imageCreateFromPNG($thumb_in);
            break;
    }

  @imagecopymerge($image_sh, $original_image, 0,0, 0,0, $o_width, $o_height, 100);

switch (strtolower(end(explode('.', $thumb_in))))
    {
        case 'gif':
            @imagegif($image_sh, $thumb_in);
            break;
        case 'jpg':
            @imagejpeg($image_sh, $thumb_in);
            break;
        case 'png':
            @imagepng($image_sh, $thumb_in);
            break;
    }

}

Отредактировано YurySpoloh (29 Oct 2009 18:52:34)

Re: Создание Галерей на Strawberry1.1.1

YurySpoloh, будет ли продолжение у этой темы?  Можно эту галерею тестировать?

Re: Создание Галерей на Strawberry1.1.1

а почему нельзя? он и выкладывает для этого wink

Здесь молодость бродит крылато, и старость не клонит голов...
Демо площадка Strawberry 1.2 - заходим и тестируем!

13

Re: Создание Галерей на Strawberry1.1.1

DeGe, Разумеется можно, все то что касается images.mdu.

Столкнулся с задачей как можно идентифицироват галерею по названию...
Не совсем понятно ... или же надо булде т делать ее по аналогии с новостими , т.е в 2 таблицы ?

Очень , очень очень сырой gallery .mdu

<?php
// ********************************************************************************
// List All Available Gallery + Show Add Gallery Form
// ********************************************************************************
////////////////////////  строим таблицы (эти функции можно залить в свой functions.inc.php)///////////////////////////
function open_table ($width, $height, $align, $border, $cellspac, $cellspac) {
 echo '<table width="'.$width.'" height="'.$height.'" align="'.$align.'" border="'.$border.'" cellspacing="'.$cellspac.'" cellpadding="'.$cellspac.'">
        <tr>';
 }

function close_table() {
 echo '</tr>
  </table>';
}

$image_path = $config['path_image_upload'];
$folder = cute_parse_url($config['path_image_upload']);
$folder = $folder['abs'];

$types = array('' => t('Выбрать тип галереи -->'), 'post' => t('Посты / Новости'), 'album' => t('Альбом'), 'private' => t('Запароленый'));

if (!$action) {
echoheader('images', t('Управление галереями'));
       if (!$number){
            $number = 21; // в настройки
       }

       $query = $sql->select(array('table' => 'gallery', 'limit' => array(($skip ? $skip : 0), $number))); 
       $count = sizeof($sql->select(array('table' => 'gallery')));       
?>

<style>
<!--
.highslide-container div { /* текст под картинкой (description) */
    font-size: 9pt;
    font-weight: bold;
    padding: 3px 0 5px 4px;
    font-family: Verdana, Helvetica;
 }
 
.highslide-wrapper, .highslide-outline {
    background: white;
}
.highslide-dimming {
    position: absolute;
    background: black;
}
-->
</style>
<script type="text/javascript" src="../js/highslide.js"></script>
<script type="text/javascript">
<!--
    hs.align = 'center';
    hs.showCredits = false;
    hs.graphicsDir = '../images/';
    hs.captionEval = 'this.thumb.desc'; // description
    hs.transitions = ['expand', 'crossfade'];
    hs.outlineType = 'rounded-white'; //border
    hs.dimmingOpacity = 0.25; //dark shadow
-->
</script>
<div id="navcell">
<div align="right" style="float: right; margin: -2px 1px 0">
<select name="action">
<option value="">- Сортировать -</option>
<option value="delete">Удалить</option>
<option value="movetocat">Изменить категорию</option>
<option value="publish">Опубликовать</option>
<option value="movetotype">Изменить тип поста</option>
</select>
</div>
<a href="#" onclick="OpenTab('gallery', 0)"> <?=t('галереи'); ?> </a><a href="#" onclick="OpenTab('add', 1)"><?=t(' добавить '); ?></a><a href="#" onclick="OpenTab('option', 2)"> <?=t('настройки'); ?> </a>
</div>
<div id="masterdiv">
<table width="100%" cellspacing="0" cellpadding="0" class="tabs" id="gallery" style="display: block">
<tr>
<?
if($query){
      if ($count_links and $number){ // создаем листалку
          $pages_skip  = 0;
          $pages_count = @ceil($count / $number);

           for ($i = 1; $i <= $pages_count; $i++){
               if ($pages_skip != $skip){
                  $pages[] = '<a href="'.$PHP_SELF.'?mod=gallery&skip='.$pages_skip.'">'.$i.'</a>';
               } else {
                  $pages[] = '<b><u>'.$i.'</u></b>';
               }

             $pages_skip += $number;
          }

           if ($pages_count > 1){
                  $pages = ($skip ? '<a href="'.$PHP_SELF.'?mod=gallery&skip='.($skip - $number).'">'.t('&lt;&lt; Пред.').'</a> ' : '').'[ '.join(' ', $pages).' ]'.((($pages_skip - $number) - $skip) ? ' <a href="'.$PHP_SELF.'?mod=gallery&skip='.($skip + $number).'">'.t('След. &gt;&gt;').'</a> ' : '');
           } else {
                  $pages = '';
          }
       }
   
   foreach ($query as $row){ 
   
          $edit = ' &nbsp;<small><a href="?mod=gallery&amp;action=edit&amp;catid='.$row['id'].'">'.t('[правка]').'</a>&nbsp;<a href="javascript:confirmDelete(\'?mod=gallery&amp;action=remove&amp;catid='.$row['id'].'\')">'.t('[удалить]').'</a></small>';      
          showRow($row['title'].$edit, $row['description'], '<a title="'.$row['description'].'" href="'.$image_path.'/'.$row['image'].'" onclick="return hs.expand(this)"><img src="'.$image_path.'/thumbs/'.$row['image'].'" align="right" width="55" desc="'.$row['description'].'<br>Рейтинг: '.$row['rating'].$row['id'].'" /></a>');
         
         }
          showRow('', '', $pages);
       } else echo '<td align="center" style="padding: 20px">'.t(' -- изображений нет -- ');
         
         //echo '<p align="center">'.$pages.'</p>';
         close_table(); 
?>

   
<table width="100%" cellspacing="2" cellpadding="2" class="tabs" id="add" style="display: none">
<tr>
   <form method="post" action="<?=$PHP_SELF; ?>" onsubmit="return process_form(this)">
   <td valign="bottom" height="10">&nbsp;
       <tr>
           <td width="150"><?=t('Название галереи'); ?>
           <td><input size="50" type="text" name="name">
       <tr> 
           <td><?=t('Url (при желании)'); ?>
           <td><input size="50" type="text" name="url">
      <tr>
           <td>&nbsp;<?=t('Тип галереи'); ?>
           <td>
                <?=makeDropDown($types, 'type"  onChange="this.value == \'post\' ? $(\'postparent\').show() : $(\'postparent\').hide(); this.value == \'private\' ? $(\'postpassword\').show() : $(\'postpassword\').hide();', ''); ?><br>
                <input size="25" id="password" name="postpassword" type="text" style="display: none;">
                <select size="1" id="postparent" name="postparent" style="display: none">
                <option value="0">...</option>';
                <?=catalogs_get_tree('-&nbsp;', '<option value="{id}">{name}</option>', false); ?>
                </select> 
       <tr>
           <td>&nbsp;<?=t('Действие'); ?>
           <td>
           <input type="checkbox" name="publication" id="publication"><label for="publication"><?=t('опубликовать'); ?></label>
           <input type="checkbox" name="project" id="project">&nbsp;<label for="project"><?=t('проекты'); ?></label>
      <tr>
        <td>&nbsp;
        <td height="35">
         <input type="submit" class="button" value="  <?=t('Добавить'); ?>  ">
         <input type="hidden" name="action" value="addgallery">
         <input type="hidden" name="mod" value="gallery">
  </form>
      </table>
</div>

<?
}
if($action == 'addgallery'){
  
$name = $_POST['name'];
$url = $_POST['url'];

echoheader('images', t('Добавление изображений'));
echo '<p>Добавить изображения в галерею <b>'.$name.'</b></p>';
?>
<script language="javascript">
<!--
 f = 0
 function file_uploader(which){
 if (which < f) return
 f ++
 $('image_'+f).innerHTML = '<input size="40" type="file" name="image['+f+']" id="image_'+f+'" value="" onchange="file_uploader('+f+');" /><br /><input size="50" type="text" id="image_'+f+'" name="description['+f+']"><br /><span id="image_'+(f+1)+'"></span>'
 }
 -->
 </script>

<table width="100%" cellspacing="2" cellpadding="2">
<tr>
   <form method="post" action="<?=$PHP_SELF; ?>" enctype="multipart/form-data">
   <td><?=t('Загрузить катинки'); ?>
   <td>
<script language="javascript">
    document.writeln('<input size="40" type="file" name="image[0]" value="" onchange="file_uploader(0);" /><br />')
    document.writeln('<input size="50" type="text" name="description[0]"><br />')
    document.writeln('<span id="image_1"></span>')
</script>
      <tr>
        <td>&nbsp;<?=t('Действие'); ?>
        <td height="35">
         <input type="submit" class="button" value="  <?=t('Добавить'); ?>  ">
         <input type="button" class="button" value="   <?=t('Отмена'); ?>    " onclick="javascript:document.location='<?=$PHP_SELF; ?>?mod=gallery'">
         <input type="hidden" name="name" value="<?=$name; ?>">
         <input type="hidden" name="url" value="<?=$url; ?>">
         <input type="hidden" name="action" value="addimages">
         <input type="hidden" name="mod" value="gallery">
  </form>
</table>

<?
 }
 
///////////// начинаем акцию //////////////////////
if($action == 'addimages'){

$allowed_upload = false;

if ($_FILES['image']['name']){

     //for ($i = 0; $i < count($_FILES['image']['name']); $i++){
     for ($i = 0; $i < (count($_FILES['image']['name']) - 1); $i++){ ////////
      if (!empty($_FILES['image']['name'][$i])) {
     
        $ext   = end($ext = explode('.', $_FILES['image']['name'][$i]));
        $type  = end($type = explode('/', $_FILES['image']['type'][$i]));
        $image = preg_replace('/(.*?).'.$ext.'$/ie', "totranslit('\\1')", $_FILES['image']['name'][$i]).'.'.$ext;

         foreach ($allowed_extensions as $allow){
            if (substr($type, -strlen($allow)) == $allow){
                $allowed_upload = true;
            }
         }

         if (!file_exists($folder.'/'.$image) and $allowed_upload){
              move_uploaded_file($_FILES['image']['tmp_name'][$i], $folder.'/'.$image);
              @img_resize($folder.'/'.$image, $folder.'/thumbs/'.$image, $config['newsicon']);
              
              $size = @getimagesize($folder.'/'.$image); // размеры
         }
         
         $sql->insert(array( ////////// добавляем в БД
         'table'  => 'gallery',
         'values' => array(
                
                 'date'         => (time() + $config['date_adjust'] * 60),
                'title'        => $name,
                'width'        => $size[0],
                'height'       => $size[1],
                'image'        => $image,
                'url'          => ($url ? $url : totranslit($name)),
                'author'       => $member['username'],
                'description'  => $description[$i],
                'publication'  => ($publication ? true : false)
          )
        ));
      }
    } ///    
  }     msg('user', t('Управление галереями'), t('Изменения сохранены.'), $PHP_SELF.'?mod=gallery');  
}   ///////////////////////////////////////////////////////////////////
?>

<?
echofooter();
?>

Отредактировано YurySpoloh (24 Nov 2009 18:50:09)

Re: Создание Галерей на Strawberry1.1.1

У меня при исправлении файла functions.inc.php не отображаются страницы в админке.

Если всталяю только код " ///////////////////Function image resize/////////////////", всё работает.
Папки создаются, фото перемещаются, привью создаются, тени накладываются.

15

Re: Создание Галерей на Strawberry1.1.1

Ой , там по мойму баг есть = папки не удаляются ...
Ну не как не могу исправить sad

Re: Создание Галерей на Strawberry1.1.1

ДА не удаляются.
Ещё заметила, что при добавлении клипа .avi он идентифицируется как папка в поле РЕДАКТИРОВАТЬ.

17

Re: Создание Галерей на Strawberry1.1.1

столкнулся вдруг с проблемой которой раньше не было :

вот кусок кода из 13-го поста

///////////// начинаем акцию //////////////////////
if($action == 'addimages'){

$allowed_upload = false;

if ($_FILES['image']['name']){

     for ($i = 0; $i < count($_FILES['image']['name']); $i++){
    
      if (!empty($_FILES['image']['name'][$i])) {
     
        $ext   = end($ext = explode('.', $_FILES['image']['name'][$i]));
        $type  = end($type = explode('/', $_FILES['image']['type'][$i]));
        $image = preg_replace('/(.*?).'.$ext.'$/ie', "totranslit('\\1')", $_FILES['image']['name'][$i]).'.'.$ext;

         foreach ($allowed_extensions as $allow){
            if (substr($type, -strlen($allow)) == $allow){
                $allowed_upload = true;
            }
         }

         if (!file_exists($folder.'/'.$image) and $allowed_upload){
              move_uploaded_file($_FILES['image']['tmp_name'][$i], $folder.'/'.$image);
              @img_resize($folder.'/'.$image, $folder.'/thumbs/'.$image, $config['newsicon']);
              
              $size = @getimagesize($folder.'/'.$image); // размеры
         }
         
         $sql->insert(array( ////////// добавляем в БД
         'table'  => 'gallery',
         'values' => array(
                
                 'date'         => (time() + $config['date_adjust'] * 60),
                'title'        => $name,
                'width'        => $size[0],
                'height'       => $size[1],
                'image'        => $image,
                'url'          => ($url ? $url : totranslit($name)),
                'author'       => $member['username'],
                'description'  => $description[$i],
                'publication'  => ($publication ? true : false)
          )
        ));
      }
    } 
  }     msg('user', t('Управление галереями'), t('Изменения сохранены.'), $PHP_SELF.'?mod=gallery');  
}   

как грамотно можно прописать добавления в БД нескольких картинок.
форма для их загрузки как в images.mdu открывает загрузочные импуты до бесконечности.
но строка в БД создается одна.

Re: Создание Галерей на Strawberry1.1.1

А можно скачать что-то готовое, чтобы установить и посмотреть?