source: extensions/upload_form/upload.php @ 4829

Last change on this file since 4829 was 4829, checked in by plg, 14 years ago

feature 1408 added: upload a zip archive containing photos, needs more tests
(on windows operating system) but "yeah it already rocks" :-)

pclzip 2.8.2 included because the low memory usage features is missing from
pclzip 2.8.1 included in Piwigo core.

File size: 12.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2010      Pierrick LE GALL             http://piwigo.org |
6// +-----------------------------------------------------------------------+
7// | This program is free software; you can redistribute it and/or modify  |
8// | it under the terms of the GNU General Public License as published by  |
9// | the Free Software Foundation                                          |
10// |                                                                       |
11// | This program is distributed in the hope that it will be useful, but   |
12// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
13// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
14// | General Public License for more details.                              |
15// |                                                                       |
16// | You should have received a copy of the GNU General Public License     |
17// | along with this program; if not, write to the Free Software           |
18// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
19// | USA.                                                                  |
20// +-----------------------------------------------------------------------+
21
22if( !defined("PHPWG_ROOT_PATH") )
23{
24  die ("Hacking attempt!");
25}
26
27include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
28include_once(UPLOAD_FORM_PATH.'include/functions_upload.inc.php');
29load_language('plugin.lang', UPLOAD_FORM_PATH);
30
31$admin_base_url = get_root_url().'admin.php?page=plugin&section=upload_form%2Fupload.php';
32
33// +-----------------------------------------------------------------------+
34// | Check Access and exit when user status is not ok                      |
35// +-----------------------------------------------------------------------+
36check_status(ACCESS_ADMINISTRATOR);
37
38// +-----------------------------------------------------------------------+
39// |                        batch management request                       |
40// +-----------------------------------------------------------------------+
41
42if (isset($_GET['batch']))
43{
44  check_input_parameter('batch', $_GET['batch'], false, '/^\d+(,\d+)*$/');
45
46  $query = '
47DELETE FROM '.CADDIE_TABLE.'
48  WHERE user_id = '.$user['id'].'
49;';
50  pwg_query($query);
51
52  $inserts = array();
53  foreach (explode(',', $_GET['batch']) as $image_id)
54  {
55    array_push(
56      $inserts,
57      array(
58        'user_id' => $user['id'],
59        'element_id' => $image_id,
60        )
61      );
62  }
63  mass_inserts(
64    CADDIE_TABLE,
65    array_keys($inserts[0]),
66    $inserts
67    );
68
69  redirect(get_root_url().'admin.php?page=element_set&cat=caddie');
70}
71
72// +-----------------------------------------------------------------------+
73// |                             process form                              |
74// +-----------------------------------------------------------------------+
75
76if (isset($_POST['submit_upload']))
77{
78  $category_id = null;
79  if ('existing' == $_POST['category_type'])
80  {
81    $category_id = $_POST['category'];
82  }
83  elseif ('new' == $_POST['category_type'])
84  {
85    $output_create = create_virtual_category(
86      $_POST['category_name'],
87      (0 == $_POST['category_parent'] ? null : $_POST['category_parent'])
88      );
89   
90    $category_id = $output_create['id'];
91
92    if (isset($output_create['error']))
93    {
94      array_push($page['errors'], $output_create['error']);
95    }
96    else
97    {
98      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
99      // information
100      array_push(
101        $page['infos'],
102        sprintf(
103          l10n('Category "%s" has been added'),
104          '<em>'.$category_name.'</em>'
105          )
106        );
107      // TODO: add the onclick="window.open(this.href); return false;"
108      // attribute with jQuery on upload.tpl side for href containing
109      // "cat_modify"
110    }
111  }
112
113  $image_ids = array();
114  $page['thumbnails'] = array();
115     
116  $starttime = get_moment();
117 
118  foreach ($_FILES['image_upload']['error'] as $idx => $error)
119  {
120    if (UPLOAD_ERR_OK == $error)
121    {
122      $images_to_add = array();
123     
124      $extension = pathinfo($_FILES['image_upload']['name'][$idx], PATHINFO_EXTENSION);
125      if ('zip' == strtolower($extension))
126      {
127        $upload_dir = PHPWG_ROOT_PATH.'upload/buffer';
128        prepare_directory($upload_dir);
129       
130        $temporary_archive_name = date('YmdHis').'-'.generate_key(10);
131        $archive_path = $upload_dir.'/'.$temporary_archive_name.'.zip';
132       
133        move_uploaded_file(
134          $_FILES['image_upload']['tmp_name'][$idx],
135          $archive_path
136          );
137
138        define('PCLZIP_TEMPORARY_DIR', $upload_dir.'/');
139        include(UPLOAD_FORM_PATH.'include/pclzip.lib.php');
140        $zip = new PclZip($archive_path);
141        if ($list = $zip->listContent())
142        {
143          $indexes_to_extract = array();
144         
145          foreach ($list as $node)
146          {
147            if (1 == $node['folder'])
148            {
149              continue;
150            }
151
152            if (is_valid_image_extension(pathinfo($node['filename'], PATHINFO_EXTENSION)))
153            {
154              array_push($indexes_to_extract, $node['index']);
155             
156              array_push(
157                $images_to_add,
158                array(
159                  'source_filepath' => $upload_dir.'/'.$temporary_archive_name.'/'.$node['filename'],
160                  'original_filename' => basename($node['filename']),
161                  )
162                );
163            }
164          }
165     
166          if (count($indexes_to_extract) > 0)
167          {
168            $zip->extract(
169              PCLZIP_OPT_PATH, $upload_dir.'/'.$temporary_archive_name,
170              PCLZIP_OPT_BY_INDEX, $indexes_to_extract,
171              PCLZIP_OPT_ADD_TEMP_FILE_ON
172              );
173          }
174        }
175      }
176      elseif (is_valid_image_extension($extension))
177      {
178        array_push(
179          $images_to_add,
180          array(
181            'source_filepath' => $_FILES['image_upload']['tmp_name'][$idx],
182            'original_filename' => $_FILES['image_upload']['name'][$idx],
183            )
184          );
185      }
186
187      foreach ($images_to_add as $image_to_add)
188      {
189        $image_id = add_uploaded_file(
190          $image_to_add['source_filepath'],
191          $image_to_add['original_filename'],
192          array($category_id),
193          $_POST['level']
194          );
195
196        array_push($image_ids, $image_id);
197
198        // TODO: if $image_id is not an integer, something went wrong
199
200        // we could return the list of properties from the add_uploaded_file
201        // function, but I like the "double check". And it costs nothing
202        // compared to the upload process.
203        $thumbnail = array();
204     
205        $query = '
206SELECT
207    file,
208    path,
209    tn_ext
210  FROM '.IMAGES_TABLE.'
211  WHERE id = '.$image_id.'
212;';
213        $image_infos = mysql_fetch_assoc(pwg_query($query));
214
215        $thumbnail['file'] = $image_infos['file'];
216     
217        $thumbnail['src'] = get_thumbnail_location(
218          array(
219            'path' => $image_infos['path'],
220            'tn_ext' => $image_infos['tn_ext'],
221            )
222          );
223
224        // TODO: when implementing this plugin in Piwigo core, we should have
225        // a function get_image_name($name, $file) (if name is null, then
226        // compute a temporary name from filename) that would be also used in
227        // picture.php. UPDATE: in fact, "get_name_from_file($file)" already
228        // exists and is used twice (element_set_unit + comments, but not in
229        // picture.php I don't know why) with the same pattern if
230        // (empty($name)) {$name = get_name_from_file($file)}, a clean
231        // function get_image_name($name, $file) would be better
232        $thumbnail['title'] = get_name_from_file($image_infos['file']);
233
234        $thumbnail['link'] = PHPWG_ROOT_PATH.'admin.php?page=picture_modify'
235          .'&amp;image_id='.$image_id
236          .'&amp;cat_id='.$category_id
237          ;
238
239        array_push($page['thumbnails'], $thumbnail);
240      }
241    }
242  }
243 
244  $endtime = get_moment();
245  $elapsed = ($endtime - $starttime) * 1000;
246  // printf('%.2f ms', $elapsed);
247
248  if (!empty($page['thumbnails']))
249  {
250    array_push(
251      $page['infos'],
252      sprintf(
253        l10n('%d photos uploaded'),
254        count($page['thumbnails'])
255        )
256      );
257   
258    if (0 != $_POST['level'])
259    {
260      array_push(
261        $page['infos'],
262        sprintf(
263          l10n('Privacy level set to "%s"'),
264          l10n(
265            sprintf('Level %d', $_POST['level'])
266            )
267          )
268        );
269    }
270
271    if ('existing' == $_POST['category_type'])
272    {
273      $query = '
274SELECT
275    COUNT(*)
276  FROM '.IMAGE_CATEGORY_TABLE.'
277  WHERE category_id = '.$category_id.'
278;';
279      list($count) = mysql_fetch_row(pwg_query($query));
280      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
281     
282      // information
283      array_push(
284        $page['infos'],
285        sprintf(
286          l10n('Category "%s" now contains %d photos'),
287          '<em>'.$category_name.'</em>',
288          $count
289          )
290        );
291    }
292
293    $page['batch_link'] = $admin_base_url.'&batch='.implode(',', $image_ids);
294  }
295}
296
297// +-----------------------------------------------------------------------+
298// |                             template init                             |
299// +-----------------------------------------------------------------------+
300
301$template->set_filenames(
302  array(
303    'plugin_admin_content' => dirname(__FILE__).'/upload.tpl'
304    )
305  );
306
307$template->assign(
308    array(
309      'F_ADD_ACTION'=> $admin_base_url,
310      'plugin_path' => UPLOAD_FORM_PATH,
311    )
312  );
313
314if (isset($page['thumbnails']))
315{
316  $template->assign(
317    array(
318      'thumbnails' => $page['thumbnails'],
319      )
320    );
321
322  // only display the batch link if we have more than 1 photo
323  if (count($page['thumbnails']) > 1)
324  {
325    $template->assign(
326      array(
327        'batch_link' => $page['batch_link'],
328        'batch_label' => sprintf(
329          l10n('Manage this set of %d photos'),
330          count($page['thumbnails'])
331          ),
332        )
333      );
334  }
335}
336
337$query = '
338SELECT id,name,uppercats,global_rank
339  FROM '.CATEGORIES_TABLE.'
340;';
341
342display_select_cat_wrapper(
343  $query,
344  array(),
345  'category_options'
346  );
347
348// image level options
349$tpl_options = array();
350foreach ($conf['available_permission_levels'] as $level)
351{
352  $tpl_options[$level] = l10n( sprintf('Level %d', $level) );
353}
354$selected_level = isset($_POST['level']) ? $_POST['level'] : 0;
355$template->assign(
356    array(
357      'level_options'=> $tpl_options,
358      'level_options_selected' => array($selected_level)
359    )
360  );
361
362// +-----------------------------------------------------------------------+
363// |                             setup errors                              |
364// +-----------------------------------------------------------------------+
365
366$setup_errors = array();
367
368$upload_base_dir = 'upload';
369$upload_dir = PHPWG_ROOT_PATH.$upload_base_dir;
370
371if (!is_dir($upload_dir))
372{
373  if (!is_writable(PHPWG_ROOT_PATH))
374  {
375    array_push(
376      $setup_errors,
377      sprintf(
378        l10n('Create the "%s" directory at the root of your Piwigo installation'),
379        $upload_base_dir
380        )
381      );
382  }
383}
384else
385{
386  if (!is_writable($upload_dir))
387  {
388    @chmod($upload_dir, 0777);
389
390    if (!is_writable($upload_dir))
391    {
392      array_push(
393        $setup_errors,
394        sprintf(
395          l10n('Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation'),
396          $upload_base_dir
397          )
398        );
399    }
400  }
401}
402
403$template->assign(
404    array(
405      'setup_errors'=> $setup_errors,
406    )
407  );
408
409// +-----------------------------------------------------------------------+
410// |                           sending html code                           |
411// +-----------------------------------------------------------------------+
412
413$template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
414?>
Note: See TracBrowser for help on using the repository browser.