source: extensions/community/main.inc.php @ 19804

Last change on this file since 19804 was 19654, checked in by plg, 11 years ago

bug fixed: even with maximum permission, creating a root album was denied

File size: 13.5 KB
Line 
1<?php
2/*
3Plugin Name: Community
4Version: auto
5Description: Non admin users can add photos
6Plugin URI: http://piwigo.org/ext/extension_view.php?eid=303
7Author: plg
8Author URI: http://piwigo.wordpress.com
9*/
10
11if (!defined('PHPWG_ROOT_PATH'))
12{
13  die('Hacking attempt!');
14}
15
16define('COMMUNITY_PATH' , PHPWG_PLUGINS_PATH.basename(dirname(__FILE__)).'/');
17
18global $prefixeTable;
19define('COMMUNITY_PERMISSIONS_TABLE', $prefixeTable.'community_permissions');
20define('COMMUNITY_PENDINGS_TABLE', $prefixeTable.'community_pendings');
21
22include_once(COMMUNITY_PATH.'include/functions_community.inc.php');
23
24/* Plugin admin */
25add_event_handler('get_admin_plugin_menu_links', 'community_admin_menu');
26function community_admin_menu($menu)
27{
28  global $page;
29 
30  $query = '
31SELECT
32    COUNT(*)
33  FROM '.COMMUNITY_PENDINGS_TABLE.'
34  WHERE state = \'moderation_pending\'
35;';
36  $result = pwg_query($query);
37  list($page['community_nb_pendings']) = pwg_db_fetch_row($result);
38
39  $name = 'Community';
40  if ($page['community_nb_pendings'] > 0)
41  {
42    $style = 'background-color:#666;';
43    $style.= 'color:white;';
44    $style.= 'padding:1px 5px;';
45    $style.= '-moz-border-radius:10px;';
46    $style.= '-webkit-border-radius:10px;';
47    $style.= '-border-radius:10px;';
48    $style.= 'margin-left:5px;';
49   
50    $name.= '<span style="'.$style.'">'.$page['community_nb_pendings'].'</span>';
51
52    if (defined('IN_ADMIN') and IN_ADMIN and $page['page'] == 'intro')
53    {
54      global $template;
55     
56      $template->set_prefilter('intro', 'community_pendings_on_intro');
57      $template->assign(
58        array(
59          'COMMUNITY_PENDINGS' => sprintf(
60            '<a href="%s">'.l10n('%u pending photos').'</a>',
61            get_root_url().'admin.php?page=plugin-community-pendings',
62            $page['community_nb_pendings']
63            ),
64          )
65        );
66    }
67  }
68
69  array_push(
70    $menu,
71    array(
72      'NAME' => $name,
73      'URL'  => get_root_url().'admin.php?page=plugin-community'
74      )
75    );
76
77  return $menu;
78}
79
80function community_pendings_on_intro($content, &$smarty)
81{
82  $pattern = '#<li>\s*{\$DB_ELEMENTS\}#ms';
83  $replacement = '<li>{$COMMUNITY_PENDINGS}</li><li>{$DB_ELEMENTS}';
84  return preg_replace($pattern, $replacement, $content);
85}
86
87add_event_handler('init', 'community_load_language');
88function community_load_language()
89{
90  if (!defined('IN_ADMIN') or !IN_ADMIN)
91  {
92    load_language('admin.lang');
93  }
94 
95  load_language('plugin.lang', COMMUNITY_PATH);
96}
97
98
99add_event_handler('loc_end_section_init', 'community_section_init');
100function community_section_init()
101{
102  global $tokens, $page;
103 
104  if ($tokens[0] == 'add_photos')
105  {
106    $page['section'] = 'add_photos';
107  }
108}
109
110add_event_handler('loc_end_index', 'community_index');
111function community_index()
112{
113  global $page;
114 
115  if (isset($page['section']) and $page['section'] == 'add_photos')
116  {
117    include(COMMUNITY_PATH.'add_photos.php');
118  }
119}
120
121add_event_handler('blockmanager_apply' , 'community_gallery_menu', EVENT_HANDLER_PRIORITY_NEUTRAL+10);
122function community_gallery_menu($menu_ref_arr)
123{
124  global $conf, $user;
125
126  // conditional : depending on community permissions, display the "Add
127  // photos" link in the gallery menu
128  $user_permissions = community_get_user_permissions($user['id']);
129
130  if (count($user_permissions['upload_categories']) == 0 and !$user_permissions ['create_whole_gallery'])
131  {
132    return;
133  }
134
135  $menu = & $menu_ref_arr[0];
136
137  if (($block = $menu->get_block('mbMenu')) != null )
138  {
139    load_language('plugin.lang', COMMUNITY_PATH);
140
141    array_splice(
142      $block->data,
143      count($block->data),
144      0,
145      array(
146        '' => array(
147          'URL' => make_index_url(array('section' => 'add_photos')),
148          'TITLE' => l10n('Upload your own photos'),
149          'NAME' => l10n('Upload Photos')
150          )
151        )
152      );
153  }
154}
155
156
157add_event_handler('ws_invoke_allowed', 'community_switch_user_to_admin', EVENT_HANDLER_PRIORITY_NEUTRAL, 3);
158function community_switch_user_to_admin($res, $methodName, $params)
159{
160  global $user, $community;
161
162  if (is_admin())
163  {
164    return $res;
165  }
166 
167  $community = array('method' => $methodName);
168
169  if ('pwg.images.addSimple' == $community['method'])
170  {
171    $community['category'] = $params['category'];
172  }
173  elseif ('pwg.images.add' == $community['method'])
174  {
175    $community['category'] = $params['categories'];
176    $community['md5sum'] = $params['original_sum'];
177  }
178
179  // $print_params = $params;
180  // unset($print_params['data']);
181  // file_put_contents('/tmp/community.log', '['.$methodName.'] '.json_encode($print_params)."\n" ,FILE_APPEND);
182
183  // conditional : depending on community permissions, display the "Add
184  // photos" link in the gallery menu
185  $user_permissions = community_get_user_permissions($user['id']);
186
187  if (count($user_permissions['upload_categories']) == 0 and !$user_permissions ['create_whole_gallery'])
188  {
189    return $res;
190  }
191
192  // if level of trust is low, then we have to set level to 16
193
194  $methods = array();
195  $methods[] = 'pwg.tags.add';
196  $methods[] = 'pwg.images.exist';
197  $methods[] = 'pwg.images.add';
198  $methods[] = 'pwg.images.addSimple';
199  $methods[] = 'pwg.images.addChunk';
200  $methods[] = 'pwg.images.checkUpload';
201  $methods[] = 'pwg.images.checkFiles';
202  $methods[] = 'pwg.images.setInfo';
203
204  if (in_array($methodName, $methods))
205  {
206    $user['status'] = 'admin';
207  }
208
209  if ('pwg.categories.add' == $methodName)
210  {
211    if (in_array($params['parent'], $user_permissions['create_categories'])
212        or $user_permissions['create_whole_gallery'])
213    {
214      $user['status'] = 'admin';
215    }
216  }
217
218  return $res;
219}
220
221add_event_handler('ws_add_methods', 'community_ws_replace_methods', EVENT_HANDLER_PRIORITY_NEUTRAL+5);
222function community_ws_replace_methods($arr)
223{
224  global $conf, $user;
225 
226  $service = &$arr[0];
227
228  if (is_admin())
229  {
230    return;
231  }
232
233  $user_permissions = community_get_user_permissions($user['id']);
234 
235  if (count($user_permissions['permission_ids']) == 0)
236  {
237    return;
238  }
239 
240  // the plugin Community is activated, the user has upload permissions, we
241  // use a specific function to list available categories, assuming the user
242  // wants to list categories where upload is possible for him
243 
244  $service->addMethod(
245    'pwg.categories.getList',
246    'community_ws_categories_getList',
247    array(
248      'cat_id' => array('default'=>0),
249      'recursive' => array('default'=>false),
250      'public' => array('default'=>false),
251      'fullname' => array('default'=>false),
252      ),
253    'retrieves a list of categories'
254    );
255 
256  $service->addMethod(
257    'pwg.tags.getAdminList',
258    'community_ws_tags_getAdminList',
259    array(),
260    'administration method only'
261    );
262}
263
264/**
265 * returns a list of categories (web service method)
266 */
267function community_ws_categories_getList($params, &$service)
268{
269  global $user, $conf;
270
271  $where = array('1=1');
272  $join_type = 'LEFT';
273  $join_user = $user['id'];
274
275  if (!$params['recursive'])
276  {
277    if ($params['cat_id']>0)
278      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
279    OR id='.(int)($params['cat_id']).')';
280    else
281      $where[] = 'id_uppercat IS NULL';
282  }
283  else if ($params['cat_id']>0)
284  {
285    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
286      (int)($params['cat_id'])
287      .'(,|$)\'';
288  }
289
290  if ($params['public'])
291  {
292    $where[] = 'status = "public"';
293    $where[] = 'visible = "true"';
294   
295    $join_user = $conf['guest_id'];
296  }
297
298  $user_permissions = community_get_user_permissions($user['id']);
299  $upload_categories = $user_permissions['upload_categories'];
300  if (count($upload_categories) == 0)
301  {
302    $upload_categories = array(-1);
303  }
304
305  $where[] = 'id IN ('.implode(',', $upload_categories).')';
306
307  $query = '
308SELECT
309    id,
310    name,
311    permalink,
312    uppercats,
313    global_rank,
314    comment,
315    nb_images,
316    count_images AS total_nb_images,
317    date_last,
318    max_date_last,
319    count_categories AS nb_categories
320  FROM '.CATEGORIES_TABLE.'
321   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
322  WHERE '. implode('
323    AND ', $where);
324
325  $result = pwg_query($query);
326
327  $cats = array();
328  while ($row = pwg_db_fetch_assoc($result))
329  {
330    $row['url'] = make_index_url(
331        array(
332          'category' => $row
333          )
334      );
335    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
336    {
337      $row[$key] = (int)$row[$key];
338    }
339
340    if ($params['fullname'])
341    {
342      $row['name'] = strip_tags(get_cat_display_name_cache($row['uppercats'], null, false));
343    }
344    else
345    {
346      $row['name'] = strip_tags(
347        trigger_event(
348          'render_category_name',
349          $row['name'],
350          'ws_categories_getList'
351          )
352        );
353    }
354   
355    $row['comment'] = strip_tags(
356      trigger_event(
357        'render_category_description',
358        $row['comment'],
359        'ws_categories_getList'
360        )
361      );
362   
363    array_push($cats, $row);
364  }
365  usort($cats, 'global_rank_compare');
366  return array(
367    'categories' => new PwgNamedArray(
368      $cats,
369      'category',
370      array(
371        'id',
372        'url',
373        'nb_images',
374        'total_nb_images',
375        'nb_categories',
376        'date_last',
377        'max_date_last',
378        )
379      )
380    );
381}
382
383function community_ws_tags_getAdminList($params, &$service)
384{
385  $tags = get_available_tags();
386
387  // keep orphan tags
388  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
389  $orphan_tags = get_orphan_tags();
390  if (count($orphan_tags) > 0)
391  {
392    $orphan_tag_ids = array();
393    foreach ($orphan_tags as $tag)
394    {
395      $orphan_tag_ids[] = $tag['id'];
396    }
397   
398    $query = '
399SELECT *
400  FROM '.TAGS_TABLE.'
401  WHERE id IN ('.implode(',', $orphan_tag_ids).')
402;';
403    $result = pwg_query($query);
404    while ($row = pwg_db_fetch_assoc($result))
405    {
406      $tags[] = $row;
407    }
408  }
409
410  usort($tags, 'tag_alpha_compare');
411 
412  return array(
413    'tags' => new PwgNamedArray(
414      $tags,
415      'tag',
416      array(
417        'name',
418        'id',
419        'url_name',
420        )
421      )
422    );
423}
424
425add_event_handler('sendResponse', 'community_sendResponse');
426function community_sendResponse($encodedResponse)
427{
428  global $community, $user;
429
430  if (!isset($community['method']))
431  {
432    return;
433  }
434
435  if ('pwg.images.addSimple' == $community['method'])
436  {
437    $response = json_decode($encodedResponse);
438    $image_id = $response->result->image_id;
439  }
440  elseif ('pwg.images.add' == $community['method'])
441  {   
442    $query = '
443SELECT
444    id
445  FROM '.IMAGES_TABLE.'
446  WHERE md5sum = \''.$community['md5sum'].'\'
447  ORDER BY id DESC
448  LIMIT 1
449;';
450    list($image_id) = pwg_db_fetch_row(pwg_query($query));
451  }
452  else
453  {
454    return;
455  }
456 
457  $image_ids = array($image_id);
458
459  // $category_id is set in the photos_add_direct_process.inc.php included script
460  $category_infos = get_cat_info($community['category']);
461
462  // should the photos be moderated?
463  //
464  // if one of the user community permissions is not moderated on the path
465  // to gallery root, then the upload is not moderated. For example, if the
466  // user is allowed to upload to events/parties with no admin moderation,
467  // then he's not moderated when uploading in
468  // events/parties/happyNewYear2011
469  $moderate = true;
470
471  $user_permissions = community_get_user_permissions($user['id']);
472  $query = '
473SELECT
474    cp.category_id,
475    c.uppercats
476  FROM '.COMMUNITY_PERMISSIONS_TABLE.' AS cp
477    LEFT JOIN '.CATEGORIES_TABLE.' AS c ON category_id = c.id
478  WHERE cp.id IN ('.implode(',', $user_permissions['permission_ids']).')
479    AND cp.moderated = \'false\'
480;';
481  $result = pwg_query($query);
482  while ($row = pwg_db_fetch_assoc($result))
483  {
484    if (empty($row['category_id']))
485    {
486      $moderate = false;
487    }
488    elseif (preg_match('/^'.$row['uppercats'].'(,|$)/', $category_infos['uppercats']))
489    {
490      $moderate = false;
491    }
492  }
493 
494  if ($moderate)
495  {
496    $inserts = array();
497
498    $query = '
499SELECT
500    id,
501    date_available
502  FROM '.IMAGES_TABLE.'
503  WHERE id IN ('.implode(',', $image_ids).')
504;';
505    $result = pwg_query($query);
506    while ($row = pwg_db_fetch_assoc($result))
507    {
508      array_push(
509        $inserts,
510        array(
511          'image_id' => $row['id'],
512          'added_on' => $row['date_available'],
513          'state' => 'moderation_pending',
514          )
515        );
516    }
517   
518    mass_inserts(
519      COMMUNITY_PENDINGS_TABLE,
520      array_keys($inserts[0]),
521      $inserts
522      );
523   
524    // the level of a user upload photo with moderation is 16
525    $level = 16;
526  }
527  else
528  {
529    // the level of a user upload photo with no moderation is 0
530    $level = 0;
531  }
532
533  $query = '
534UPDATE '.IMAGES_TABLE.'
535  SET level = '.$level.'
536  WHERE id IN ('.implode(',', $image_ids).')
537;';
538  pwg_query($query);
539
540  invalidate_user_cache();
541}
542
543add_event_handler('delete_user', 'community_delete_user');
544function community_delete_user($user_id)
545{
546  $query = '
547DELETE
548  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
549  WHERE user_id = '.$user_id.'
550;';
551  pwg_query($query);
552
553  community_reject_user_pendings($user_id);
554}
555
556add_event_handler('delete_categories', 'community_delete_category');
557function community_delete_category($category_ids)
558{
559  // $category_ids includes all the sub-category ids
560  $query = '
561DELETE
562  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
563  WHERE category_id IN ('.implode(',', $category_ids).')
564;';
565  pwg_query($query);
566 
567  community_update_cache_key();
568}
569
570add_event_handler('invalidate_user_cache', 'community_refresh_cache_update_time');
571function community_refresh_cache_update_time()
572{
573  community_update_cache_key();
574}
575
576add_event_handler('init', 'community_uploadify_privacy_level');
577function community_uploadify_privacy_level()
578{
579  if (script_basename() == 'uploadify' and !is_admin())
580  {
581    $_POST['level'] = 16;
582  }
583}
584?>
Note: See TracBrowser for help on using the repository browser.