source: trunk/admin/photos_add_direct.php @ 6323

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

bug 1639 fixed: the upload form now correctly uses the $confupload_dir
parameter (web API already use it).

By default, the $confupload_dir is no longer dependent to PHPWG_ROOT_PATH
because it becomes a real mess when admin/include/uploadify.php (called
directly, not from an include) tries to perform an upload.

Improvement: make clearer how $confupload_dir can be set (relative to the
Piwigo installation directory + HTTP reachable)

File size: 13.1 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('PHOTOS_ADD_BASE_URL'))
23{
24  die ("Hacking attempt!");
25}
26
27// +-----------------------------------------------------------------------+
28// |                        batch management request                       |
29// +-----------------------------------------------------------------------+
30
31if (isset($_GET['batch']))
32{
33  check_input_parameter('batch', $_GET, false, '/^\d+(,\d+)*$/');
34
35  $query = '
36DELETE FROM '.CADDIE_TABLE.'
37  WHERE user_id = '.$user['id'].'
38;';
39  pwg_query($query);
40
41  $inserts = array();
42  foreach (explode(',', $_GET['batch']) as $image_id)
43  {
44    array_push(
45      $inserts,
46      array(
47        'user_id' => $user['id'],
48        'element_id' => $image_id,
49        )
50      );
51  }
52  mass_inserts(
53    CADDIE_TABLE,
54    array_keys($inserts[0]),
55    $inserts
56    );
57
58  redirect(get_root_url().'admin.php?page=element_set&cat=caddie');
59}
60
61// +-----------------------------------------------------------------------+
62// |                             process form                              |
63// +-----------------------------------------------------------------------+
64
65if (isset($_POST['submit_upload']))
66{
67//   echo '<pre>POST'."\n"; print_r($_POST); echo '</pre>';
68//   echo '<pre>FILES'."\n"; print_r($_FILES); echo '</pre>';
69//   echo '<pre>SESSION'."\n"; print_r($_SESSION); echo '</pre>';
70//   exit();
71 
72  $category_id = null;
73  if ('existing' == $_POST['category_type'])
74  {
75    $category_id = $_POST['category'];
76  }
77  elseif ('new' == $_POST['category_type'])
78  {
79    $output_create = create_virtual_category(
80      $_POST['category_name'],
81      (0 == $_POST['category_parent'] ? null : $_POST['category_parent'])
82      );
83   
84    $category_id = $output_create['id'];
85
86    if (isset($output_create['error']))
87    {
88      array_push($page['errors'], $output_create['error']);
89    }
90    else
91    {
92      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
93      // information
94      array_push(
95        $page['infos'],
96        sprintf(
97          l10n('Category "%s" has been added'),
98          '<em>'.$category_name.'</em>'
99          )
100        );
101      // TODO: add the onclick="window.open(this.href); return false;"
102      // attribute with jQuery on upload.tpl side for href containing
103      // "cat_modify"
104    }
105  }
106
107  $image_ids = array();
108       
109  if (isset($_FILES) and !empty($_FILES['image_upload']))
110  {
111    $starttime = get_moment();
112
113  foreach ($_FILES['image_upload']['error'] as $idx => $error)
114  {
115    if (UPLOAD_ERR_OK == $error)
116    {
117      $images_to_add = array();
118     
119      $extension = pathinfo($_FILES['image_upload']['name'][$idx], PATHINFO_EXTENSION);
120      if ('zip' == strtolower($extension))
121      {
122        $upload_dir = $conf['upload_dir'].'/buffer';
123        prepare_directory($upload_dir);
124       
125        $temporary_archive_name = date('YmdHis').'-'.generate_key(10);
126        $archive_path = $upload_dir.'/'.$temporary_archive_name.'.zip';
127       
128        move_uploaded_file(
129          $_FILES['image_upload']['tmp_name'][$idx],
130          $archive_path
131          );
132
133        define('PCLZIP_TEMPORARY_DIR', $upload_dir.'/');
134        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
135        $zip = new PclZip($archive_path);
136        if ($list = $zip->listContent())
137        {
138          $indexes_to_extract = array();
139         
140          foreach ($list as $node)
141          {
142            if (1 == $node['folder'])
143            {
144              continue;
145            }
146
147            if (is_valid_image_extension(pathinfo($node['filename'], PATHINFO_EXTENSION)))
148            {
149              array_push($indexes_to_extract, $node['index']);
150             
151              array_push(
152                $images_to_add,
153                array(
154                  'source_filepath' => $upload_dir.'/'.$temporary_archive_name.'/'.$node['filename'],
155                  'original_filename' => basename($node['filename']),
156                  )
157                );
158            }
159          }
160     
161          if (count($indexes_to_extract) > 0)
162          {
163            $zip->extract(
164              PCLZIP_OPT_PATH, $upload_dir.'/'.$temporary_archive_name,
165              PCLZIP_OPT_BY_INDEX, $indexes_to_extract,
166              PCLZIP_OPT_ADD_TEMP_FILE_ON
167              );
168          }
169        }
170      }
171      elseif (is_valid_image_extension($extension))
172      {
173        array_push(
174          $images_to_add,
175          array(
176            'source_filepath' => $_FILES['image_upload']['tmp_name'][$idx],
177            'original_filename' => $_FILES['image_upload']['name'][$idx],
178            )
179          );
180      }
181
182      foreach ($images_to_add as $image_to_add)
183      {
184        $image_id = add_uploaded_file(
185          $image_to_add['source_filepath'],
186          $image_to_add['original_filename'],
187          array($category_id),
188          $_POST['level']
189          );
190
191        array_push($image_ids, $image_id);
192
193        // TODO: if $image_id is not an integer, something went wrong
194      }
195    }
196  }
197 
198  $endtime = get_moment();
199  $elapsed = ($endtime - $starttime) * 1000;
200  // printf('%.2f ms', $elapsed);
201
202  } // if (!empty($_FILES))
203
204  if (isset($_POST['upload_id']))
205  {
206    // we're on a multiple upload, with uploadify and so on
207    $image_ids = $_SESSION['uploads'][ $_POST['upload_id'] ];
208
209    associate_images_to_categories(
210      $image_ids,
211      array($category_id)
212      );
213
214    $query = '
215UPDATE '.IMAGES_TABLE.'
216  SET level = '.$_POST['level'].'
217  WHERE id IN ('.implode(', ', $image_ids).')
218;';
219    pwg_query($query);
220   
221    invalidate_user_cache();
222  }
223 
224  $page['thumbnails'] = array();
225  foreach ($image_ids as $image_id)
226  {
227    // we could return the list of properties from the add_uploaded_file
228    // function, but I like the "double check". And it costs nothing
229    // compared to the upload process.
230    $thumbnail = array();
231     
232    $query = '
233SELECT
234    file,
235    path,
236    tn_ext
237  FROM '.IMAGES_TABLE.'
238  WHERE id = '.$image_id.'
239;';
240    $image_infos = mysql_fetch_assoc(pwg_query($query));
241
242    $thumbnail['file'] = $image_infos['file'];
243   
244    $thumbnail['src'] = get_thumbnail_location(
245      array(
246        'path' => $image_infos['path'],
247        'tn_ext' => $image_infos['tn_ext'],
248        )
249      );
250
251    // TODO: when implementing this plugin in Piwigo core, we should have
252    // a function get_image_name($name, $file) (if name is null, then
253    // compute a temporary name from filename) that would be also used in
254    // picture.php. UPDATE: in fact, "get_name_from_file($file)" already
255    // exists and is used twice (element_set_unit + comments, but not in
256    // picture.php I don't know why) with the same pattern if
257    // (empty($name)) {$name = get_name_from_file($file)}, a clean
258    // function get_image_name($name, $file) would be better
259    $thumbnail['title'] = get_name_from_file($image_infos['file']);
260
261    $thumbnail['link'] = PHPWG_ROOT_PATH.'admin.php?page=picture_modify'
262      .'&amp;image_id='.$image_id
263      .'&amp;cat_id='.$category_id
264      ;
265
266    array_push($page['thumbnails'], $thumbnail);
267  }
268 
269  if (!empty($page['thumbnails']))
270  {
271    array_push(
272      $page['infos'],
273      sprintf(
274        l10n('%d photos uploaded'),
275        count($page['thumbnails'])
276        )
277      );
278   
279    if (0 != $_POST['level'])
280    {
281      array_push(
282        $page['infos'],
283        sprintf(
284          l10n('Privacy level set to "%s"'),
285          l10n(
286            sprintf('Level %d', $_POST['level'])
287            )
288          )
289        );
290    }
291
292    if ('existing' == $_POST['category_type'])
293    {
294      $query = '
295SELECT
296    COUNT(*)
297  FROM '.IMAGE_CATEGORY_TABLE.'
298  WHERE category_id = '.$category_id.'
299;';
300      list($count) = mysql_fetch_row(pwg_query($query));
301      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
302     
303      // information
304      array_push(
305        $page['infos'],
306        sprintf(
307          l10n('Category "%s" now contains %d photos'),
308          '<em>'.$category_name.'</em>',
309          $count
310          )
311        );
312    }
313
314    $page['batch_link'] = PHOTOS_ADD_BASE_URL.'&batch='.implode(',', $image_ids);
315  }
316}
317
318// +-----------------------------------------------------------------------+
319// |                             template init                             |
320// +-----------------------------------------------------------------------+
321
322$uploadify_path = PHPWG_ROOT_PATH.'admin/include/uploadify';
323
324$template->assign(
325    array(
326      'F_ADD_ACTION'=> PHOTOS_ADD_BASE_URL,
327      'uploadify_path' => $uploadify_path,
328    )
329  );
330
331$upload_modes = array('html', 'multiple');
332$upload_mode = isset($conf['upload_mode']) ? $conf['upload_mode'] : 'multiple';
333
334if (isset($_GET['upload_mode']) and in_array($_GET['upload_mode'], $upload_modes))
335{
336  $upload_mode = $_GET['upload_mode'];
337  conf_update_param('upload_mode', $upload_mode);
338}
339
340// what is the upload switch mode
341$index_of_upload_mode = array_flip($upload_modes);
342$upload_mode_index = $index_of_upload_mode[$upload_mode];
343$upload_switch = $upload_modes[ ($upload_mode_index + 1) % 2 ];
344
345$template->assign(
346    array(
347      'upload_mode' => $upload_mode,
348      'switch_url' => PHOTOS_ADD_BASE_URL.'&amp;upload_mode='.$upload_switch,
349      'upload_id' => md5(rand()),
350      'session_id' => session_id(),
351      'pwg_token' => get_pwg_token(),
352    )
353  );
354
355$template->append(
356  'head_elements',
357  '<link rel="stylesheet" type="text/css" href="'.$uploadify_path.'/uploadify.css">'."\n"
358  );
359
360if (isset($page['thumbnails']))
361{
362  $template->assign(
363    array(
364      'thumbnails' => $page['thumbnails'],
365      )
366    );
367
368  // only display the batch link if we have more than 1 photo
369  if (count($page['thumbnails']) > 1)
370  {
371    $template->assign(
372      array(
373        'batch_link' => $page['batch_link'],
374        'batch_label' => sprintf(
375          l10n('Manage this set of %d photos'),
376          count($page['thumbnails'])
377          ),
378        )
379      );
380  }
381}
382
383// categories
384//
385// we need to know the category in which the last photo was added
386$selected_category = array();
387$selected_parent = array();
388
389$query = '
390SELECT
391    category_id,
392    id_uppercat
393  FROM '.IMAGES_TABLE.' AS i
394    JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON image_id = i.id
395    JOIN '.CATEGORIES_TABLE.' AS c ON category_id = c.id
396  ORDER BY i.id DESC
397  LIMIT 1
398;';
399$result = pwg_query($query);
400if (pwg_db_num_rows($result) > 0)
401{
402  $row = pwg_db_fetch_assoc($result);
403 
404  $selected_category = array($row['category_id']);
405
406  if (!empty($row['id_uppercat']))
407  {
408    $selected_parent = array($row['id_uppercat']);
409  }
410}
411
412// existing category
413$query = '
414SELECT id,name,uppercats,global_rank
415  FROM '.CATEGORIES_TABLE.'
416;';
417
418display_select_cat_wrapper(
419  $query,
420  $selected_category,
421  'category_options'
422  );
423
424// new category
425display_select_cat_wrapper(
426  $query,
427  $selected_parent,
428  'category_parent_options'
429  );
430
431
432// image level options
433$selected_level = isset($_POST['level']) ? $_POST['level'] : 0;
434$template->assign(
435    array(
436      'level_options'=> get_privacy_level_options(),
437      'level_options_selected' => array($selected_level)
438    )
439  );
440
441// +-----------------------------------------------------------------------+
442// |                             setup errors                              |
443// +-----------------------------------------------------------------------+
444
445$setup_errors = array();
446
447$error_message = ready_for_upload_message();
448if (!empty($error_message))
449{
450  array_push($setup_errors, $error_message);
451}
452
453$template->assign(
454    array(
455      'setup_errors'=> $setup_errors,
456    )
457  );
458
459// +-----------------------------------------------------------------------+
460// |                           sending html code                           |
461// +-----------------------------------------------------------------------+
462
463$template->assign_var_from_handle('ADMIN_CONTENT', 'photos_add');
464?>
Note: See TracBrowser for help on using the repository browser.