source: extensions/upload_form/upload.php @ 4895

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

feature 1438: switch between uploadify and HTML form

feature 1435 related: change the order to display the "who can see these
photos?" options. It's just a test, we're discussing about usability on this
field.

graphical design: distinguish the 3 main fields (category/privacy/files), no
use of the table anymore to have a smaller width. One goal was to see the
"Upload" button when the form opens for the first time in a 1024x768 browser.

File size: 13.9 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//   echo '<pre>POST'."\n"; print_r($_POST); echo '</pre>';
79//   echo '<pre>FILES'."\n"; print_r($_FILES); echo '</pre>';
80//   echo '<pre>SESSION'."\n"; print_r($_SESSION); echo '</pre>';
81//   exit();
82 
83  $category_id = null;
84  if ('existing' == $_POST['category_type'])
85  {
86    $category_id = $_POST['category'];
87  }
88  elseif ('new' == $_POST['category_type'])
89  {
90    $output_create = create_virtual_category(
91      $_POST['category_name'],
92      (0 == $_POST['category_parent'] ? null : $_POST['category_parent'])
93      );
94   
95    $category_id = $output_create['id'];
96
97    if (isset($output_create['error']))
98    {
99      array_push($page['errors'], $output_create['error']);
100    }
101    else
102    {
103      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
104      // information
105      array_push(
106        $page['infos'],
107        sprintf(
108          l10n('Category "%s" has been added'),
109          '<em>'.$category_name.'</em>'
110          )
111        );
112      // TODO: add the onclick="window.open(this.href); return false;"
113      // attribute with jQuery on upload.tpl side for href containing
114      // "cat_modify"
115    }
116  }
117
118  $image_ids = array();
119       
120  if (isset($_FILES) and !empty($_FILES['image_upload']))
121  {
122    $starttime = get_moment();
123
124  foreach ($_FILES['image_upload']['error'] as $idx => $error)
125  {
126    if (UPLOAD_ERR_OK == $error)
127    {
128      $images_to_add = array();
129     
130      $extension = pathinfo($_FILES['image_upload']['name'][$idx], PATHINFO_EXTENSION);
131      if ('zip' == strtolower($extension))
132      {
133        $upload_dir = PHPWG_ROOT_PATH.'upload/buffer';
134        prepare_directory($upload_dir);
135       
136        $temporary_archive_name = date('YmdHis').'-'.generate_key(10);
137        $archive_path = $upload_dir.'/'.$temporary_archive_name.'.zip';
138       
139        move_uploaded_file(
140          $_FILES['image_upload']['tmp_name'][$idx],
141          $archive_path
142          );
143
144        define('PCLZIP_TEMPORARY_DIR', $upload_dir.'/');
145        include(UPLOAD_FORM_PATH.'include/pclzip.lib.php');
146        $zip = new PclZip($archive_path);
147        if ($list = $zip->listContent())
148        {
149          $indexes_to_extract = array();
150         
151          foreach ($list as $node)
152          {
153            if (1 == $node['folder'])
154            {
155              continue;
156            }
157
158            if (is_valid_image_extension(pathinfo($node['filename'], PATHINFO_EXTENSION)))
159            {
160              array_push($indexes_to_extract, $node['index']);
161             
162              array_push(
163                $images_to_add,
164                array(
165                  'source_filepath' => $upload_dir.'/'.$temporary_archive_name.'/'.$node['filename'],
166                  'original_filename' => basename($node['filename']),
167                  )
168                );
169            }
170          }
171     
172          if (count($indexes_to_extract) > 0)
173          {
174            $zip->extract(
175              PCLZIP_OPT_PATH, $upload_dir.'/'.$temporary_archive_name,
176              PCLZIP_OPT_BY_INDEX, $indexes_to_extract,
177              PCLZIP_OPT_ADD_TEMP_FILE_ON
178              );
179          }
180        }
181      }
182      elseif (is_valid_image_extension($extension))
183      {
184        array_push(
185          $images_to_add,
186          array(
187            'source_filepath' => $_FILES['image_upload']['tmp_name'][$idx],
188            'original_filename' => $_FILES['image_upload']['name'][$idx],
189            )
190          );
191      }
192
193      foreach ($images_to_add as $image_to_add)
194      {
195        $image_id = add_uploaded_file(
196          $image_to_add['source_filepath'],
197          $image_to_add['original_filename'],
198          array($category_id),
199          $_POST['level']
200          );
201
202        array_push($image_ids, $image_id);
203
204        // TODO: if $image_id is not an integer, something went wrong
205      }
206    }
207  }
208 
209  $endtime = get_moment();
210  $elapsed = ($endtime - $starttime) * 1000;
211  // printf('%.2f ms', $elapsed);
212
213  } // if (!empty($_FILES))
214
215  if (isset($_POST['upload_id']))
216  {
217    // we're on a multiple upload, with uploadify and so on
218    $image_ids = $_SESSION['uploads'][ $_POST['upload_id'] ];
219
220    associate_images_to_categories(
221      $image_ids,
222      array($category_id)
223      );
224
225    $query = '
226UPDATE '.IMAGES_TABLE.'
227  SET level = '.$_POST['level'].'
228  WHERE id IN ('.implode(', ', $image_ids).')
229;';
230    pwg_query($query);
231   
232    invalidate_user_cache();
233  }
234 
235  $page['thumbnails'] = array();
236  foreach ($image_ids as $image_id)
237  {
238    // we could return the list of properties from the add_uploaded_file
239    // function, but I like the "double check". And it costs nothing
240    // compared to the upload process.
241    $thumbnail = array();
242     
243    $query = '
244SELECT
245    file,
246    path,
247    tn_ext
248  FROM '.IMAGES_TABLE.'
249  WHERE id = '.$image_id.'
250;';
251    $image_infos = mysql_fetch_assoc(pwg_query($query));
252
253    $thumbnail['file'] = $image_infos['file'];
254   
255    $thumbnail['src'] = get_thumbnail_location(
256      array(
257        'path' => $image_infos['path'],
258        'tn_ext' => $image_infos['tn_ext'],
259        )
260      );
261
262    // TODO: when implementing this plugin in Piwigo core, we should have
263    // a function get_image_name($name, $file) (if name is null, then
264    // compute a temporary name from filename) that would be also used in
265    // picture.php. UPDATE: in fact, "get_name_from_file($file)" already
266    // exists and is used twice (element_set_unit + comments, but not in
267    // picture.php I don't know why) with the same pattern if
268    // (empty($name)) {$name = get_name_from_file($file)}, a clean
269    // function get_image_name($name, $file) would be better
270    $thumbnail['title'] = get_name_from_file($image_infos['file']);
271
272    $thumbnail['link'] = PHPWG_ROOT_PATH.'admin.php?page=picture_modify'
273      .'&amp;image_id='.$image_id
274      .'&amp;cat_id='.$category_id
275      ;
276
277    array_push($page['thumbnails'], $thumbnail);
278  }
279 
280  if (!empty($page['thumbnails']))
281  {
282    array_push(
283      $page['infos'],
284      sprintf(
285        l10n('%d photos uploaded'),
286        count($page['thumbnails'])
287        )
288      );
289   
290    if (0 != $_POST['level'])
291    {
292      array_push(
293        $page['infos'],
294        sprintf(
295          l10n('Privacy level set to "%s"'),
296          l10n(
297            sprintf('Level %d', $_POST['level'])
298            )
299          )
300        );
301    }
302
303    if ('existing' == $_POST['category_type'])
304    {
305      $query = '
306SELECT
307    COUNT(*)
308  FROM '.IMAGE_CATEGORY_TABLE.'
309  WHERE category_id = '.$category_id.'
310;';
311      list($count) = mysql_fetch_row(pwg_query($query));
312      $category_name = get_cat_display_name_from_id($category_id, 'admin.php?page=cat_modify&amp;cat_id=');
313     
314      // information
315      array_push(
316        $page['infos'],
317        sprintf(
318          l10n('Category "%s" now contains %d photos'),
319          '<em>'.$category_name.'</em>',
320          $count
321          )
322        );
323    }
324
325    $page['batch_link'] = $admin_base_url.'&batch='.implode(',', $image_ids);
326  }
327}
328
329// +-----------------------------------------------------------------------+
330// |                             template init                             |
331// +-----------------------------------------------------------------------+
332
333$template->set_filenames(
334  array(
335    'plugin_admin_content' => dirname(__FILE__).'/upload.tpl'
336    )
337  );
338
339$template->assign(
340    array(
341      'F_ADD_ACTION'=> $admin_base_url,
342      'plugin_path' => UPLOAD_FORM_PATH,
343    )
344  );
345
346$upload_modes = array('html', 'multiple');
347
348$upload_mode = 'multiple';
349$upload_switch = 'html';
350if (isset($_GET['upload_mode']) and in_array($_GET['upload_mode'], $upload_modes))
351{
352  $index_of_upload_mode = array_flip($upload_modes);
353  $upload_mode_index = $index_of_upload_mode[ $_GET['upload_mode'] ];
354
355  $upload_mode = $_GET['upload_mode'];
356  $upload_switch = $upload_modes[ ($upload_mode_index + 1) % 2 ];
357}
358
359$template->assign(
360    array(
361      'upload_mode' => $upload_mode,
362      'switch_url' => $admin_base_url.'&upload_mode='.$upload_switch,
363      'upload_id' => md5(rand()),
364      'session_id' => session_id(),
365      'pwg_token' => get_pwg_token(),
366    )
367  );
368
369$template->append(
370  'head_elements',
371  '<link rel="stylesheet" type="text/css" href="'.UPLOAD_FORM_PATH.'uploadify/uploadify.css">'."\n"
372  );
373
374if (isset($page['thumbnails']))
375{
376  $template->assign(
377    array(
378      'thumbnails' => $page['thumbnails'],
379      )
380    );
381
382  // only display the batch link if we have more than 1 photo
383  if (count($page['thumbnails']) > 1)
384  {
385    $template->assign(
386      array(
387        'batch_link' => $page['batch_link'],
388        'batch_label' => sprintf(
389          l10n('Manage this set of %d photos'),
390          count($page['thumbnails'])
391          ),
392        )
393      );
394  }
395}
396
397$query = '
398SELECT id,name,uppercats,global_rank
399  FROM '.CATEGORIES_TABLE.'
400;';
401
402display_select_cat_wrapper(
403  $query,
404  array(),
405  'category_options'
406  );
407
408// image level options
409$tpl_options = array();
410foreach (array_reverse($conf['available_permission_levels']) as $level)
411{
412  $label = null;
413 
414  if (0 == $level)
415  {
416    $label = l10n('Everybody');
417  }
418  else
419  {
420    $labels = array();
421    $sub_levels = array_reverse($conf['available_permission_levels']);
422    foreach ($sub_levels as $sub_level)
423    {
424      if ($sub_level == 0 or $sub_level < $level)
425      {
426        break;
427      }
428      array_push(
429        $labels,
430        l10n(
431          sprintf(
432            'Level %d',
433            $sub_level
434            )
435          )
436        );
437    }
438   
439    $label = implode(', ', $labels);
440  }
441  $tpl_options[$level] = $label;
442}
443$selected_level = isset($_POST['level']) ? $_POST['level'] : 0;
444$template->assign(
445    array(
446      'level_options'=> $tpl_options,
447      'level_options_selected' => array($selected_level)
448    )
449  );
450
451// +-----------------------------------------------------------------------+
452// |                             setup errors                              |
453// +-----------------------------------------------------------------------+
454
455$setup_errors = array();
456
457$upload_base_dir = 'upload';
458$upload_dir = PHPWG_ROOT_PATH.$upload_base_dir;
459
460if (!is_dir($upload_dir))
461{
462  if (!is_writable(PHPWG_ROOT_PATH))
463  {
464    array_push(
465      $setup_errors,
466      sprintf(
467        l10n('Create the "%s" directory at the root of your Piwigo installation'),
468        $upload_base_dir
469        )
470      );
471  }
472}
473else
474{
475  if (!is_writable($upload_dir))
476  {
477    @chmod($upload_dir, 0777);
478
479    if (!is_writable($upload_dir))
480    {
481      array_push(
482        $setup_errors,
483        sprintf(
484          l10n('Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation'),
485          $upload_base_dir
486          )
487        );
488    }
489  }
490}
491
492$template->assign(
493    array(
494      'setup_errors'=> $setup_errors,
495    )
496  );
497
498// +-----------------------------------------------------------------------+
499// |                           sending html code                           |
500// +-----------------------------------------------------------------------+
501
502$template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
503?>
Note: See TracBrowser for help on using the repository browser.