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

Last change on this file since 14518 was 12333, checked in by plg, 13 years ago

Make Community plugin compatible with the new upload form

The privacy level is set at the beginning of uploadify because Piwigo core
don't use 8 by default.

As soon as the user has created an album, he can't create another one (too
complicated to refresh the list of parent albums: this feature doesn't deserve
to make the code more complexe)

File size: 13.3 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');
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    {
213      $user['status'] = 'admin';
214    }
215  }
216
217  return $res;
218}
219
220add_event_handler('ws_add_methods', 'community_ws_replace_methods', EVENT_HANDLER_PRIORITY_NEUTRAL+5);
221function community_ws_replace_methods($arr)
222{
223  global $conf, $user;
224 
225  $service = &$arr[0];
226
227  if (is_admin())
228  {
229    return;
230  }
231
232  $user_permissions = community_get_user_permissions($user['id']);
233 
234  if (count($user_permissions['permission_ids']) == 0)
235  {
236    return;
237  }
238 
239  // the plugin Community is activated, the user has upload permissions, we
240  // use a specific function to list available categories, assuming the use
241  // want to list categories where upload is possible for him
242 
243  $service->addMethod(
244    'pwg.categories.getList',
245    'community_ws_categories_getList',
246    array(
247      'cat_id' => array('default'=>0),
248      'recursive' => array('default'=>false),
249      'public' => array('default'=>false),
250      ),
251    'retrieves a list of categories'
252    );
253 
254  $service->addMethod(
255    'pwg.tags.getAdminList',
256    'community_ws_tags_getAdminList',
257    array(),
258    'administration method only'
259    );
260}
261
262/**
263 * returns a list of categories (web service method)
264 */
265function community_ws_categories_getList($params, &$service)
266{
267  global $user, $conf;
268
269  $where = array('1=1');
270  $join_type = 'LEFT';
271  $join_user = $user['id'];
272
273  if (!$params['recursive'])
274  {
275    if ($params['cat_id']>0)
276      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
277    OR id='.(int)($params['cat_id']).')';
278    else
279      $where[] = 'id_uppercat IS NULL';
280  }
281  else if ($params['cat_id']>0)
282  {
283    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
284      (int)($params['cat_id'])
285      .'(,|$)\'';
286  }
287
288  if ($params['public'])
289  {
290    $where[] = 'status = "public"';
291    $where[] = 'visible = "true"';
292   
293    $join_user = $conf['guest_id'];
294  }
295
296  $user_permissions = community_get_user_permissions($user['id']);
297  $upload_categories = $user_permissions['upload_categories'];
298  if (count($upload_categories) == 0)
299  {
300    $upload_categories = array(-1);
301  }
302
303  $where[] = 'id IN ('.implode(',', $upload_categories).')';
304
305  $query = '
306SELECT
307    id,
308    name,
309    permalink,
310    uppercats,
311    global_rank,
312    comment,
313    nb_images,
314    count_images AS total_nb_images,
315    date_last,
316    max_date_last,
317    count_categories AS nb_categories
318  FROM '.CATEGORIES_TABLE.'
319   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
320  WHERE '. implode('
321    AND ', $where);
322
323  $result = pwg_query($query);
324
325  $cats = array();
326  while ($row = pwg_db_fetch_assoc($result))
327  {
328    $row['url'] = make_index_url(
329        array(
330          'category' => $row
331          )
332      );
333    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
334    {
335      $row[$key] = (int)$row[$key];
336    }
337
338    if ($params['fullname'])
339    {
340      $row['name'] = strip_tags(get_cat_display_name_cache($row['uppercats'], null, false));
341    }
342    else
343    {
344      $row['name'] = strip_tags(
345        trigger_event(
346          'render_category_name',
347          $row['name'],
348          'ws_categories_getList'
349          )
350        );
351    }
352   
353    $row['comment'] = strip_tags(
354      trigger_event(
355        'render_category_description',
356        $row['comment'],
357        'ws_categories_getList'
358        )
359      );
360   
361    array_push($cats, $row);
362  }
363  usort($cats, 'global_rank_compare');
364  return array(
365    'categories' => new PwgNamedArray(
366      $cats,
367      'category',
368      array(
369        'id',
370        'url',
371        'nb_images',
372        'total_nb_images',
373        'nb_categories',
374        'date_last',
375        'max_date_last',
376        )
377      )
378    );
379}
380
381function community_ws_tags_getAdminList($params, &$service)
382{
383  $tags = get_available_tags();
384
385  // keep orphan tags
386  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
387  $orphan_tags = get_orphan_tags();
388  if (count($orphan_tags) > 0)
389  {
390    $orphan_tag_ids = array();
391    foreach ($orphan_tags as $tag)
392    {
393      $orphan_tag_ids[] = $tag['id'];
394    }
395   
396    $query = '
397SELECT *
398  FROM '.TAGS_TABLE.'
399  WHERE id IN ('.implode(',', $orphan_tag_ids).')
400;';
401    $result = pwg_query($query);
402    while ($row = pwg_db_fetch_assoc($result))
403    {
404      $tags[] = $row;
405    }
406  }
407
408  usort($tags, 'tag_alpha_compare');
409 
410  return array(
411    'tags' => new PwgNamedArray(
412      $tags,
413      'tag',
414      array(
415        'name',
416        'id',
417        'url_name',
418        )
419      )
420    );
421}
422
423add_event_handler('sendResponse', 'community_sendResponse');
424function community_sendResponse($encodedResponse)
425{
426  global $community, $user;
427
428  if (!isset($community['method']))
429  {
430    return;
431  }
432
433  if ('pwg.images.addSimple' == $community['method'])
434  {
435    $response = json_decode($encodedResponse);
436    $image_id = $response->result->image_id;
437  }
438  elseif ('pwg.images.add' == $community['method'])
439  {   
440    $query = '
441SELECT
442    id
443  FROM '.IMAGES_TABLE.'
444  WHERE md5sum = \''.$community['md5sum'].'\'
445  ORDER BY id DESC
446  LIMIT 1
447;';
448    list($image_id) = pwg_db_fetch_row(pwg_query($query));
449  }
450  else
451  {
452    return;
453  }
454 
455  $image_ids = array($image_id);
456
457  // $category_id is set in the photos_add_direct_process.inc.php included script
458  $category_infos = get_cat_info($community['category']);
459
460  // should the photos be moderated?
461  //
462  // if one of the user community permissions is not moderated on the path
463  // to gallery root, then the upload is not moderated. For example, if the
464  // user is allowed to upload to events/parties with no admin moderation,
465  // then he's not moderated when uploading in
466  // events/parties/happyNewYear2011
467  $moderate = true;
468
469  $user_permissions = community_get_user_permissions($user['id']);
470  $query = '
471SELECT
472    cp.category_id,
473    c.uppercats
474  FROM '.COMMUNITY_PERMISSIONS_TABLE.' AS cp
475    LEFT JOIN '.CATEGORIES_TABLE.' AS c ON category_id = c.id
476  WHERE cp.id IN ('.implode(',', $user_permissions['permission_ids']).')
477    AND cp.moderated = \'false\'
478;';
479  $result = pwg_query($query);
480  while ($row = pwg_db_fetch_assoc($result))
481  {
482    if (empty($row['category_id']))
483    {
484      $moderate = false;
485    }
486    elseif (preg_match('/^'.$row['uppercats'].'(,|$)/', $category_infos['uppercats']))
487    {
488      $moderate = false;
489    }
490  }
491 
492  if ($moderate)
493  {
494    $inserts = array();
495
496    $query = '
497SELECT
498    id,
499    date_available
500  FROM '.IMAGES_TABLE.'
501  WHERE id IN ('.implode(',', $image_ids).')
502;';
503    $result = pwg_query($query);
504    while ($row = pwg_db_fetch_assoc($result))
505    {
506      array_push(
507        $inserts,
508        array(
509          'image_id' => $row['id'],
510          'added_on' => $row['date_available'],
511          'state' => 'moderation_pending',
512          )
513        );
514    }
515   
516    mass_inserts(
517      COMMUNITY_PENDINGS_TABLE,
518      array_keys($inserts[0]),
519      $inserts
520      );
521   
522    // the level of a user upload photo with moderation is 16
523    $level = 16;
524  }
525  else
526  {
527    // the level of a user upload photo with no moderation is 0
528    $level = 0;
529  }
530
531  $query = '
532UPDATE '.IMAGES_TABLE.'
533  SET level = '.$level.'
534  WHERE id IN ('.implode(',', $image_ids).')
535;';
536  pwg_query($query);
537
538  invalidate_user_cache();
539}
540
541add_event_handler('delete_user', 'community_delete_user');
542function community_delete_user($user_id)
543{
544  $query = '
545DELETE
546  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
547  WHERE user_id = '.$user_id.'
548;';
549  pwg_query($query);
550
551  community_reject_user_pendings($user_id);
552}
553
554add_event_handler('delete_categories', 'community_delete_category');
555function community_delete_category($category_ids)
556{
557  // $category_ids includes all the sub-category ids
558  $query = '
559DELETE
560  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
561  WHERE category_id IN ('.implode(',', $category_ids).')
562;';
563  pwg_query($query);
564 
565  community_update_cache_key();
566}
567
568add_event_handler('invalidate_user_cache', 'community_refresh_cache_update_time');
569function community_refresh_cache_update_time()
570{
571  community_update_cache_key();
572}
573
574add_event_handler('init', 'community_uploadify_privacy_level');
575function community_uploadify_privacy_level()
576{
577  if (script_basename() == 'uploadify' and !is_admin())
578  {
579    $_POST['level'] = 16;
580  }
581}
582?>
Note: See TracBrowser for help on using the repository browser.