source: trunk/admin/batch_manager_global.php @ 12201

Last change on this file since 12201 was 11853, checked in by rvelices, 13 years ago

feature 2387: addd a filter by tag in the batch manager

File size: 21.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**
25 * Management of elements set. Elements can belong to a category or to the
26 * user caddie.
27 *
28 */
29
30if (!defined('PHPWG_ROOT_PATH'))
31{
32  die('Hacking attempt!');
33}
34
35include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
36include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
37
38$upload_form_config = get_upload_form_config();
39foreach ($upload_form_config as $param_shortname => $param)
40{
41  $param_name = 'upload_form_'.$param_shortname;
42  $form_values[$param_shortname] = $conf[$param_name];
43}
44
45// User cache must not be regenerated during simultaneous ajax requests
46if (!isset($user['need_update']) or !$user['need_update'])
47{
48  getuserdata($user['id'], true);
49}
50
51// +-----------------------------------------------------------------------+
52// | Check Access and exit when user status is not ok                      |
53// +-----------------------------------------------------------------------+
54
55check_status(ACCESS_ADMINISTRATOR);
56
57trigger_action('loc_begin_element_set_global');
58
59check_input_parameter('del_tags', $_POST, true, PATTERN_ID);
60check_input_parameter('associate', $_POST, false, PATTERN_ID);
61check_input_parameter('dissociate', $_POST, false, PATTERN_ID);
62
63// +-----------------------------------------------------------------------+
64// |                            current selection                          |
65// +-----------------------------------------------------------------------+
66
67$collection = array();
68if (isset($_POST['setSelected']))
69{
70  $collection = $page['cat_elements_id'];
71}
72else if (isset($_POST['selection']))
73{
74  $collection = $_POST['selection'];
75}
76
77// +-----------------------------------------------------------------------+
78// |                       global mode form submission                     |
79// +-----------------------------------------------------------------------+
80
81// $page['prefilter'] is a shortcut to test if the current filter contains a
82// given prefilter. The idea is to make conditions simpler to write in the
83// code.
84$page['prefilter'] = 'none';
85if (isset($_SESSION['bulk_manager_filter']['prefilter']))
86{
87  $page['prefilter'] = $_SESSION['bulk_manager_filter']['prefilter'];
88}
89
90// $page['category'] is a shortcut to test if the current filter contains a
91// given category. The idea is the same as for prefilter
92$page['category'] = -1;
93if (isset($_SESSION['bulk_manager_filter']['category']))
94{
95  $page['category'] = $_SESSION['bulk_manager_filter']['category'];
96}
97
98$redirect_url = get_root_url().'admin.php?page='.$_GET['page'];
99
100if (isset($_POST['submit']))
101{
102  // if the user tries to apply an action, it means that there is at least 1
103  // photo in the selection
104  if (count($collection) == 0)
105  {
106    array_push($page['errors'], l10n('Select at least one photo'));
107  }
108
109  $action = $_POST['selectAction'];
110 
111  if ('remove_from_caddie' == $action)
112  {
113    $query = '
114DELETE
115  FROM '.CADDIE_TABLE.'
116  WHERE element_id IN ('.implode(',', $collection).')
117    AND user_id = '.$user['id'].'
118;';
119    pwg_query($query);
120
121    if ('caddie' == $page['prefilter'])
122    {
123      redirect($redirect_url);
124    }
125   
126    // if we are here in the code, it means that the user is currently
127    // displaying the caddie content, so we have to remove the current
128    // selection from the current set
129    $page['cat_elements_id'] = array_diff($page['cat_elements_id'], $collection);
130  }
131
132  if ('add_tags' == $action)
133  {
134    if (empty($_POST['add_tags']))
135    {
136      array_push($page['errors'], l10n('Select at least one tag'));
137    }
138    else
139    {
140      $tag_ids = get_tag_ids($_POST['add_tags']);
141      add_tags($tag_ids, $collection);
142
143      if ('with no tag' == $page['prefilter'])
144      {
145        redirect(get_root_url().'admin.php?page='.$_GET['page']);
146      }
147    }
148  }
149
150  if ('del_tags' == $action)
151  {
152    if (count($_POST['del_tags']) == 0)
153    {
154      array_push($page['errors'], l10n('Select at least one tag'));
155    }
156   
157    $query = '
158DELETE
159  FROM '.IMAGE_TAG_TABLE.'
160  WHERE image_id IN ('.implode(',', $collection).')
161    AND tag_id IN ('.implode(',', $_POST['del_tags']).')
162;';
163    pwg_query($query);
164  }
165
166  if ('associate' == $action)
167  {
168    associate_images_to_categories(
169      $collection,
170      array($_POST['associate'])
171      );
172
173    $_SESSION['page_infos'] = array(
174      l10n('Information data registered in database')
175      );
176   
177    // let's refresh the page because we the current set might be modified
178    if ('with no album' == $page['prefilter'])
179    {
180      redirect($redirect_url);
181    }
182
183    if ('with no virtual album' == $page['prefilter'])
184    {
185      $category_info = get_cat_info($_POST['associate']);
186      if (empty($category_info['dir']))
187      {
188        redirect($redirect_url);
189      }
190    }
191  }
192
193  if ('dissociate' == $action)
194  {
195    // physical links must not be broken, so we must first retrieve image_id
196    // which create virtual links with the category to "dissociate from".
197    $query = '
198SELECT id
199  FROM '.IMAGE_CATEGORY_TABLE.'
200    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
201  WHERE category_id = '.$_POST['dissociate'].'
202    AND id IN ('.implode(',', $collection).')
203    AND (
204      category_id != storage_category_id
205      OR storage_category_id IS NULL
206    )
207;';
208    $dissociables = array_from_query($query, 'id');
209
210    if (!empty($dissociables))
211    {
212      $query = '
213DELETE
214  FROM '.IMAGE_CATEGORY_TABLE.'
215  WHERE category_id = '.$_POST['dissociate'].'
216    AND image_id IN ('.implode(',', $dissociables).')
217';
218      pwg_query($query);
219
220      update_category($_POST['dissociate']);
221     
222      $_SESSION['page_infos'] = array(
223        l10n('Information data registered in database')
224        );
225     
226      // let's refresh the page because we the current set might be modified
227      redirect($redirect_url);
228    }
229  }
230
231  // author
232  if ('author' == $action)
233  {
234    if (isset($_POST['remove_author']))
235    {
236      $_POST['author'] = null;
237    }
238   
239    $datas = array();
240    foreach ($collection as $image_id)
241    {
242      array_push(
243        $datas,
244        array(
245          'id' => $image_id,
246          'author' => $_POST['author']
247          )
248        );
249    }
250
251    mass_updates(
252      IMAGES_TABLE,
253      array('primary' => array('id'), 'update' => array('author')),
254      $datas
255      );
256  }
257
258  // title
259  if ('title' == $action)
260  {
261    if (isset($_POST['remove_title']))
262    {
263      $_POST['title'] = null;
264    }
265   
266    $datas = array();
267    foreach ($collection as $image_id)
268    {
269      array_push(
270        $datas,
271        array(
272          'id' => $image_id,
273          'name' => $_POST['title']
274          )
275        );
276    }
277
278    mass_updates(
279      IMAGES_TABLE,
280      array('primary' => array('id'), 'update' => array('name')),
281      $datas
282      );
283  }
284 
285  // date_creation
286  if ('date_creation' == $action)
287  {
288    $date_creation = sprintf(
289      '%u-%u-%u',
290      $_POST['date_creation_year'],
291      $_POST['date_creation_month'],
292      $_POST['date_creation_day']
293      );
294
295    if (isset($_POST['remove_date_creation']))
296    {
297      $date_creation = null;
298    }
299
300    $datas = array();
301    foreach ($collection as $image_id)
302    {
303      array_push(
304        $datas,
305        array(
306          'id' => $image_id,
307          'date_creation' => $date_creation
308          )
309        );
310    }
311
312    mass_updates(
313      IMAGES_TABLE,
314      array('primary' => array('id'), 'update' => array('date_creation')),
315      $datas
316      );
317  }
318 
319  // privacy_level
320  if ('level' == $action)
321  {
322    $datas = array();
323    foreach ($collection as $image_id)
324    {
325      array_push(
326        $datas,
327        array(
328          'id' => $image_id,
329          'level' => $_POST['level']
330          )
331        );
332    }
333
334    mass_updates(
335      IMAGES_TABLE,
336      array('primary' => array('id'), 'update' => array('level')),
337      $datas
338      );
339
340    if (isset($_SESSION['bulk_manager_filter']['level']))
341    {
342      if ($_POST['level'] < $_SESSION['bulk_manager_filter']['level'])
343      {
344        redirect($redirect_url);
345      }
346    }
347  }
348 
349  // add_to_caddie
350  if ('add_to_caddie' == $action)
351  {
352    fill_caddie($collection);
353  }
354 
355  // delete
356  if ('delete' == $action)
357  {
358    if (isset($_POST['confirm_deletion']) and 1 == $_POST['confirm_deletion'])
359    {
360      $deleted_count = delete_elements($collection, true);
361      if ($deleted_count > 0)
362      {
363        $_SESSION['page_infos'] = array(
364          sprintf(
365            l10n_dec(
366              '%d photo was deleted',
367              '%d photos were deleted',
368              $deleted_count
369              ),
370            $deleted_count
371            )
372          );
373
374        $redirect_url = get_root_url().'admin.php?page='.$_GET['page'];
375        redirect($redirect_url);
376      }
377      else
378      {
379        array_push($page['errors'], l10n('No photo can be deleted'));
380      }
381    }
382    else
383    {
384      array_push($page['errors'], l10n('You need to confirm deletion'));
385    }
386  }
387
388  // synchronize metadata
389  if ('metadata' == $action)
390  {
391    $query = '
392SELECT id, path
393  FROM '.IMAGES_TABLE.'
394  WHERE id IN ('.implode(',', $collection).')
395;';
396    $id_to_path = array();
397    $result = pwg_query($query);
398    while ($row = pwg_db_fetch_assoc($result))
399    {
400      $id_to_path[$row['id']] = $row['path'];
401    }
402   
403    update_metadata($id_to_path);
404
405    array_push(
406      $page['infos'],
407      l10n('Metadata synchronized from file')
408      );
409  }
410
411  if ('regenerateThumbnails' == $action)
412  {
413    if ($_POST['regenerateSuccess'] != '0')
414      array_push($page['infos'], sprintf(l10n('%s thumbnails have been regenerated'), $_POST['regenerateSuccess']));
415
416    if ($_POST['regenerateError'] != '0')
417      array_push($page['warnings'], sprintf(l10n('%s thumbnails can not be regenerated'), $_POST['regenerateError']));
418
419    $update_fields = array('thumb_maxwidth', 'thumb_maxheight', 'thumb_quality', 'thumb_crop', 'thumb_follow_orientation');
420  }
421
422  if ('regenerateWebsize' == $action)
423  {
424    if ($_POST['regenerateSuccess'] != '0')
425      array_push($page['infos'], sprintf(l10n('%s photos have been regenerated'), $_POST['regenerateSuccess']));
426
427    if ($_POST['regenerateError'] != '0')
428      array_push($page['warnings'], sprintf(l10n('%s photos can not be regenerated'), $_POST['regenerateError']));
429
430    $update_fields = array('websize_maxwidth', 'websize_maxheight', 'websize_quality');
431  }
432
433  if (!empty($update_fields))
434  {
435    // Update upload configuration
436    $updates = array();
437    foreach ($update_fields as $field)
438    {
439      $value = !empty($_POST[$field]) ? $_POST[$field] : null;
440      $form_values[$field] = $value;
441      $updates[$field] = $value;
442    }
443    save_upload_form_config($updates);
444    $template->delete_compiled_templates();
445  }
446
447  trigger_action('element_set_global_action', $action, $collection);
448}
449
450// +-----------------------------------------------------------------------+
451// |                             template init                             |
452// +-----------------------------------------------------------------------+
453$template->set_filenames(array('batch_manager_global' => 'batch_manager_global.tpl'));
454
455$base_url = get_root_url().'admin.php';
456
457$prefilters = array();
458
459array_push($prefilters,
460  array('ID' => 'caddie', 'NAME' => l10n('caddie')),
461  array('ID' => 'last import', 'NAME' => l10n('last import')),
462  array('ID' => 'with no album', 'NAME' => l10n('with no album')),
463  array('ID' => 'with no tag', 'NAME' => l10n('with no tag')),
464  array('ID' => 'duplicates', 'NAME' => l10n('duplicates')),
465  array('ID' => 'all photos', 'NAME' => l10n('All'))
466);
467
468if ($conf['enable_synchronization'])
469{
470  array_push($prefilters,
471    array('ID' => 'with no virtual album', 'NAME' => l10n('with no virtual album'))
472  );
473}
474
475$prefilters = trigger_event('get_batch_manager_prefilters', $prefilters);
476usort($prefilters, 'UC_name_compare');
477
478$template->assign(
479  array(
480    'prefilters' => $prefilters,
481    'filter' => $_SESSION['bulk_manager_filter'],
482    'selection' => $collection,
483    'all_elements' => $page['cat_elements_id'],
484    'upload_form_settings' => $form_values,
485    'U_DISPLAY'=>$base_url.get_query_string_diff(array('display')),
486    'F_ACTION'=>$base_url.get_query_string_diff(array('cat')),
487   )
488 );
489
490// +-----------------------------------------------------------------------+
491// |                            caddie options                             |
492// +-----------------------------------------------------------------------+
493
494$in_caddie = false;
495if (isset($_SESSION['bulk_manager_filter']['prefilter'])
496    and 'caddie' == $_SESSION['bulk_manager_filter']['prefilter'])
497{
498  $in_caddie = true;
499}
500$template->assign('IN_CADDIE', $in_caddie);
501
502// +-----------------------------------------------------------------------+
503// |                            deletion form                              |
504// +-----------------------------------------------------------------------+
505
506// we can only remove photos that have no storage_category_id, in other
507// word, it currently (Butterfly) means that the photo was added with
508// pLoader
509if (count($page['cat_elements_id']) > 0)
510{
511  $query = '
512SELECT
513    id
514  FROM '.IMAGES_TABLE.'
515  WHERE id IN ('.implode(',', $page['cat_elements_id']).')
516    AND file NOT LIKE \'http%\'
517  LIMIT 1
518;';
519  ;
520
521  if ( pwg_db_fetch_row(pwg_query($query)) )
522  {
523    $template->assign('show_delete_form', true);
524  }
525}
526
527// +-----------------------------------------------------------------------+
528// |                           global mode form                            |
529// +-----------------------------------------------------------------------+
530
531// privacy level
532$template->assign(
533    array(
534      'filter_level_options'=> get_privacy_level_options(),
535      'filter_level_options_selected' => isset($_SESSION['bulk_manager_filter']['level'])
536        ? $_SESSION['bulk_manager_filter']['level']
537        : 0,
538    )
539  );
540
541if (!empty($_SESSION['bulk_manager_filter']['tags']))
542{
543        $query = '
544SELECT id, name
545        FROM '.TAGS_TABLE.'
546        WHERE id IN ('.implode(',', $_SESSION['bulk_manager_filter']['tags']).')';
547        $template->assign('filter_tags', get_taglist($query));
548}
549
550// Virtualy associate a picture to a category
551$query = '
552SELECT id,name,uppercats,global_rank
553  FROM '.CATEGORIES_TABLE.'
554;';
555display_select_cat_wrapper($query, array(), 'associate_options', true);
556
557// in the filter box, which category to select by default
558$selected_category = array();
559
560if (isset($_SESSION['bulk_manager_filter']['category']))
561{
562  $selected_category = array($_SESSION['bulk_manager_filter']['category']);
563}
564else
565{
566  // we need to know the category in which the last photo was added
567  $selected_category = array();
568
569  $query = '
570SELECT
571    category_id,
572    id_uppercat
573  FROM '.IMAGES_TABLE.' AS i
574    JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON image_id = i.id
575    JOIN '.CATEGORIES_TABLE.' AS c ON category_id = c.id
576  ORDER BY i.id DESC
577  LIMIT 1
578;';
579  $result = pwg_query($query);
580  if (pwg_db_num_rows($result) > 0)
581  {
582    $row = pwg_db_fetch_assoc($result);
583 
584    $selected_category = array($row['category_id']);
585  }
586}
587
588$query = '
589SELECT id,name,uppercats,global_rank
590  FROM '.CATEGORIES_TABLE.'
591;';
592display_select_cat_wrapper($query, $selected_category, 'filter_category_options', true);
593
594// Dissociate from a category : categories listed for dissociation can only
595// represent virtual links. We can't create orphans. Links to physical
596// categories can't be broken.
597if (count($page['cat_elements_id']) > 0)
598{
599  $query = '
600SELECT
601    DISTINCT(category_id) AS id,
602    c.name,
603    c.uppercats,
604    c.global_rank
605  FROM '.IMAGE_CATEGORY_TABLE.' AS ic
606    JOIN '.CATEGORIES_TABLE.' AS c ON c.id = ic.category_id
607    JOIN '.IMAGES_TABLE.' AS i ON i.id = ic.image_id
608  WHERE ic.image_id IN ('.implode(',', $page['cat_elements_id']).')
609    AND (
610      ic.category_id != i.storage_category_id
611      OR i.storage_category_id IS NULL
612    )
613;';
614  display_select_cat_wrapper($query, array(), 'dissociate_options', true);
615}
616
617if (count($page['cat_elements_id']) > 0)
618{
619  // remove tags
620  $tags = get_common_tags($page['cat_elements_id'], -1);
621
622  $template->assign(
623    array(
624      'DEL_TAG_SELECTION' => get_html_tag_selection($tags, 'del_tags'),
625      )
626    );
627}
628
629// creation date
630$day =
631empty($_POST['date_creation_day']) ? date('j') : $_POST['date_creation_day'];
632
633$month =
634empty($_POST['date_creation_month']) ? date('n') : $_POST['date_creation_month'];
635
636$year =
637empty($_POST['date_creation_year']) ? date('Y') : $_POST['date_creation_year'];
638
639$month_list = $lang['month'];
640$month_list[0]='------------';
641ksort($month_list);
642$template->assign( array(
643      'month_list'         => $month_list,
644      'DATE_CREATION_DAY'  => (int)$day,
645      'DATE_CREATION_MONTH'=> (int)$month,
646      'DATE_CREATION_YEAR' => (int)$year,
647    )
648  );
649
650// image level options
651$template->assign(
652    array(
653      'level_options'=> get_privacy_level_options(),
654      'level_options_selected' => 0,
655    )
656  );
657
658// metadata
659include_once( PHPWG_ROOT_PATH.'admin/site_reader_local.php');
660$site_reader = new LocalSiteReader('./');
661$used_metadata = implode( ', ', $site_reader->get_metadata_attributes());
662
663$template->assign(
664    array(
665      'used_metadata' => $used_metadata,
666    )
667  );
668
669// +-----------------------------------------------------------------------+
670// |                        global mode thumbnails                         |
671// +-----------------------------------------------------------------------+
672
673// how many items to display on this page
674if (!empty($_GET['display']))
675{
676  if ('all' == $_GET['display'])
677  {
678    $page['nb_images'] = count($page['cat_elements_id']);
679  }
680  else
681  {
682    $page['nb_images'] = intval($_GET['display']);
683  }
684}
685else
686{
687  $page['nb_images'] = 20;
688}
689
690$nb_thumbs_page = 0;
691
692if (count($page['cat_elements_id']) > 0)
693{
694  $nav_bar = create_navigation_bar(
695    $base_url.get_query_string_diff(array('start')),
696    count($page['cat_elements_id']),
697    $page['start'],
698    $page['nb_images']
699    );
700  $template->assign('navbar', $nav_bar);
701
702  $is_category = false;
703  if (isset($_SESSION['bulk_manager_filter']['category'])
704      and !isset($_SESSION['bulk_manager_filter']['category_recursive']))
705  {
706    $is_category = true;
707  }
708
709  if (isset($_SESSION['bulk_manager_filter']['prefilter'])
710      and 'duplicates' == $_SESSION['bulk_manager_filter']['prefilter'])
711  {
712    $conf['order_by'] = ' ORDER BY file, id';
713  }
714
715
716  $query = '
717SELECT id,path,tn_ext,file,filesize,level,name
718  FROM '.IMAGES_TABLE;
719 
720  if ($is_category)
721  {
722    $category_info = get_cat_info($_SESSION['bulk_manager_filter']['category']);
723   
724    $conf['order_by'] = $conf['order_by_inside_category'];
725    if (!empty($category_info['image_order']))
726    {
727      $conf['order_by'] = ' ORDER BY '.$category_info['image_order'];
728    }
729
730    $query.= '
731    JOIN '.IMAGE_CATEGORY_TABLE.' ON id = image_id';
732  }
733
734  $query.= '
735  WHERE id IN ('.implode(',', $page['cat_elements_id']).')';
736
737  if ($is_category)
738  {
739    $query.= '
740    AND category_id = '.$_SESSION['bulk_manager_filter']['category'];
741  }
742
743  $query.= '
744  '.$conf['order_by'].'
745  LIMIT '.$page['nb_images'].' OFFSET '.$page['start'].'
746;';
747  $result = pwg_query($query);
748
749  // template thumbnail initialization
750  while ($row = pwg_db_fetch_assoc($result))
751  {
752    $nb_thumbs_page++;
753    $src = get_thumbnail_url($row);
754
755    $title = $row['name'];
756    if (empty($title))
757    {     
758      $title = get_name_from_file($row['file']);
759    }
760
761    $template->append(
762      'thumbnails',
763      array(
764        'ID' => $row['id'],
765        'TN_SRC' => $src,
766        'FILE' => $row['file'],
767        'TITLE' => $title,
768        'LEVEL' => $row['level']
769        )
770      );
771  }
772}
773
774$template->assign(
775  array(
776    'nb_thumbs_page' => $nb_thumbs_page,
777    'nb_thumbs_set' => count($page['cat_elements_id']),
778    )
779  );
780
781function regenerateThumbnails_prefilter($content, $smarty)
782{
783  return str_replace('{$thumbnail.TN_SRC}', '{$thumbnail.TN_SRC}?rand='.md5(uniqid(rand(), true)), $content);
784}
785$template->set_prefilter('batch_manager_global', 'regenerateThumbnails_prefilter');
786
787trigger_action('loc_end_element_set_global');
788
789//----------------------------------------------------------- sending html code
790$template->assign_var_from_handle('ADMIN_CONTENT', 'batch_manager_global');
791?>
Note: See TracBrowser for help on using the repository browser.