source: trunk/admin/photos_add_direct.php @ 8728

Revision 8728, 15.5 KB checked in by plg, 9 years ago (diff)

Happy new year 2011

Change "Piwigo - a PHP based picture gallery" into "Piwigo - a PHP based photo gallery"

Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo 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=batch_manager&cat=caddie');
59}
60
61// +-----------------------------------------------------------------------+
62// |                             process form                              |
63// +-----------------------------------------------------------------------+
64
65if (isset($_GET['processed']))
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  // sometimes, you have submitted the form but you have nothing in $_POST
73  // and $_FILES. This may happen when you have an HTML upload and you
74  // exceeded the post_max_size (but not the upload_max_size)
75  if (!isset($_POST['submit_upload']))
76  {
77    array_push(
78      $page['errors'],
79      sprintf(
80        l10n('The uploaded files exceed the post_max_size directive in php.ini: %sB'),
81        ini_get('post_max_size')
82        )
83      );
84  }
85 
86  $category_id = null;
87  if (!isset($_POST['category_type']))
88  {
89    // nothing to do, we certainly have the post_max_size issue
90  }
91  elseif ('existing' == $_POST['category_type'])
92  {
93    $category_id = $_POST['category'];
94  }
95  elseif ('new' == $_POST['category_type'])
96  {
97    $output_create = create_virtual_category(
98      $_POST['category_name'],
99      (0 == $_POST['category_parent'] ? null : $_POST['category_parent'])
100      );
101   
102    $category_id = $output_create['id'];
103
104    if (isset($output_create['error']))
105    {
106      array_push($page['errors'], $output_create['error']);
107    }
108    else
109    {
110      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
111      // information
112      array_push(
113        $page['infos'],
114        sprintf(
115          l10n('Album "%s" has been added'),
116          '<em>'.$category_name.'</em>'
117          )
118        );
119      // TODO: add the onclick="window.open(this.href); return false;"
120      // attribute with jQuery on upload.tpl side for href containing
121      // "cat_modify"
122    }
123  }
124
125  $image_ids = array();
126       
127  if (isset($_FILES) and !empty($_FILES['image_upload']))
128  {
129    $starttime = get_moment();
130
131  foreach ($_FILES['image_upload']['error'] as $idx => $error)
132  {
133    if (UPLOAD_ERR_OK == $error)
134    {
135      $images_to_add = array();
136     
137      $extension = pathinfo($_FILES['image_upload']['name'][$idx], PATHINFO_EXTENSION);
138      if ('zip' == strtolower($extension))
139      {
140        $upload_dir = $conf['upload_dir'].'/buffer';
141        prepare_directory($upload_dir);
142       
143        $temporary_archive_name = date('YmdHis').'-'.generate_key(10);
144        $archive_path = $upload_dir.'/'.$temporary_archive_name.'.zip';
145       
146        move_uploaded_file(
147          $_FILES['image_upload']['tmp_name'][$idx],
148          $archive_path
149          );
150
151        define('PCLZIP_TEMPORARY_DIR', $upload_dir.'/');
152        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
153        $zip = new PclZip($archive_path);
154        if ($list = $zip->listContent())
155        {
156          $indexes_to_extract = array();
157         
158          foreach ($list as $node)
159          {
160            if (1 == $node['folder'])
161            {
162              continue;
163            }
164
165            if (is_valid_image_extension(pathinfo($node['filename'], PATHINFO_EXTENSION)))
166            {
167              array_push($indexes_to_extract, $node['index']);
168             
169              array_push(
170                $images_to_add,
171                array(
172                  'source_filepath' => $upload_dir.'/'.$temporary_archive_name.'/'.$node['filename'],
173                  'original_filename' => basename($node['filename']),
174                  )
175                );
176            }
177          }
178     
179          if (count($indexes_to_extract) > 0)
180          {
181            $zip->extract(
182              PCLZIP_OPT_PATH, $upload_dir.'/'.$temporary_archive_name,
183              PCLZIP_OPT_BY_INDEX, $indexes_to_extract,
184              PCLZIP_OPT_ADD_TEMP_FILE_ON
185              );
186          }
187        }
188      }
189      elseif (is_valid_image_extension($extension))
190      {
191        array_push(
192          $images_to_add,
193          array(
194            'source_filepath' => $_FILES['image_upload']['tmp_name'][$idx],
195            'original_filename' => $_FILES['image_upload']['name'][$idx],
196            )
197          );
198      }
199
200      foreach ($images_to_add as $image_to_add)
201      {
202        $image_id = add_uploaded_file(
203          $image_to_add['source_filepath'],
204          $image_to_add['original_filename'],
205          array($category_id),
206          $_POST['level']
207          );
208
209        array_push($image_ids, $image_id);
210
211        // TODO: if $image_id is not an integer, something went wrong
212      }
213    }
214    else
215    {
216      $error_message = file_upload_error_message($error);
217     
218      array_push(
219        $page['errors'],
220        sprintf(
221          l10n('Error on file "%s" : %s'),
222          $_FILES['image_upload']['name'][$idx],
223          $error_message
224          )
225        );
226    }
227  }
228 
229  $endtime = get_moment();
230  $elapsed = ($endtime - $starttime) * 1000;
231  // printf('%.2f ms', $elapsed);
232
233  } // if (!empty($_FILES))
234
235  if (isset($_POST['upload_id']))
236  {
237    // we're on a multiple upload, with uploadify and so on
238    if (isset($_SESSION['uploads_error'][ $_POST['upload_id'] ]))
239    {
240      foreach ($_SESSION['uploads_error'][ $_POST['upload_id'] ] as $error)
241      {
242        array_push($page['errors'], $error);
243      }
244    }
245
246    if (isset($_SESSION['uploads'][ $_POST['upload_id'] ]))
247    {
248      $image_ids = $_SESSION['uploads'][ $_POST['upload_id'] ];
249
250      associate_images_to_categories(
251        $image_ids,
252        array($category_id)
253        );
254
255      $query = '
256UPDATE '.IMAGES_TABLE.'
257  SET level = '.$_POST['level'].'
258  WHERE id IN ('.implode(', ', $image_ids).')
259;';
260      pwg_query($query);
261   
262      invalidate_user_cache();
263    }
264  }
265 
266  $page['thumbnails'] = array();
267  foreach ($image_ids as $image_id)
268  {
269    // we could return the list of properties from the add_uploaded_file
270    // function, but I like the "double check". And it costs nothing
271    // compared to the upload process.
272    $thumbnail = array();
273     
274    $query = '
275SELECT
276    file,
277    path,
278    tn_ext
279  FROM '.IMAGES_TABLE.'
280  WHERE id = '.$image_id.'
281;';
282    $image_infos = pwg_db_fetch_assoc(pwg_query($query));
283
284    $thumbnail['file'] = $image_infos['file'];
285   
286    $thumbnail['src'] = get_thumbnail_location(
287      array(
288        'path' => $image_infos['path'],
289        'tn_ext' => $image_infos['tn_ext'],
290        )
291      );
292
293    // TODO: when implementing this plugin in Piwigo core, we should have
294    // a function get_image_name($name, $file) (if name is null, then
295    // compute a temporary name from filename) that would be also used in
296    // picture.php. UPDATE: in fact, "get_name_from_file($file)" already
297    // exists and is used twice (batch_manager_unit + comments, but not in
298    // picture.php I don't know why) with the same pattern if
299    // (empty($name)) {$name = get_name_from_file($file)}, a clean
300    // function get_image_name($name, $file) would be better
301    $thumbnail['title'] = get_name_from_file($image_infos['file']);
302
303    $thumbnail['link'] = PHPWG_ROOT_PATH.'admin.php?page=picture_modify'
304      .'&amp;image_id='.$image_id
305      .'&amp;cat_id='.$category_id
306      ;
307
308    array_push($page['thumbnails'], $thumbnail);
309  }
310 
311  if (!empty($page['thumbnails']))
312  {
313    array_push(
314      $page['infos'],
315      sprintf(
316        l10n('%d photos uploaded'),
317        count($page['thumbnails'])
318        )
319      );
320   
321    if (0 != $_POST['level'])
322    {
323      array_push(
324        $page['infos'],
325        sprintf(
326          l10n('Privacy level set to "%s"'),
327          l10n(
328            sprintf('Level %d', $_POST['level'])
329            )
330          )
331        );
332    }
333
334    if ('existing' == $_POST['category_type'])
335    {
336      $query = '
337SELECT
338    COUNT(*)
339  FROM '.IMAGE_CATEGORY_TABLE.'
340  WHERE category_id = '.$category_id.'
341;';
342      list($count) = pwg_db_fetch_row(pwg_query($query));
343      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
344     
345      // information
346      array_push(
347        $page['infos'],
348        sprintf(
349          l10n('Album "%s" now contains %d photos'),
350          '<em>'.$category_name.'</em>',
351          $count
352          )
353        );
354    }
355
356    $page['batch_link'] = PHOTOS_ADD_BASE_URL.'&batch='.implode(',', $image_ids);
357  }
358}
359
360// +-----------------------------------------------------------------------+
361// |                             template init                             |
362// +-----------------------------------------------------------------------+
363
364$uploadify_path = PHPWG_ROOT_PATH.'admin/include/uploadify';
365
366$template->assign(
367    array(
368      'F_ADD_ACTION'=> PHOTOS_ADD_BASE_URL,
369      'uploadify_path' => $uploadify_path,
370      'upload_max_filesize' => min(
371        get_ini_size('upload_max_filesize'),
372        get_ini_size('post_max_size')
373        ),
374    )
375  );
376
377$upload_modes = array('html', 'multiple');
378$upload_mode = isset($conf['upload_mode']) ? $conf['upload_mode'] : 'multiple';
379
380if (isset($_GET['upload_mode']) and in_array($_GET['upload_mode'], $upload_modes))
381{
382  $upload_mode = $_GET['upload_mode'];
383  conf_update_param('upload_mode', $upload_mode);
384}
385
386// what is the upload switch mode
387$index_of_upload_mode = array_flip($upload_modes);
388$upload_mode_index = $index_of_upload_mode[$upload_mode];
389$upload_switch = $upload_modes[ ($upload_mode_index + 1) % 2 ];
390
391$template->assign(
392    array(
393      'upload_mode' => $upload_mode,
394      'form_action' => PHOTOS_ADD_BASE_URL.'&amp;upload_mode='.$upload_mode.'&amp;processed=1',
395      'switch_url' => PHOTOS_ADD_BASE_URL.'&amp;upload_mode='.$upload_switch,
396      'upload_id' => md5(rand()),
397      'session_id' => session_id(),
398      'pwg_token' => get_pwg_token(),
399      'another_upload_link' => PHOTOS_ADD_BASE_URL.'&amp;upload_mode='.$upload_mode,
400    )
401  );
402
403$template->append(
404  'head_elements',
405  '<link rel="stylesheet" type="text/css" href="'.$uploadify_path.'/uploadify.css">'."\n"
406  );
407
408if (isset($page['thumbnails']))
409{
410  $template->assign(
411    array(
412      'thumbnails' => $page['thumbnails'],
413      )
414    );
415
416  // only display the batch link if we have more than 1 photo
417  if (count($page['thumbnails']) > 1)
418  {
419    $template->assign(
420      array(
421        'batch_link' => $page['batch_link'],
422        'batch_label' => sprintf(
423          l10n('Manage this set of %d photos'),
424          count($page['thumbnails'])
425          ),
426        )
427      );
428  }
429}
430
431// categories
432//
433// we need to know the category in which the last photo was added
434$selected_category = array();
435$selected_parent = array();
436
437$query = '
438SELECT
439    category_id,
440    id_uppercat
441  FROM '.IMAGES_TABLE.' AS i
442    JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON image_id = i.id
443    JOIN '.CATEGORIES_TABLE.' AS c ON category_id = c.id
444  ORDER BY i.id DESC
445  LIMIT 1
446;';
447$result = pwg_query($query);
448if (pwg_db_num_rows($result) > 0)
449{
450  $row = pwg_db_fetch_assoc($result);
451 
452  $selected_category = array($row['category_id']);
453
454  if (!empty($row['id_uppercat']))
455  {
456    $selected_parent = array($row['id_uppercat']);
457  }
458}
459
460// existing album
461$query = '
462SELECT id,name,uppercats,global_rank
463  FROM '.CATEGORIES_TABLE.'
464;';
465
466display_select_cat_wrapper(
467  $query,
468  $selected_category,
469  'category_options'
470  );
471
472// new category
473display_select_cat_wrapper(
474  $query,
475  $selected_parent,
476  'category_parent_options'
477  );
478
479
480// image level options
481$selected_level = isset($_POST['level']) ? $_POST['level'] : 0;
482$template->assign(
483    array(
484      'level_options'=> get_privacy_level_options(),
485      'level_options_selected' => array($selected_level)
486    )
487  );
488
489// +-----------------------------------------------------------------------+
490// |                         setup errors/warnings                         |
491// +-----------------------------------------------------------------------+
492
493// Errors
494$setup_errors = array();
495
496$error_message = ready_for_upload_message();
497if (!empty($error_message))
498{
499  array_push($setup_errors, $error_message);
500}
501
502if (!function_exists('gd_info'))
503{
504  array_push($setup_errors, l10n('GD library is missing'));
505}
506
507$template->assign(
508  array(
509    'setup_errors'=> $setup_errors,
510    )
511  );
512
513// Warnings
514if (isset($_GET['hide_warnings']))
515{
516  $_SESSION['upload_hide_warnings'] = true;
517}
518
519if (!isset($_SESSION['upload_hide_warnings']))
520{
521  $setup_warnings = array();
522 
523  if ($conf['use_exif'] and !function_exists('read_exif_data'))
524  {
525    array_push(
526      $setup_warnings,
527      l10n('Exif extension not available, admin should disable exif use')
528      );
529  }
530
531  if (get_ini_size('upload_max_filesize') > get_ini_size('post_max_size'))
532  {
533    array_push(
534      $setup_warnings,
535      sprintf(
536        l10n('In your php.ini file, the upload_max_filesize (%sB) is bigger than post_max_size (%sB), you should change this setting'),
537        get_ini_size('upload_max_filesize', false),
538        get_ini_size('post_max_size', false)
539        )
540      );
541  }
542
543  $template->assign(
544    array(
545      'setup_warnings' => $setup_warnings,
546      'hide_warnings_link' => PHOTOS_ADD_BASE_URL.'&amp;upload_mode='.$upload_mode.'&amp;hide_warnings=1'
547      )
548    );
549}
550
551// +-----------------------------------------------------------------------+
552// |                           sending html code                           |
553// +-----------------------------------------------------------------------+
554
555$template->assign_var_from_handle('ADMIN_CONTENT', 'photos_add');
556?>
Note: See TracBrowser for help on using the repository browser.