source: extensions/upload_form/upload.php @ 9752

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

feature 1409 added: new tab "Settings".

Note: I would have like to use jQuery UI sliders for resize dimensions and
image quality BUT I can't even find the documentation of the very old version
of jQuery UI we use. I'll implement theses widget when integrating UploadForm
into trunk (with jQuery + jQuery UI updated).

File size: 13.3 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('UPLOAD_FORM_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['batch'], 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 = PHPWG_ROOT_PATH.'upload/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(UPLOAD_FORM_PATH.'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'] = UPLOAD_FORM_BASE_URL.'&batch='.implode(',', $image_ids);
315  }
316}
317
318// +-----------------------------------------------------------------------+
319// |                             template init                             |
320// +-----------------------------------------------------------------------+
321
322$template->assign(
323    array(
324      'F_ADD_ACTION'=> UPLOAD_FORM_BASE_URL,
325      'plugin_path' => UPLOAD_FORM_PATH,
326    )
327  );
328
329$upload_modes = array('html', 'multiple');
330
331$upload_mode = 'multiple';
332$upload_switch = 'html';
333if (isset($_GET['upload_mode']) and in_array($_GET['upload_mode'], $upload_modes))
334{
335  $index_of_upload_mode = array_flip($upload_modes);
336  $upload_mode_index = $index_of_upload_mode[ $_GET['upload_mode'] ];
337
338  $upload_mode = $_GET['upload_mode'];
339  $upload_switch = $upload_modes[ ($upload_mode_index + 1) % 2 ];
340}
341
342$template->assign(
343    array(
344      'upload_mode' => $upload_mode,
345      'switch_url' => UPLOAD_FORM_BASE_URL.'&amp;upload_mode='.$upload_switch,
346      'upload_id' => md5(rand()),
347      'session_id' => session_id(),
348      'pwg_token' => get_pwg_token(),
349    )
350  );
351
352$template->append(
353  'head_elements',
354  '<link rel="stylesheet" type="text/css" href="'.UPLOAD_FORM_PATH.'uploadify/uploadify.css">'."\n"
355  );
356
357if (isset($page['thumbnails']))
358{
359  $template->assign(
360    array(
361      'thumbnails' => $page['thumbnails'],
362      )
363    );
364
365  // only display the batch link if we have more than 1 photo
366  if (count($page['thumbnails']) > 1)
367  {
368    $template->assign(
369      array(
370        'batch_link' => $page['batch_link'],
371        'batch_label' => sprintf(
372          l10n('Manage this set of %d photos'),
373          count($page['thumbnails'])
374          ),
375        )
376      );
377  }
378}
379
380$query = '
381SELECT id,name,uppercats,global_rank
382  FROM '.CATEGORIES_TABLE.'
383;';
384
385display_select_cat_wrapper(
386  $query,
387  array(),
388  'category_options'
389  );
390
391// image level options
392$tpl_options = array();
393foreach (array_reverse($conf['available_permission_levels']) as $level)
394{
395  $label = null;
396 
397  if (0 == $level)
398  {
399    $label = l10n('Everybody');
400  }
401  else
402  {
403    $labels = array();
404    $sub_levels = array_reverse($conf['available_permission_levels']);
405    foreach ($sub_levels as $sub_level)
406    {
407      if ($sub_level == 0 or $sub_level < $level)
408      {
409        break;
410      }
411      array_push(
412        $labels,
413        l10n(
414          sprintf(
415            'Level %d',
416            $sub_level
417            )
418          )
419        );
420    }
421   
422    $label = implode(', ', $labels);
423  }
424  $tpl_options[$level] = $label;
425}
426$selected_level = isset($_POST['level']) ? $_POST['level'] : 0;
427$template->assign(
428    array(
429      'level_options'=> $tpl_options,
430      'level_options_selected' => array($selected_level)
431    )
432  );
433
434// +-----------------------------------------------------------------------+
435// |                             setup errors                              |
436// +-----------------------------------------------------------------------+
437
438$setup_errors = array();
439
440$upload_base_dir = 'upload';
441$upload_dir = PHPWG_ROOT_PATH.$upload_base_dir;
442
443if (!is_dir($upload_dir))
444{
445  if (!is_writable(PHPWG_ROOT_PATH))
446  {
447    array_push(
448      $setup_errors,
449      sprintf(
450        l10n('Create the "%s" directory at the root of your Piwigo installation'),
451        $upload_base_dir
452        )
453      );
454  }
455}
456else
457{
458  if (!is_writable($upload_dir))
459  {
460    @chmod($upload_dir, 0777);
461
462    if (!is_writable($upload_dir))
463    {
464      array_push(
465        $setup_errors,
466        sprintf(
467          l10n('Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation'),
468          $upload_base_dir
469          )
470        );
471    }
472  }
473}
474
475$template->assign(
476    array(
477      'setup_errors'=> $setup_errors,
478    )
479  );
480
481// +-----------------------------------------------------------------------+
482// |                           sending html code                           |
483// +-----------------------------------------------------------------------+
484
485$template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
486?>
Note: See TracBrowser for help on using the repository browser.