Index: /extensions/community/add_photos.php
===================================================================
--- /extensions/community/add_photos.php	(revision 9372)
+++ /extensions/community/add_photos.php	(revision 9372)
@@ -0,0 +1,365 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based photo gallery                                    |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
+
+global $template, $conf, $user;
+
+include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
+include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
+include_once(COMMUNITY_PATH.'include/functions_community.inc.php');
+
+define('PHOTOS_ADD_BASE_URL', make_index_url(array('section' => 'add_photos')));
+
+$user_permissions = community_get_user_permissions($user['id']);
+
+// +-----------------------------------------------------------------------+
+// |                             process form                              |
+// +-----------------------------------------------------------------------+
+
+$page['errors'] = array();
+$page['infos'] = array();
+$_POST['level'] = 16;
+
+if (isset($_GET['processed']))
+{
+  $hacking_attempt = false;
+  
+  if ('existing' == $_POST['category_type'])
+  {
+    // is the user authorized to upload in this album?
+    if (!$user_permissions['upload_whole_gallery'])
+    {
+      if (!in_array($_POST['category'], $user_permissions['upload_categories']))
+      {
+        echo 'Hacking attempt, you have no permission to upload in this album';
+        $hacking_attempt = true;
+      }
+    }
+  }
+  elseif ('new' == $_POST['category_type'])
+  {
+    if (!$user_permissions['create_whole_gallery'])
+    {
+      if (!in_array($_POST['category_parent'], $user_permissions['create_categories']))
+      {
+        echo 'Hacking attempt, you have no permission to create this album';
+        $hacking_attempt = true;
+      }
+    }
+  }
+
+  if ($hacking_attempt)
+  {
+    if (isset($_SESSION['uploads'][ $_POST['upload_id'] ]))
+    {
+      delete_elements($_SESSION['uploads'][ $_POST['upload_id'] ], true);
+    }
+    exit();
+  }
+}
+
+include_once(PHPWG_ROOT_PATH.'admin/include/photos_add_direct_process.inc.php');
+
+if (isset($image_ids) and count($image_ids) > 0)
+{
+  // reinitialize the informations to display on the result page
+  $page['infos'] = array();
+  
+  // $category_id is set in the photos_add_direct_process.inc.php included script
+  $category_infos = get_cat_info($category_id);
+  $category_name = get_cat_display_name($category_infos['upper_names']);
+
+  array_push(
+    $page['infos'],
+    sprintf(
+      l10n('%d photos uploaded into album "%s"'),
+      count($page['thumbnails']),
+      '<em>'.$category_name.'</em>'
+      )
+    );
+
+  // should the photos be moderated?
+  //
+  // if one of the user community permissions is not moderated on the path
+  // to gallery root, then the upload is not moderated. For example, if the
+  // user is allowed to upload to events/parties with no admin moderation,
+  // then he's not moderated when uploading in
+  // events/parties/happyNewYear2011
+  $moderate = true;
+  
+  $query = '
+SELECT
+    cp.category_id,
+    c.uppercats
+  FROM '.COMMUNITY_PERMISSIONS_TABLE.' AS cp
+    LEFT JOIN '.CATEGORIES_TABLE.' AS c ON category_id = c.id
+  WHERE cp.id IN ('.implode(',', $user_permissions['permission_ids']).')
+    AND cp.moderated = \'false\'
+;';
+  $result = pwg_query($query);
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    if (empty($row['category_id']))
+    {
+      $moderate = false;
+    }
+    elseif (preg_match('/^'.$row['uppercats'].'(,|$)/', $category_infos['uppercats']))
+    {
+      $moderate = false;
+    }
+  }
+
+  if ($moderate)
+  {
+    $inserts = array();
+
+    $query = '
+SELECT
+    id,
+    date_available
+  FROM '.IMAGES_TABLE.'
+  WHERE id IN ('.implode(',', $image_ids).')
+;';
+    $result = pwg_query($query);
+    while ($row = pwg_db_fetch_assoc($result))
+    {
+      array_push(
+        $inserts,
+        array(
+          'image_id' => $row['id'],
+          'added_on' => $row['date_available'],
+          'state' => 'moderation_pending',
+          )
+        );
+    }
+    
+    mass_inserts(
+      COMMUNITY_PENDINGS_TABLE,
+      array_keys($inserts[0]),
+      $inserts
+      );
+
+    // the link on thumbnail must go to the websize photo
+    foreach ($page['thumbnails'] as $idx => $thumbnail)
+    {
+      $page['thumbnails'][$idx]['link'] = str_replace(
+        'thumbnail/'.$conf['prefix_thumbnail'],
+        '',
+        $thumbnail['src']
+        );
+    }
+
+    array_push(
+      $page['infos'],
+      l10n('Your photos are waiting for validation, administrators have been notified')
+      );
+  }
+  else
+  {
+    // we have to change the level.
+    //
+    // the level must equal the minimum level between :
+    // * the privacy level of the uploader
+    // * the minimum level for photos in the same album
+    $category_min_level = null;
+    
+    $query = '
+SELECT
+    image_id,
+    level
+  FROM '.IMAGE_CATEGORY_TABLE.' AS ic
+    JOIN '.IMAGES_TABLE.' AS i ON ic.image_id = i.id
+  WHERE category_id = '.$category_id.'
+;';
+    $result = pwg_query($query);
+    while ($row = pwg_db_fetch_assoc($result))
+    {
+      if (in_array($row['image_id'], $image_ids))
+      {
+        continue;
+      }
+
+      if (!isset($category_min_level))
+      {
+        $category_min_level = $row['level'];
+      }
+
+      if ($row['level'] < $category_min_level)
+      {
+        $category_min_level = $row['level'];
+      }
+    }
+
+    if (!isset($category_min_level))
+    {
+      $category_min_level = 0;
+    }
+
+    $level = min($category_min_level, $user['level']);
+
+    $query = '
+UPDATE '.IMAGES_TABLE.'
+  SET level = '.$level.'
+  WHERE id IN ('.implode(',', $image_ids).')
+;';
+    pwg_query($query);
+
+    // the link on thumbnail must go to picture.php
+    foreach ($page['thumbnails'] as $idx => $thumbnail)
+    {
+      if (preg_match('/image_id=(\d+)/', $thumbnail['link'], $matches))
+      {
+        $page['thumbnails'][$idx]['link'] = make_picture_url(
+          array(
+            'image_id' => $matches[1],
+            'image_file' => $thumbnail['file'],
+            'category' => $category_infos,
+            )
+          );
+      }
+    }
+  }
+
+  invalidate_user_cache();
+
+  // let's notify administrators
+  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
+
+  $keyargs_content = array(
+    get_l10n_args('Hi administrators,', ''),
+    get_l10n_args('', ''),
+    get_l10n_args('Album: %s', get_cat_display_name($category_infos['upper_names'], null, false)),
+    get_l10n_args('User: %s', $user['username']),
+    get_l10n_args('Email: %s', $user['email']),
+    );
+
+  if ($moderate)
+  {
+    $keyargs_content[] = get_l10n_args('', '');
+    
+    array_push(
+      $keyargs_content,
+      get_l10n_args(
+        'Validation page: %s',
+        get_absolute_root_url().'admin.php?page=plugin-community-pendings'
+        )
+      );
+  }
+
+  pwg_mail_notification_admins(
+    get_l10n_args('%d photos uploaded by %s', array(count($image_ids), $user['username'])),
+    $keyargs_content,
+    false
+    );
+}
+
+// +-----------------------------------------------------------------------+
+// |                             prepare form                              |
+// +-----------------------------------------------------------------------+
+
+$template->set_filenames(array('add_photos' => dirname(__FILE__).'/add_photos.tpl'));
+
+include_once(PHPWG_ROOT_PATH.'admin/include/photos_add_direct_prepare.inc.php');
+
+if (!$user_permissions['upload_whole_gallery'])
+{
+  // we have to change the list of uploadable albums
+  $query = '
+SELECT id,name,uppercats,global_rank
+  FROM '.CATEGORIES_TABLE.'
+  WHERE id IN ('.implode(',', $user_permissions['upload_categories']).')
+;';
+
+  display_select_cat_wrapper(
+    $query,
+    $selected_category,
+    'category_options'
+    );
+}
+
+$create_subcategories = false;
+
+if ($user_permissions['create_whole_gallery'] or count($user_permissions['create_categories']) > 0)
+{
+  $create_subcategories = true;
+  $category_ids = null;
+  
+  $query = '
+SELECT id,name,uppercats,global_rank
+  FROM '.CATEGORIES_TABLE;
+  
+  if (!$user_permissions['create_whole_gallery'])
+  {
+    $query.= '
+  WHERE id IN ('.implode(',', $user_permissions['create_categories']).')';
+  }
+
+  $query.= '
+;';
+
+  display_select_cat_wrapper(
+    $query,
+    $selected_category,
+    'category_parent_options'
+    );
+}
+
+$template->assign(
+  array(
+    'create_subcategories' => $create_subcategories,
+    'create_whole_gallery' => $user_permissions['create_whole_gallery'],
+    )
+  );
+
+
+// +-----------------------------------------------------------------------+
+// |                             display page                              |
+// +-----------------------------------------------------------------------+
+
+if (count($page['errors']) != 0)
+{
+  $template->assign('errors', $page['errors']);
+}
+
+if (count($page['infos']) != 0)
+{
+  $template->assign('infos', $page['infos']);
+}
+
+$title = l10n('Upload Photos');
+$page['body_id'] = 'theUploadPage';
+// include(PHPWG_ROOT_PATH.'include/page_header.php');
+// $template->pparse('add_photos');
+// include(PHPWG_ROOT_PATH.'include/page_tail.php');
+
+$template->assign_var_from_handle('PLUGIN_INDEX_CONTENT_BEGIN', 'add_photos');
+
+$template->clear_assign(array('U_MODE_POSTED', 'U_MODE_CREATED'));
+
+$template->assign(
+  array(
+    'TITLE' => '<a href="'.get_gallery_home_url().'">'.l10n('Home').'</a>'.$conf['level_separator'].$title,
+    )
+  );
+?>
Index: /extensions/community/add_photos.tpl
===================================================================
--- /extensions/community/add_photos.tpl	(revision 9372)
+++ /extensions/community/add_photos.tpl	(revision 9372)
@@ -0,0 +1,416 @@
+{combine_script id='jquery' path='themes/default/js/jquery.min.js'}
+{combine_script id='jquery.jgrowl' load='footer' require='jquery' path='themes/default/js/plugins/jquery.jgrowl_minimized.js' }
+
+{if $upload_mode eq 'multiple'}
+{combine_script id='swfobject' load='footer' path='admin/include/uploadify/swfobject.js'}
+{combine_script id='jquery.uploadify' load='footer' require='jquery' path='admin/include/uploadify/jquery.uploadify.v2.1.0.min.js' }
+{/if}
+
+{combine_css path="admin/include/uploadify/uploadify.css"}
+{combine_css path="admin/themes/default/uploadify.jGrowl.css"}
+
+
+{footer_script}{literal}
+jQuery(document).ready(function(){
+  function checkUploadStart() {
+    var nbErrors = 0;
+    $("#formErrors").hide();
+    $("#formErrors li").hide();
+
+    if ($("input[name=category_type]:checked").val() == "new" && $("input[name=category_name]").val() == "") {
+      $("#formErrors #emptyCategoryName").show();
+      nbErrors++;
+    }
+
+    var nbFiles = 0;
+    if ($("#uploadBoxes").size() == 1) {
+      $("input[name^=image_upload]").each(function() {
+        if ($(this).val() != "") {
+          nbFiles++;
+        }
+      });
+    }
+    else {
+      nbFiles = $(".uploadifyQueueItem").size();
+    }
+
+    if (nbFiles == 0) {
+      $("#formErrors #noPhoto").show();
+      nbErrors++;
+    }
+
+    if (nbErrors != 0) {
+      $("#formErrors").show();
+      return false;
+    }
+    else {
+      return true;
+    }
+
+  }
+
+  function humanReadableFileSize(bytes) {
+    var byteSize = Math.round(bytes / 1024 * 100) * .01;
+    var suffix = 'KB';
+
+    if (byteSize > 1000) {
+      byteSize = Math.round(byteSize *.001 * 100) * .01;
+      suffix = 'MB';
+    }
+
+    var sizeParts = byteSize.toString().split('.');
+    if (sizeParts.length > 1) {
+      byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2);
+    }
+    else {
+      byteSize = sizeParts[0];
+    }
+
+    return byteSize+suffix;
+  }
+
+  if ($("select[name=category] option").length == 0) {
+    $('input[name=category_type][value=existing]').attr('disabled', true);
+    $('input[name=category_type]').attr('checked', false);
+    $('input[name=category_type][value=new]').attr('checked', true);
+  }
+
+  $("input[name=category_type]").click(function () {
+    $("[id^=category_type_]").hide();
+    $("#category_type_"+$(this).attr("value")).show();
+  });
+
+  $("#hideErrors").click(function() {
+    $("#formErrors").hide();
+    return false;
+  });
+
+  $("a.externalLink").click(function() {
+    window.open($(this).attr("href"));
+    return false;
+  });
+
+{/literal}
+{if $upload_mode eq 'html'}
+{literal}
+  function addUploadBox() {
+    var uploadBox = '<p class="file"><input type="file" size="60" name="image_upload[]"></p>';
+    $(uploadBox).appendTo("#uploadBoxes");
+  }
+
+  addUploadBox();
+
+  $("#addUploadBox A").click(function () {
+    addUploadBox();
+  });
+
+  $("#uploadForm").submit(function() {
+    return checkUploadStart();
+  });
+{/literal}
+{elseif $upload_mode eq 'multiple'}
+
+var uploadify_path = '{$uploadify_path}';
+var upload_id = '{$upload_id}';
+var session_id = '{$session_id}';
+var pwg_token = '{$pwg_token}';
+var buttonText = 'Browse';
+var sizeLimit = {$upload_max_filesize};
+
+{literal}
+  jQuery("#uploadify").uploadify({
+    'uploader'       : uploadify_path + '/uploadify.swf',
+    'script'         : uploadify_path + '/uploadify.php',
+    'scriptData'     : {
+      'upload_id' : upload_id,
+      'session_id' : session_id,
+      'pwg_token' : pwg_token,
+    },
+    'cancelImg'      : uploadify_path + '/cancel.png',
+    'queueID'        : 'fileQueue',
+    'auto'           : false,
+    'displayData'    : 'speed',
+    'buttonText'     : buttonText,
+    'multi'          : true,
+    'fileDesc'       : 'Photo files (*.jpg,*.jpeg,*.png)',
+    'fileExt'        : '*.jpg;*.JPG;*.jpeg;*.JPEG;*.png;*.PNG',
+    'sizeLimit'      : sizeLimit,
+    'onAllComplete'  : function(event, data) {
+      if (data.errors) {
+        return false;
+      }
+      else {
+        $("input[name=submit_upload]").click();
+      }
+    },
+    onError: function (event, queueID ,fileObj, errorObj) {
+      var msg;
+
+      if (errorObj.type === "HTTP") {
+        if (errorObj.info === 404) {
+          alert('Could not find upload script.');
+          msg = 'Could not find upload script.';
+        }
+        else {
+          msg = errorObj.type+": "+errorObj.info;
+        }
+      }
+      else if (errorObj.type ==="File Size") {
+        msg = "File too big";
+        msg = msg + '<br>'+fileObj.name+': '+humanReadableFileSize(fileObj.size);
+        msg = msg + '<br>Limit: '+humanReadableFileSize(sizeLimit);
+      }
+      else {
+        msg = errorObj.type+": "+errorObj.info;
+      }
+
+      $.jGrowl(
+        '<p></p>'+msg,
+        {
+          theme:  'error',
+          header: 'ERROR',
+          sticky: true
+        }
+      );
+
+      $("#fileUploadgrowl" + queueID).fadeOut(
+        250,
+        function() {
+          $("#fileUploadgrowl" + queueID).remove()
+        }
+      );
+      return false;
+    },
+    onCancel: function (a, b, c, d) {
+      var msg = "Cancelled uploading: "+c.name;
+      $.jGrowl(
+        '<p></p>'+msg,
+        {
+          theme:  'warning',
+          header: 'Cancelled Upload',
+          life:   4000,
+          sticky: false
+        }
+      );
+    },
+    onClearQueue: function (a, b) {
+      var msg = "Cleared "+b.fileCount+" files from queue";
+      $.jGrowl(
+        '<p></p>'+msg,
+        {
+          theme:  'warning',
+          header: 'Cleared Queue',
+          life:   4000,
+          sticky: false
+        }
+      );
+    },
+    onComplete: function (a, b ,c, d, e) {
+      var size = Math.round(c.size/1024);
+      $.jGrowl(
+        '<p></p>'+c.name+' - '+size+'KB',
+        {
+          theme:  'success',
+          header: 'Upload Complete',
+          life:   4000,
+          sticky: false
+        }
+      );
+    }
+  });
+
+  $("input[type=button]").click(function() {
+    if (!checkUploadStart()) {
+      return false;
+    }
+
+    $("#uploadify").uploadifyUpload();
+  });
+
+{/literal}
+{/if}
+});
+{/footer_script}
+
+{literal}
+<style>
+#photosAddContent FIELDSET {
+  width:650px;
+  margin:20px auto;
+}
+
+#photosAddContent P {
+  /* margin:0; */
+}
+
+#uploadBoxes P {
+  margin:0;
+  margin-bottom:2px;
+  padding:0;
+}
+
+#batchLink {
+  text-align:center;
+}
+
+.category_selection {
+  min-height:50px;
+  margin-top:5px;
+}
+
+.category_selection TABLE {
+  margin:0;
+}
+</style>
+{/literal}
+
+<div id="photosAddContent">
+
+  {if isset($errors)}
+  <div class="errors">
+    <ul>
+      {foreach from=$errors item=error}
+      <li>{$error}</li>
+      {/foreach}
+    </ul>
+  </div>
+  {/if}
+
+  {if isset($infos)}
+  <div class="infos">
+    <ul>
+      {foreach from=$infos item=info}
+      <li>{$info}</li>
+      {/foreach}
+    </ul>
+  </div>
+  {/if}
+
+
+{if count($setup_errors) > 0}
+<div class="errors">
+  <ul>
+  {foreach from=$setup_errors item=error}
+    <li>{$error}</li>
+  {/foreach}
+  </ul>
+</div>
+{else}
+
+  {if count($setup_warnings) > 0}
+<div class="warnings">
+  <ul>
+    {foreach from=$setup_warnings item=warning}
+    <li>{$warning}</li>
+    {/foreach}
+  </ul>
+  <div class="hideButton" style="text-align:center"><a href="{$hide_warnings_link}">{'Hide'|@translate}</a></div>
+</div>
+  {/if}
+
+
+{if !empty($thumbnails)}
+<fieldset>
+  <legend>{'Uploaded Photos'|@translate}</legend>
+  <div>
+  {foreach from=$thumbnails item=thumbnail}
+    <a href="{$thumbnail.link}" class="externalLink">
+      <img src="{$thumbnail.src}" alt="{$thumbnail.file}" title="{$thumbnail.title}" class="thumbnail">
+    </a>
+  {/foreach}
+  </div>
+</fieldset>
+<p><a href="{$another_upload_link}">{'Add another set of photos'|@translate}</a></p>
+{else}
+
+<div id="formErrors" class="errors" style="display:none">
+  <ul>
+    <li id="emptyCategoryName">{'The name of an album must not be empty'|@translate}</li>
+    <li id="noPhoto">{'Select at least one photo'|@translate}</li>
+  </ul>
+  <div class="hideButton" style="text-align:center"><a href="#" id="hideErrors">{'Hide'|@translate}</a></div>
+</div>
+
+<form id="uploadForm" enctype="multipart/form-data" method="post" action="{$form_action}" class="properties">
+    <fieldset>
+      <legend>{'Drop into album'|@translate}</legend>
+      {if $upload_mode eq 'multiple'}
+      <input name="upload_id" value="{$upload_id}" type="hidden">
+      {/if}
+
+{if $create_subcategories}
+      <label><input type="radio" name="category_type" value="existing"> {'existing album'|@translate}</label>
+      <label><input type="radio" name="category_type" value="new" checked="checked"> {'create a new album'|@translate}</label>
+{else}
+      <input name="category_type" value="existing" type="hidden">
+{/if}
+
+      <div id="category_type_existing" {if $create_subcategories}style="display:none" class="category_selection"{/if}>
+        <select class="categoryDropDown" name="category">
+          {html_options options=$category_options selected=$category_options_selected}
+        </select>
+      </div>
+
+{if $create_subcategories}
+      <div id="category_type_new" class="category_selection">
+        <table>
+          <tr>
+            <td>{'Parent album'|@translate}</td>
+            <td>
+              <select class="categoryDropDown" name="category_parent">
+{if $create_whole_gallery}
+                <option value="0">------------</option>
+{/if}
+                {html_options options=$category_parent_options selected=$category_parent_options_selected}
+              </select>
+            </td>
+          </tr>
+          <tr>
+            <td>{'Album name'|@translate}</td>
+            <td>
+              <input type="text" name="category_name" value="{$F_CATEGORY_NAME}" style="width:400px">
+            </td>
+          </tr>
+        </table>
+      </div>
+{/if}
+    </fieldset>
+
+    <fieldset>
+      <legend>{'Select files'|@translate}</legend>
+
+{if $upload_mode eq 'html'}
+    <p><a href="{$switch_url}">{'... or switch to the multiple files form'|@translate}</a></p>
+
+      <p>{'JPEG files or ZIP archives with JPEG files inside please.'|@translate}</p>
+
+      <div id="uploadBoxes"></div>
+      <div id="addUploadBox">
+        <a href="javascript:">{'+ Add an upload box'|@translate}</a>
+      </div>
+    
+    </fieldset>
+
+    <p>
+      <input class="submit" type="submit" name="submit_upload" value="{'Upload'|@translate}">
+    </p>
+{elseif $upload_mode eq 'multiple'}
+    <p>
+      <input type="file" name="uploadify" id="uploadify">
+    </p>
+
+    <p><a href="{$switch_url}">{'... or switch to the old style form'|@translate}</a></p>
+
+    <div id="fileQueue"></div>
+
+    </fieldset>
+    <p>
+      <input class="submit" type="button" value="{'Upload'|@translate}">
+      <input type="submit" name="submit_upload" style="display:none">
+    </p>
+{/if}
+</form>
+{/if} {* empty($thumbnails) *}
+{/if} {* $setup_errors *}
+
+</div> <!-- photosAddContent -->
Index: /extensions/community/admin.php
===================================================================
--- /extensions/community/admin.php	(revision 9371)
+++ /extensions/community/admin.php	(revision 9372)
@@ -3,5 +3,7 @@
 // | Piwigo - a PHP based picture gallery                                  |
 // +-----------------------------------------------------------------------+
-// | Copyright(C) 2009      Pierrick LE GALL             http://piwigo.org |
+// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
 // +-----------------------------------------------------------------------+
 // | This program is free software; you can redistribute it and/or modify  |
@@ -26,122 +28,56 @@
 
 include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
+include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
+
 load_language('plugin.lang', COMMUNITY_PATH);
 
-$conf['community_permission_levels'] = array(1,2);
-$admin_base_url = get_root_url().'admin.php?page=plugin&section=community%2Fadmin.php';
+define('COMMUNITY_BASE_URL', get_root_url().'admin.php?page=plugin-community');
 
 // +-----------------------------------------------------------------------+
 // | Check Access and exit when user status is not ok                      |
 // +-----------------------------------------------------------------------+
+
 check_status(ACCESS_ADMINISTRATOR);
 
 // +-----------------------------------------------------------------------+
-// |                               functions                               |
+// | Tabs                                                                  |
 // +-----------------------------------------------------------------------+
 
-function get_permission_level_label($level)
+$tabs = array(
+  array(
+    'code' => 'permissions',
+    'label' => l10n('Upload Permissions'),
+    ),
+  array(
+    'code' => 'pendings',
+    'label' => l10n('Pending Photos'),
+    ),
+  );
+
+$tab_codes = array_map(
+  create_function('$a', 'return $a["code"];'),
+  $tabs
+  );
+
+if (isset($_GET['tab']) and in_array($_GET['tab'], $tab_codes))
 {
-  return '('.$level.') '.l10n( sprintf('Community level %d', $level) );
+  $page['tab'] = $_GET['tab'];
+}
+else
+{
+  $page['tab'] = $tabs[0]['code'];
 }
 
-// +-----------------------------------------------------------------------+
-// |                            add permissions                            |
-// +-----------------------------------------------------------------------+
-
-if (isset($_POST['submit_add']) and !is_adviser())
+$tabsheet = new tabsheet();
+foreach ($tabs as $tab)
 {
-  if (!is_numeric($_POST['user_options']))
-  {
-    array_push($page['errors'], 'invalid user');
-  }
-  if (!is_numeric($_POST['permission_level_options']))
-  {
-    array_push($page['errors'], 'invalid permission level');
-  }
-
-  if (count($page['errors']) == 0)
-  {
-    $query = '
-SELECT
-    '.$conf['user_fields']['username'].' AS username
-  FROM '.USERS_TABLE.'
-  WHERE '.$conf['user_fields']['id'].' = '.$_POST['user_options'].'
-;';
-    list($username) = mysql_fetch_row(pwg_query($query));
-    // remove any existing permission for this user
-    $query = '
-DELETE
-  FROM '.COMMUNITY_TABLE.'
-  WHERE user_id = '.$_POST['user_options'].'
-;';
-    pwg_query($query);
-
-    // creating the permission
-    $query = '
-INSERT INTO '.COMMUNITY_TABLE.'
-  (user_id, permission_level)
-  VALUES
-  ('.$_POST['user_options'].', '.$_POST['permission_level_options'].')
-;';
-    pwg_query($query);
-
-    array_push(
-      $page['infos'],
-      sprintf(
-        l10n('community permissions "%s" added/updated for "%s"'),
-        get_permission_level_label($_POST['permission_level_options']),
-        $username
-        )
-      );
-  }
-
+  $tabsheet->add(
+    $tab['code'],
+    $tab['label'],
+    COMMUNITY_BASE_URL.'-'.$tab['code']
+    );
 }
-
-// +-----------------------------------------------------------------------+
-// |                           remove permissions                          |
-// +-----------------------------------------------------------------------+
-
-if (isset($_GET['delete']) and !is_adviser())
-{
-  if (is_numeric($_GET['delete']))
-  {
-    $query = '
-SELECT
-    community.user_id,
-    community.permission_level,
-    u.'.$conf['user_fields']['username'].' AS username
-  FROM '.COMMUNITY_TABLE.' AS community
-    INNER JOIN '.USERS_TABLE.' AS u
-      ON u.'.$conf['user_fields']['id'].' = community.user_id
-  WHERE community.user_id = '.$_GET['delete'].'
-;';
-    $result = pwg_query($query);
-    if (mysql_num_rows($result) == 0)
-    {
-      array_push($page['errors'], 'this user has no community permission yet');
-    }
-
-    if (count($page['errors']) == 0)
-    {
-      list($user_id, $permission_level, $username) = mysql_fetch_row($result);
-
-      $query = '
-DELETE
-  FROM '.COMMUNITY_TABLE.'
-  WHERE user_id = '.$user_id.'
-;';
-      pwg_query($query);
-
-      array_push(
-        $page['infos'],
-        sprintf(
-          l10n('community permissions "%s" removed for "%s"'),
-          get_permission_level_label($permission_level),
-          $username
-        )
-      );
-    }
-  }
-}
+$tabsheet->select($page['tab']);
+$tabsheet->assign();
 
 // +-----------------------------------------------------------------------+
@@ -151,80 +87,12 @@
 $template->set_filenames(
   array(
-    'plugin_admin_content' => dirname(__FILE__).'/admin.tpl'
+    'photos_add' => 'photos_add_'.$page['tab'].'.tpl'
     )
   );
 
-$template->assign(
-    array(
-      'F_ADD_ACTION'=> $admin_base_url,
-    )
-  );
-
-
-// user options
-$query = '
-SELECT
-    u.'.$conf['user_fields']['id'].' AS id,
-    u.'.$conf['user_fields']['username'].' AS username
-  FROM '.USERS_TABLE.' AS u
-    INNER JOIN '.USER_INFOS_TABLE.' AS ui
-      ON u.'.$conf['user_fields']['id'].' = ui.user_id
-  WHERE ui.status = "normal"
-  ORDER BY username
-;';
-$user_options = array();
-$result = pwg_query($query);
-while ($row = mysql_fetch_assoc($result))
-{
-  $user_options[ $row['id'] ] = $row['username'];
-}
-$template->assign(
-    array(
-      'user_options'=> $user_options,
-    )
-  );
-
-  
-// permission level options
-$permission_level_options = array();
-foreach ($conf['community_permission_levels'] as $level)
-{
-  $permission_level_options[$level] = get_permission_level_label($level);
-}
-$template->assign(
-    array(
-      'permission_level_options'=> $permission_level_options,
-    )
-  );
-
-// user with community permissions
-$query = '
-SELECT
-    community.user_id,
-    community.permission_level,
-    u.'.$conf['user_fields']['username'].' AS username
-  FROM '.COMMUNITY_TABLE.' AS community
-    INNER JOIN '.USERS_TABLE.' AS u
-      ON u.'.$conf['user_fields']['id'].' = community.user_id
-  ORDER BY username
-;';
-$result = pwg_query($query);
-
-while ($row = mysql_fetch_assoc($result))
-{
-  $template->append(
-    'users',
-    array(
-      'NAME' => $row['username'],
-      'PERMISSION_LEVEL' => get_permission_level_label($row['permission_level']),
-      'U_DELETE' => $admin_base_url.'&amp;delete='.$row['user_id']
-      )
-    );
-}
-
 // +-----------------------------------------------------------------------+
-// |                           sending html code                           |
+// |                             Load the tab                              |
 // +-----------------------------------------------------------------------+
 
-$template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
+include(COMMUNITY_PATH.'admin_'.$page['tab'].'.php');
 ?>
Index: tensions/community/admin.tpl
===================================================================
--- /extensions/community/admin.tpl	(revision 9371)
+++ 	(revision )
@@ -1,50 +1,0 @@
-<div class="titrePage">
-  <h2>{'Community'|@translate}</h2>
-</div>
-
-<form method="post" name="add_permission" action="{$F_ADD_ACTION}" class="properties">
-  <fieldset>
-    <legend>{'Add permissions'|@translate}</legend>
-
-    <table>
-      <tr>
-        <td>{'User'|@translate}</td>
-        <td>
-          {html_options name="user_options" options=$user_options}
-        </td>
-      </tr>
-
-      <tr>
-        <td>{'Permission level'|@translate}</td>
-        <td>
-          {html_options name="permission_level_options" options=$permission_level_options}
-        </td>
-      </tr>
-    </table>
-    
-    <p>
-      <input class="submit" type="submit" name="submit_add" value="{'Add'|@translate}" {$TAG_INPUT_ENABLED}/>
-    </p>
-  </fieldset>
-</form>
-
-<table class="table2">
-  <tr class="throw">
-    <th>{'User'|@translate}</th>
-    <th>{'Permission level'|@translate}</th>
-    <th>{'Actions'|@translate}</th>
-  </tr>
-  {if not empty($users)}
-  {foreach from=$users item=user name=user_loop}
-  <tr class="{if $smarty.foreach.user_loop.index is odd}row1{else}row2{/if}">
-    <td>{$user.NAME}</td>
-    <td>{$user.PERMISSION_LEVEL}</td>
-    <td style="text-align:center;">
-      <a href="{$user.U_DELETE}" onclick="return confirm( document.getElementById('btn_delete').title + '\n\n' + '{'Are you sure?'|@translate|@escape:'javascript'}');">
-        <img src="{$ROOT_URL}{$themeconf.admin_icon_dir}/delete.png" class="button" style="border:none" id="btn_delete" alt="{'delete'|@translate}" title="{'delete'|@translate}" {$TAG_INPUT_ENABLED}/>
-      </a>
-    </td>
-  </tr>
-  {/foreach}
-  {/if}
-</table>
Index: /extensions/community/admin_pendings.php
===================================================================
--- /extensions/community/admin_pendings.php	(revision 9372)
+++ /extensions/community/admin_pendings.php	(revision 9372)
@@ -0,0 +1,255 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based picture gallery                                  |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+if( !defined("PHPWG_ROOT_PATH") )
+{
+  die ("Hacking attempt!");
+}
+
+include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
+include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
+load_language('plugin.lang', COMMUNITY_PATH);
+
+$admin_base_url = get_root_url().'admin.php?page=plugin-community-pendings';
+
+// +-----------------------------------------------------------------------+
+// | Check Access and exit when user status is not ok                      |
+// +-----------------------------------------------------------------------+
+
+check_status(ACCESS_ADMINISTRATOR);
+
+// +-----------------------------------------------------------------------+
+// |                                actions                                |
+// +-----------------------------------------------------------------------+
+
+if (!empty($_POST))
+{
+  if (empty($_POST['photos']))
+  {
+    array_push(
+      $page['errors'],
+      l10n('Select at least one photo')
+      );
+  }
+  else
+  {
+    check_input_parameter('photos', $_POST, true, PATTERN_ID);
+    check_input_parameter('level', $_POST, false, PATTERN_ID);
+    
+    if (isset($_POST['validate']))
+    {
+      $query = '
+UPDATE '.COMMUNITY_PENDINGS_TABLE.'
+  SET state = \'validated\',
+      validated_by = '.$user['id'].'
+  WHERE image_id IN ('.implode(',', $_POST['photos']).')
+;';
+      pwg_query($query);
+
+      $query = '
+UPDATE '.IMAGES_TABLE.'
+  SET level = '.$_POST['level'].',
+      date_available = NOW()
+  WHERE id IN ('.implode(',', $_POST['photos']).')
+;';
+      pwg_query($query);
+
+      array_push(
+        $page['infos'],
+        sprintf(
+          l10n('%d photos validated'),
+          count($_POST['photos'])
+          )
+        );
+    }
+
+    if (isset($_POST['reject']))
+    {
+      $query = '
+DELETE
+  FROM '.COMMUNITY_PENDINGS_TABLE.'
+  WHERE image_id IN ('.implode(',', $_POST['photos']).')
+;';
+      pwg_query($query);
+
+      delete_elements($_POST['photos'], true);
+
+      array_push(
+        $page['infos'],
+        sprintf(
+          l10n('%d photos rejected'),
+          count($_POST['photos'])
+          )
+        );
+    }
+
+    invalidate_user_cache();
+  }
+}
+
+// +-----------------------------------------------------------------------+
+// | template init                                                         |
+// +-----------------------------------------------------------------------+
+
+$template->set_filenames(
+  array(
+    'plugin_admin_content' => dirname(__FILE__).'/admin_pendings.tpl'
+    )
+  );
+
+// +-----------------------------------------------------------------------+
+// | pending photos list                                                   |
+// +-----------------------------------------------------------------------+
+
+$list = array();
+
+$query = '
+SELECT
+    image_id,
+    added_on,
+
+    i.id,
+    path,
+    tn_ext,
+    date_creation,
+    name,
+    comment,
+    added_by,
+    file,
+    name,
+    filesize,
+    width,
+    height,
+    has_high,
+    high_filesize,
+
+    '.$conf['user_fields']['username'].' AS username
+
+  FROM '.COMMUNITY_PENDINGS_TABLE.' AS cp
+    INNER JOIN '.IMAGES_TABLE.' AS i ON i.id = cp.image_id
+    LEFT JOIN '.USERS_TABLE.' AS u ON u.'.$conf['user_fields']['id'].' = i.added_by
+
+  WHERE state = \'moderation_pending\'
+
+  ORDER BY image_id DESC
+;';
+$result = pwg_query($query);
+$rows = array();
+$image_ids = array();
+while ($row = pwg_db_fetch_assoc($result))
+{
+  array_push($rows, $row);
+  array_push($image_ids, $row['id']);
+}
+
+$category_for_image = array();
+
+if (count($image_ids) > 0)
+{
+  $query = '
+SELECT
+    id,
+    image_id,
+    uppercats
+  FROM '.IMAGE_CATEGORY_TABLE.'
+    JOIN '.CATEGORIES_TABLE.' ON id = category_id
+  WHERE image_id IN ('.implode(',', $image_ids).')
+;';
+  $result = pwg_query($query);
+
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    $category_for_image[ $row['image_id'] ] = get_cat_display_name_cache(
+      $row['uppercats'],
+      'admin.php?page=cat_modify&amp;cat_id=',
+      false,
+      true,
+      'externalLink'
+      );
+  }
+}
+
+foreach ($rows as $row)
+{
+  $thumb = get_thumbnail_url(
+    array(
+      'id' => $row['image_id'],
+      'path' => $row['path'],
+      'tn_ext' => @$row['tn_ext']
+      )
+    );
+
+  // file properties
+  $dimensions = null;
+  $websize_props = $row['width'].'x'.$row['height'].' '.l10n('pixels').', '.sprintf(l10n('%d Kb'), $row['filesize']);
+  if (!empty($row['has_high']) and get_boolean($row['has_high']))
+  {
+    $high_path = get_high_path($row);
+    list($high_width, $high_height) = getimagesize($high_path);
+    $high_props = $high_width.'x'.$high_height.' '.l10n('pixels').', '.sprintf(l10n('%d Kb'), $row['high_filesize']);
+    
+    $dimensions = $high_props.' ('.l10n('web size').' '.$websize_props.')';
+  }
+  else
+  {
+    $dimensions = $websize_props;
+  }
+  
+  $template->append(
+    'photos',
+    array(
+      'U_EDIT' => get_root_url().'admin.php?page=picture_modify&amp;image_id='.$row['image_id'],
+      'ID' => $row['image_id'],
+      'TN_SRC' => $thumb,
+      'WEBSIZE_SRC' => $row['path'],
+      'ADDED_BY' => $row['username'],
+      'ADDED_ON' => format_date($row['added_on'], true),
+      'NAME' => get_image_name($row['name'], $row['file']),
+      'DIMENSIONS' => $dimensions,
+      'FILE' => $row['file'],
+      'DATE_CREATION' => format_date($row['date_creation']),
+      'ALBUM' => $category_for_image[ $row['id'] ],
+      )
+    );
+}
+
+// +-----------------------------------------------------------------------+
+// | form options                                                          |
+// +-----------------------------------------------------------------------+
+
+// image level options
+$selected_level = isset($_POST['level']) ? $_POST['level'] : 0;
+$template->assign(
+    array(
+      'level_options'=> get_privacy_level_options(),
+      'level_options_selected' => array($selected_level)
+    )
+  );
+
+
+// +-----------------------------------------------------------------------+
+// | sending html code                                                     |
+// +-----------------------------------------------------------------------+
+
+$template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
+?>
Index: /extensions/community/admin_pendings.tpl
===================================================================
--- /extensions/community/admin_pendings.tpl	(revision 9372)
+++ /extensions/community/admin_pendings.tpl	(revision 9372)
@@ -0,0 +1,130 @@
+{literal}
+<style>
+.rowSelected {background-color:#C2F5C2 !important}
+.comment p {text-align:left; margin:5px 0 0 5px}
+.comment table {margin:5px 0 0 0}
+.comment table th {padding-right:10px}
+</style>
+{/literal}
+
+{literal}
+<script type="text/javascript">
+$(document).ready(function(){
+
+  function checkSelectedRows() {
+    $(".checkPhoto").each(function() {
+      var row = $(this).parent("tr");
+      var checkbox = $(this).children("input[type=checkbox]");
+
+      if ($(checkbox).is(':checked')) {
+        $(row).addClass("rowSelected"); 
+      }
+      else {
+        $(row).removeClass("rowSelected"); 
+      }
+    });
+  }
+
+
+  $(".checkPhoto").click(function(event) {
+    if (event.target.type !== 'checkbox') {
+      var checkbox = $(this).children("input[type=checkbox]");
+      $(checkbox).attr('checked', !$(checkbox).is(':checked'));
+    }
+    checkSelectedRows();
+  });
+
+  $("#selectAll").click(function () {
+    $(".checkPhoto input[type=checkbox]").attr('checked', true);
+    checkSelectedRows();
+    return false;
+  });
+
+  $("#selectNone").click(function () {
+    $(".checkPhoto input[type=checkbox]").attr('checked', false);
+    checkSelectedRows();
+    return false;
+  });
+
+  $("#selectInvert").click(function () {
+    $(".checkPhoto input[type=checkbox]").each(function() {
+      $(this).attr('checked', !$(this).is(':checked'));
+    });
+    checkSelectedRows();
+    return false;
+  });
+
+});
+</script>
+{/literal}
+
+<div class="titrePage">
+  <h2>{'Pending Photos'|@translate} - {'Community'|@translate}</h2>
+</div>
+
+{if !empty($photos) }
+<form method="post" action="{$F_ACTION}">
+  
+  <fieldset>
+
+    <legend>{'Selection'|@translate}</legend>
+<table width="99%">
+  {foreach from=$photos item=photo name=photo}
+  <tr valign="top" class="{if $smarty.foreach.photo.index is odd}row2{else}row1{/if}">
+    <td style="width:50px;text-align:center" class="checkPhoto">
+      <input type="checkbox" name="photos[]" value="{$photo.ID}" style="z-index:99;display:box;float:left;">
+      <img src="{$photo.TN_SRC}" style="margin:0.5em">
+    </td>
+    <td>
+  <div class="comment">
+    <p class="commentAction" style="float:left;margin:0.5em 0 0 0.5em"><a href="{$photo.WEBSIZE_SRC}" class="externalLink">{'Zoom'|@translate}</a> &middot; <a href="{$photo.U_EDIT}" class="externalLink">{'Edit'|@translate}</a></p>
+    <p class="commentHeader"><strong>{$photo.ADDED_BY}</strong> - <em>{$photo.ADDED_ON}</em></p>
+    <table>
+      <tr>
+        <th>{'Album'|@translate}</th>
+        <td>{$photo.ALBUM}</td>
+      </tr>
+      <tr>
+        <th>{'Name'|@translate}</th>
+        <td>{$photo.NAME} ({'File'|@translate} {$photo.FILE})</td>
+      </tr>
+      <tr>
+        <th>{'Created on'|@translate}</th>
+        <td>{$photo.DATE_CREATION}</td>
+      </tr>
+      <tr>
+        <th>{'Dimensions'|@translate}</th>
+        <td>{$photo.DIMENSIONS}</td>
+      </tr>
+    </table>
+  </div>
+    </td>
+  </tr>
+  {/foreach}
+</table>
+
+  <p class="checkActions">
+    {'Select:'|@translate}
+    <a href="#" id="selectAll">{'All'|@translate}</a>,
+    <a href="#" id="selectNone">{'None'|@translate}</a>,
+    <a href="#" id="selectInvert">{'Invert'|@translate}</a>
+  </p>
+
+    </fieldset>
+
+    <fieldset>
+      <legend>{'Who can see these photos?'|@translate}</legend>
+
+      <select name="level" size="1">
+        {html_options options=$level_options selected=$level_options_selected}
+      </select>
+    </fieldset>
+
+
+  <p class="bottomButtons">
+    <input class="submit" type="submit" name="validate" value="{'Validate'|@translate}">
+    <input class="submit" type="submit" name="reject" value="{'Reject'|@translate}">
+  </p>
+
+</form>
+{/if}
Index: /extensions/community/admin_permissions.php
===================================================================
--- /extensions/community/admin_permissions.php	(revision 9372)
+++ /extensions/community/admin_permissions.php	(revision 9372)
@@ -0,0 +1,335 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based picture gallery                                  |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+if( !defined("PHPWG_ROOT_PATH") )
+{
+  die ("Hacking attempt!");
+}
+
+include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
+load_language('plugin.lang', COMMUNITY_PATH);
+
+$admin_base_url = get_root_url().'admin.php?page=plugin-community-permissions';
+
+// +-----------------------------------------------------------------------+
+// | Check Access and exit when user status is not ok                      |
+// +-----------------------------------------------------------------------+
+
+check_status(ACCESS_ADMINISTRATOR);
+
+// +-----------------------------------------------------------------------+
+// |                            add permissions                            |
+// +-----------------------------------------------------------------------+
+
+if (isset($_POST['submit_add']))
+{
+  $who_options = array('any_visitor', 'any_registered_user', 'user', 'group');
+  
+  if (!in_array($_POST['who'], $who_options))
+  {
+    die('hacking attempt: invalid "who" option');
+  }
+  
+  if ('user' == $_POST['who'])
+  {
+    check_input_parameter('who_user', $_POST, false, PATTERN_ID);
+  }
+
+  if ('group' == $_POST['who'])
+  {
+    check_input_parameter('who_group', $_POST, false, PATTERN_ID);
+  }
+
+  if (-1 != $_POST['category'])
+  {
+    check_input_parameter('category', $_POST, false, PATTERN_ID);
+  }
+
+  check_input_parameter('moderate', $_POST, false, '/^(true|false)$/');
+
+  // creating the permission
+  $insert = array(
+    'type' => $_POST['who'],
+    'group_id' => ('group' == $_POST['who']) ? $_POST['who_group'] : null,
+    'user_id' => ('user' == $_POST['who']) ? $_POST['who_user'] : null,
+    'category_id' => ($_POST['category'] > 0) ? $_POST['category'] : null,
+    'create_subcategories' => isset($_POST['create_subcategories']) ? 'true' : 'false',
+    'moderated' => $_POST['moderate'],
+    );
+  mass_inserts(
+    COMMUNITY_PERMISSIONS_TABLE,
+    array_keys($insert),
+    array($insert)
+    );
+  
+  array_push(
+    $page['infos'],
+    l10n('Permission added')
+    );
+}
+
+// +-----------------------------------------------------------------------+
+// |                           remove permissions                          |
+// +-----------------------------------------------------------------------+
+
+if (isset($_GET['delete']))
+{
+  check_input_parameter('delete', $_GET, false, PATTERN_ID);
+  
+  $query = '
+DELETE
+  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
+  WHERE id = '.$_GET['delete'].'
+;';
+  pwg_query($query);
+
+  $_SESSION['page_infos'] = array(l10n('Permission removed'));
+  redirect($admin_base_url);
+}
+
+// +-----------------------------------------------------------------------+
+// | template init                                                         |
+// +-----------------------------------------------------------------------+
+
+$template->set_filenames(
+  array(
+    'plugin_admin_content' => dirname(__FILE__).'/admin_permissions.tpl'
+    )
+  );
+
+// +-----------------------------------------------------------------------+
+// | prepare form                                                          |
+// +-----------------------------------------------------------------------+
+
+
+// list of users
+$users = array();
+
+$query = '
+SELECT
+    '.$conf['user_fields']['id'].' AS id,
+    '.$conf['user_fields']['username'].' AS username
+  FROM '.USERS_TABLE.' AS u
+    INNER JOIN '.USER_INFOS_TABLE.' AS uf ON uf.user_id = id
+  WHERE uf.status IN (\'normal\',\'generic\')
+;';
+$result = pwg_query($query);
+while ($row = pwg_db_fetch_assoc($result))
+{
+  $users[$row['id']] = $row['username'];
+}
+
+natcasesort($users);
+
+$template->assign(
+  array(
+    'user_options' => $users,
+    )
+  );
+
+// list of groups
+$query = '
+SELECT
+    id,
+    name
+  FROM '.GROUPS_TABLE.'
+;';
+$result = pwg_query($query);
+while ($row = pwg_db_fetch_assoc($result))
+{
+  $groups[$row['id']] = $row['name'];
+}
+
+natcasesort($groups);
+
+$template->assign(
+  array(
+    'group_options' => $groups,
+    )
+  );
+
+
+$template->assign(
+  array(
+    'F_ADD_ACTION' => COMMUNITY_BASE_URL.'-'.$page['tab'],
+    )
+  );
+
+// list of albums
+$query = '
+SELECT id,name,uppercats,global_rank
+  FROM '.CATEGORIES_TABLE.'
+;';
+
+display_select_cat_wrapper(
+  $query,
+  array(),
+  'category_options'
+  );
+
+// +-----------------------------------------------------------------------+
+// | permission list                                                       |
+// +-----------------------------------------------------------------------+
+
+// user with community permissions
+$query = '
+SELECT
+    *
+  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
+  ORDER BY id DESC
+;';
+$result = pwg_query($query);
+
+$permissions = array();
+$user_ids = array();
+$group_ids = array();
+$category_ids = array();
+
+while ($row = mysql_fetch_assoc($result))
+{
+  array_push($permissions, $row);
+
+  if (!empty($row['user_id']))
+  {
+    array_push($user_ids, $row['user_id']);
+  }
+
+  if (!empty($row['group_id']))
+  {
+    array_push($group_ids, $row['group_id']);
+  }
+
+  if (!empty($row['category_id']))
+  {
+    array_push($category_ids, $row['category_id']);
+  }
+}
+
+if (!empty($user_ids))
+{
+  $query = '
+SELECT
+    '.$conf['user_fields']['id'].' AS id,
+    '.$conf['user_fields']['username'].' AS username
+  FROM '.USERS_TABLE.'
+  WHERE '.$conf['user_fields']['id'].' IN ('.implode(',', $user_ids).')
+;';
+  $result = pwg_query($query);
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    $name_of_user[ $row['id'] ] = $row['username'];
+  }
+}
+
+if (!empty($group_ids))
+{
+  $query = '
+SELECT
+    id,
+    name
+  FROM '.GROUPS_TABLE.'
+  WHERE id IN ('.implode(',', $group_ids).')
+;';
+  $result = pwg_query($query);
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    $name_of_group[ $row['id'] ] = $row['name'];
+  }
+}
+
+if (!empty($category_ids))
+{
+  $query = '
+SELECT
+    id,
+    uppercats
+  FROM '.CATEGORIES_TABLE.'
+  WHERE id IN ('.implode(',', $category_ids).')
+;';
+  $result = pwg_query($query);
+
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    $name_of_category[ $row['id'] ] = get_cat_display_name_cache(
+      $row['uppercats'],
+      null,
+      false
+      );
+  }
+}
+
+foreach ($permissions as $permission)
+{
+  $where = l10n('The whole gallery');
+  if (isset($permission['category_id']))
+  {
+    $where = $name_of_category[ $permission['category_id'] ];
+  }
+
+  $who = l10n('any visitor');
+  if ('any_registered_user' == $permission['type'])
+  {
+    $who = l10n('any registered user');
+  }
+  elseif ('user' == $permission['type'])
+  {
+    $who = sprintf(
+      l10n('%s (the user)'),
+      $name_of_user[$permission['user_id']]
+      );
+  }
+  elseif ('group' == $permission['type'])
+  {
+    $who = sprintf(
+      l10n('%s (the group)'),
+      $name_of_group[$permission['group_id']]
+      );
+  }
+
+  $trust = l10n('low trust');
+  $trust_tooltip = l10n('uploaded photos must be validated by an administrator');
+  if ('false' == $permission['moderated'])
+  {
+    $trust = l10n('high trust');
+    $trust_tooltip = l10n('uploaded photos are directly displayed in the gallery');
+  }
+  
+  $template->append(
+    'permissions',
+    array(
+      'WHO' => $who,
+      'WHERE' => $where,
+      'TRUST' => $trust,
+      'TRUST_TOOLTIP' => $trust_tooltip,
+      'CREATE_SUBCATEGORIES' => get_boolean($permission['create_subcategories']),
+      'U_DELETE' => $admin_base_url.'&amp;delete='.$permission['id']
+      )
+    );
+}
+
+// +-----------------------------------------------------------------------+
+// | sending html code                                                     |
+// +-----------------------------------------------------------------------+
+
+$template->assign_var_from_handle('ADMIN_CONTENT', 'plugin_admin_content');
+?>
Index: /extensions/community/admin_permissions.tpl
===================================================================
--- /extensions/community/admin_permissions.tpl	(revision 9372)
+++ /extensions/community/admin_permissions.tpl	(revision 9372)
@@ -0,0 +1,102 @@
+{literal}
+<style>
+form fieldset p {text-align:left;margin:0 0 1.5em 0;line-height:20px;}
+</style>
+{/literal}
+
+{footer_script}{literal}
+$(document).ready(function() {
+  $("select[name=who]").click(function () {
+    $("[name^=who_]").hide();
+    $("[name=who_"+$(this).attr("value")+"]").show();
+  });
+
+  $("#displayForm").click(function() {
+    $("[name=add_permission]").show();
+    $(this).hide();
+    return false;
+  });
+});
+{/literal}{/footer_script}
+
+
+<div class="titrePage">
+  <h2>{'Upload Permissions'|@translate} - {'Community'|@translate}</h2>
+</div>
+
+<a id="displayForm" href="#">{'Add a permission'|@translate}</a>
+
+<form method="post" name="add_permission" action="{$F_ADD_ACTION}" class="properties" style="display:none">
+  <fieldset>
+    <legend>{'Add a permission'|@translate}</legend>
+
+    <p>
+      <strong>{'Who?'|@translate}</strong>
+      <br>
+      <select name="who">
+        <option value="any_visitor">{'any visitor'|@translate}</option>
+        <option value="any_registered_user">{'any registered user'|@translate}</option>
+        <option value="user">{'a specific user'|@translate}</option>
+        <option value="group">{'a group'|@translate}</option>
+      </select>
+
+      <select name="who_user" style="display:none">
+{html_options options=$user_options selected=$user_options_selected}
+      </select>
+
+      <select name="who_group" style="display:none">
+{html_options options=$group_options selected=$group_options_selected}
+      </select>
+    </p>
+
+    <p>
+      <strong>{'Where?'|@translate}</strong>
+      <br>
+      <select class="categoryDropDown" name="category">
+        <option value="0">{'The whole gallery'|@translate}</option>
+        <option disabled="disabled">------------</option>
+        {html_options options=$category_options selected=$category_options_selected}
+      </select>
+      <br>
+      <label><input type="checkbox" name="create_subcategories"> {'ability to create sub-albums'|@translate}</label>
+    </p>
+
+    <p>
+      <strong>{'Which level of trust?'|@translate}</strong>
+      <br><label><input type="radio" name="moderate" value="true" checked="checked"> <em>{'low trust'|@translate}</em> : {'uploaded photos must be validated by an administrator'|@translate}</label>
+      <br><label><input type="radio" name="moderate" value="false"> <em>{'high trust'|@translate}</em> : {'uploaded photos are directly displayed in the gallery'|@translate}</label>
+    </p>
+    
+    <p style="margin:0;">
+      <input class="submit" type="submit" name="submit_add" value="{'Add'|@translate}"/>
+    </p>
+  </fieldset>
+</form>
+
+<table class="table2" style="margin:15px auto;">
+  <tr class="throw">
+    <th>{'Who?'|@translate}</th>
+    <th>{'Where?'|@translate}</th>
+    <th>{'Options'|@translate}</th>
+    <th>{'Actions'|@translate}</th>
+  </tr>
+{if not empty($permissions)}
+  {foreach from=$permissions item=permission name=permission_loop}
+  <tr class="{if $smarty.foreach.permission_loop.index is odd}row1{else}row2{/if}">
+    <td>{$permission.WHO}</td>
+    <td>{$permission.WHERE}</td>
+    <td>
+      <span title="{$permission.TRUST_TOOLTIP}">{$permission.TRUST}</span>
+    {if $permission.CREATE_SUBCATEGORIES}
+, {'sub-albums creation'|@translate}
+    {/if}
+    </td>
+    <td style="text-align:center;">
+      <a href="{$permission.U_DELETE}" onclick="return confirm( document.getElementById('btn_delete').title + '\n\n' + '{'Are you sure?'|@translate|@escape:'javascript'}');">
+        <img src="{$ROOT_URL}{$themeconf.admin_icon_dir}/delete.png" class="button" style="border:none" id="btn_delete" alt="{'delete'|@translate}" title="{'delete'|@translate}" />
+      </a>
+    </td>
+  </tr>
+  {/foreach}
+{/if}
+</table>
Index: tensions/community/include/constants.php
===================================================================
--- /extensions/community/include/constants.php	(revision 9371)
+++ 	(revision )
@@ -1,4 +1,0 @@
-<?php
-global $prefixeTable;
-define('COMMUNITY_TABLE', $prefixeTable.'community');
-?>
Index: /extensions/community/include/functions_community.inc.php
===================================================================
--- /extensions/community/include/functions_community.inc.php	(revision 9372)
+++ /extensions/community/include/functions_community.inc.php	(revision 9372)
@@ -0,0 +1,107 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based photo gallery                                    |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+function community_get_user_permissions($user_id)
+{
+  global $conf;
+
+  $return = array(
+    'upload_whole_gallery' => false,
+    'create_whole_gallery' => false,
+    'create_categories' => array(),
+    'upload_categories' => array(),
+    'permission_ids' => array(),
+    );
+
+  $user_permissions = array();
+  
+  // what are the user groups?
+  $query = '
+SELECT
+    group_id
+  FROM '.USER_GROUP_TABLE.'
+  WHERE user_id = '.$user_id.'
+;';
+  $user_group_ids = array_from_query($query, 'group_id');
+
+  $query = '
+SELECT
+    id,
+    category_id,
+    create_subcategories
+  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
+  WHERE (type = \'any_visitor\')';
+
+  if ($user_id != $conf['guest_id'])
+  {
+  $query.= '
+    OR (type = \'any_registered_user\')
+    OR (type = \'user\' AND user_id = '.$user_id.')
+    OR (type = \'group\' AND group_id IN ('.implode(',', $user_group_ids).'))
+';
+  }
+    
+  $query.= '
+;';
+
+  $result = pwg_query($query);
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    array_push($return['permission_ids'], $row['id']);
+    
+    if (empty($row['category_id']))
+    {
+      $return ['upload_whole_gallery'] = true;
+    }
+    else
+    {
+      array_push($return['upload_categories'], $row['category_id']);
+    }
+
+    if ('true' == $row['create_subcategories'])
+    {
+      if (empty($row['category_id']))
+      {
+        $return ['create_whole_gallery'] = true;
+      }
+      else
+      {
+        array_push($return['create_categories'], $row['category_id']);
+      }
+    }
+  }
+
+  if (!$return['upload_whole_gallery'])
+  {
+    $return['upload_categories'] = get_subcat_ids($return['upload_categories']);
+  }
+
+  if (!$return ['create_whole_gallery'] and count($return['create_categories']) > 0)
+  {
+    $return['create_categories'] = get_subcat_ids($return['create_categories']);
+  }
+
+  return $return;
+}
+
+?>
Index: /extensions/community/language/en_UK/plugin.lang.php
===================================================================
--- /extensions/community/language/en_UK/plugin.lang.php	(revision 9371)
+++ /extensions/community/language/en_UK/plugin.lang.php	(revision 9372)
@@ -20,10 +20,33 @@
 // +-----------------------------------------------------------------------+
 
-$lang['Community'] = 'Community';
-$lang['Add permissions'] = 'Add permissions';
-$lang['Permission level'] = 'Permission level';
-$lang['Community level 1'] = 'add photos';
-$lang['Community level 2'] = 'add photos + categories';
-$lang['community permissions "%s" added/updated for "%s"'] = 'community permissions "%s" added/updated for "%s"';
-$lang['community permissions "%s" removed for "%s"'] = 'community permissions "%s" removed for "%s"';
+$lang['Add a permission'] = 'Add a permission';
+$lang['Who?'] = 'Who?';
+$lang['any visitor'] = 'any visitor';
+$lang['any registered user'] = 'any registered user';
+$lang['a specific user'] = 'a specific user';
+$lang['a group'] = 'a group';
+$lang['Where?'] = 'Where?';
+$lang['The whole gallery'] = 'The whole gallery';
+$lang['ability to create sub-albums'] = 'ability to create sub-albums';
+$lang['Which level of trust?'] = 'Which level of trust?';
+$lang['sub-albums creation'] = 'sub-albums creation';
+$lang['Upload Permissions'] = 'Upload Permissions';
+$lang['Pending Photos'] = 'Pending Photos';
+$lang['Permission added'] = 'Permission added';
+$lang['Permission removed'] = 'Permission removed';
+$lang['%s (the user)'] = '%s (the user)';
+$lang['%s (the group)'] = '%s (the group)';
+$lang['low trust'] = 'low trust';
+$lang['uploaded photos must be validated by an administrator'] = 'uploaded photos must be validated by an administrator';
+$lang['high trust'] = 'high trust';
+$lang['uploaded photos are directly displayed in the gallery'] = 'uploaded photos are directly displayed in the gallery';
+$lang['%d photos validated'] = '%d photos validated';
+$lang['%d photos rejected'] = '%d photos rejected';
+$lang['web size'] = 'web size';
+$lang['Zoom'] = 'Zoom';
+$lang['Upload your own photos'] = 'Upload your own photos';
+$lang['%d photos uploaded by %s'] = '%d photos uploaded by %s';
+$lang['Validation page: %s'] = 'Validation page: %s';
+$lang['%d photos uploaded into album "%s"'] = '%d photos uploaded into album "%s"';
+$lang['Hi administrators,'] = 'Hi administrators,';
 ?>
Index: /extensions/community/language/fr_FR/description.txt
===================================================================
--- /extensions/community/language/fr_FR/description.txt	(revision 9371)
+++ /extensions/community/language/fr_FR/description.txt	(revision 9372)
@@ -1,1 +1,1 @@
-Permettre à des utilisateurs d'ajouter des photos avec pLoader
+Permet aux utilisateurs d'ajouter des photos sans être administrateur
Index: /extensions/community/language/fr_FR/plugin.lang.php
===================================================================
--- /extensions/community/language/fr_FR/plugin.lang.php	(revision 9371)
+++ /extensions/community/language/fr_FR/plugin.lang.php	(revision 9372)
@@ -3,5 +3,7 @@
 // | Piwigo - a PHP based picture gallery                                  |
 // +-----------------------------------------------------------------------+
-// | Copyright(C) 2009      Pierrick LE GALL             http://piwigo.org |
+// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
 // +-----------------------------------------------------------------------+
 // | This program is free software; you can redistribute it and/or modify  |
@@ -20,10 +22,33 @@
 // +-----------------------------------------------------------------------+
 
-$lang['Community'] = 'Communauté';
-$lang['Add permissions'] = 'Ajouter des permissions';
-$lang['Permission level'] = 'Niveau de permission';
-$lang['Community level 1'] = 'ajouter des photos';
-$lang['Community level 2'] = 'ajouter des photos + categories';
-$lang['community permissions "%s" added/updated for "%s"'] = 'permissions communautaires "%s" ajoutées ou mises à jour pour "%s"';
-$lang['community permissions "%s" removed for "%s"'] = 'permissions communautaires "%s" supprimées pour "%s"';
+$lang['Add a permission'] = 'Ajouter une permission';
+$lang['Who?'] = 'Qui ?';
+$lang['any visitor'] = 'n\'importe quel visiteur';
+$lang['any registered user'] = 'n\'importe quel utilisateur enregistré';
+$lang['a specific user'] = 'un utilisateur en particulier';
+$lang['a group'] = 'un groupe';
+$lang['Where?'] = 'Où ?';
+$lang['The whole gallery'] = 'La galerie toute entière';
+$lang['ability to create sub-albums'] = 'possibilité de créer des sous-albums';
+$lang['Which level of trust?'] = 'Quel degré de confiance ?';
+$lang['sub-albums creation'] = 'création de sous-albums';
+$lang['Upload Permissions'] = 'Permissions d\'ajout';
+$lang['Pending Photos'] = 'Photos en attente';
+$lang['Permission added'] = 'Permission enregistrée';
+$lang['Permission removed'] = 'Permission supprimée';
+$lang['%s (the user)'] = '%s (l\'utilisateur)';
+$lang['%s (the group)'] = '%s (le groupe)';
+$lang['low trust'] = 'confiance faible';
+$lang['uploaded photos must be validated by an administrator'] = 'les photos ajoutées doivent être validées par un administrateur';
+$lang['high trust'] = 'confiance élevée';
+$lang['uploaded photos are directly displayed in the gallery'] = 'les photos ajoutées sont directement visibles dans la galerie';
+$lang['%d photos validated'] = '%d photos validées';
+$lang['%d photos rejected'] = '%d photos rejetées';
+$lang['web size'] = 'taille web';
+$lang['Zoom'] = 'Zoom';
+$lang['Upload your own photos'] = 'Ajoutez vos propres photos';
+$lang['%d photos uploaded by %s'] = '%d photos ajoutées par %s';
+$lang['Validation page: %s'] = 'Page de validation : %s';
+$lang['%d photos uploaded into album "%s"'] = '%d photos ajoutée à l\'album "%s"';
+$lang['Hi administrators,'] = 'Bonjours chers administrateurs,';
 ?>
Index: /extensions/community/main.inc.php
===================================================================
--- /extensions/community/main.inc.php	(revision 9371)
+++ /extensions/community/main.inc.php	(revision 9372)
@@ -15,5 +15,9 @@
 
 define('COMMUNITY_PATH' , PHPWG_PLUGINS_PATH.basename(dirname(__FILE__)).'/');
-include_once (COMMUNITY_PATH.'/include/constants.php');
+
+global $prefixeTable;
+define('COMMUNITY_TABLE', $prefixeTable.'community');
+define('COMMUNITY_PERMISSIONS_TABLE', $prefixeTable.'community_permissions');
+define('COMMUNITY_PENDINGS_TABLE', $prefixeTable.'community_pendings');
 
 /* Plugin admin */
@@ -26,5 +30,5 @@
     array(
       'NAME' => 'Community',
-      'URL'  => get_admin_plugin_menu_link(dirname(__FILE__).'/admin.php')
+      'URL'  => get_root_url().'admin.php?page=plugin-community'
       )
     );
@@ -32,4 +36,93 @@
   return $menu;
 }
+
+add_event_handler('loc_end_section_init', 'community_section_init');
+function community_section_init()
+{
+  global $tokens, $page;
+  
+  if ($tokens[0] == 'add_photos')
+  {
+    $page['section'] = 'add_photos';
+  }
+}
+
+add_event_handler('loc_end_index', 'community_index');
+function community_index()
+{
+  global $page;
+  
+  if (isset($page['section']) and $page['section'] == 'add_photos')
+  {
+    include(COMMUNITY_PATH.'add_photos.php');
+  }
+}
+
+add_event_handler('blockmanager_apply' , 'community_gallery_menu');
+function community_gallery_menu($menu_ref_arr)
+{
+  global $conf, $user;
+
+  // conditional : depending on community permissions, display the "Add
+  // photos" link in the gallery menu
+  
+  // admins are not concerned about community permissions
+  if (!is_admin())
+  {
+    // what are the user groups?
+    $query = '
+SELECT
+    group_id
+  FROM '.USER_GROUP_TABLE.'
+  WHERE user_id = '.$user['id'].'
+;';
+    $user_group_ids = array_from_query($query, 'group_id');
+
+    $query = '
+SELECT
+    COUNT(*)
+  FROM '.COMMUNITY_PERMISSIONS_TABLE.'
+  WHERE (type = \'any_visitor\')';
+
+    if ($user['id'] != $conf['guest_id'])
+    {
+      $query.= '
+    OR (type = \'any_registered_user\')
+    OR (type = \'user\' AND user_id = '.$user['id'].')
+    OR (type = \'group\' AND group_id IN ('.implode(',', $user_group_ids).'))
+';
+    }
+    
+    $query.= '
+;';
+
+    list($counter) = pwg_db_fetch_row(pwg_query($query));
+    if (0 == $counter)
+    {
+      return;
+    }
+  }
+
+  $menu = & $menu_ref_arr[0];
+
+  if (($block = $menu->get_block('mbMenu')) != null )
+  {
+    load_language('plugin.lang', COMMUNITY_PATH);
+
+    array_splice(
+      $block->data,
+      count($block->data),
+      0,
+      array(
+        '' => array(
+          'URL' => make_index_url(array('section' => 'add_photos')),
+          'TITLE' => l10n('Upload your own photos'),
+          'NAME' => l10n('Upload Photos')
+          )
+        )
+      );
+  }
+}
+
 
 add_event_handler('ws_invoke_allowed', 'community_switch_user_to_admin', EVENT_HANDLER_PRIORITY_NEUTRAL, 3);
Index: /extensions/community/maintain.inc.php
===================================================================
--- /extensions/community/maintain.inc.php	(revision 9371)
+++ /extensions/community/maintain.inc.php	(revision 9372)
@@ -10,17 +10,94 @@
 function plugin_install()
 {
-  $query = "
-CREATE TABLE IF NOT EXISTS ".COMMUNITY_TABLE." (
-  user_id smallint(5) NOT NULL default '0',
-  permission_level tinyint NOT NULL default 1,
-  PRIMARY KEY  (user_id)
+  global $conf, $prefixeTable;
+
+  if ('mysql' == $conf['dblayer'])
+  {
+    $query = '
+CREATE TABLE '.$prefixeTable.'community_permissions (
+  id int(11) NOT NULL AUTO_INCREMENT,
+  type varchar(255) NOT NULL,
+  group_id smallint(5) unsigned DEFAULT NULL,
+  user_id smallint(5) DEFAULT NULL,
+  category_id smallint(5) unsigned DEFAULT NULL,
+  create_subcategories enum(\'true\',\'false\') NOT NULL DEFAULT \'false\',
+  moderated enum(\'true\',\'false\') NOT NULL DEFAULT \'true\',
+  PRIMARY KEY (id)
+) ENGINE=MyISAM DEFAULT CHARACTER SET utf8
+;';
+    pwg_query($query);
+
+    $query = '
+CREATE TABLE '.$prefixeTable.'community_pendings (
+  image_id mediumint(8) unsigned NOT NULL,
+  state varchar(255) NOT NULL,
+  added_on datetime NOT NULL,
+  validated_by smallint(5) DEFAULT NULL
+) ENGINE=MyISAM DEFAULT CHARACTER SET utf8
+;';
+    pwg_query($query);
+  }
+  elseif ('pgsql' == $conf['dblayer'])
+  {
+    $query = '
+CREATE TABLE "'.$prefixeTable.'community_permissions" (
+  "id" serial NOT NULL,
+  "type" VARCHAR(255) NOT NULL,
+  "group_id" INTEGER,
+  "user_id" INTEGER,
+  "category_id" INTEGER,
+  "create_subcategories" BOOLEAN default false,
+  "moderated" BOOLEAN default true,
+  PRIMARY KEY ("id")
 )
-;";
-  pwg_query($query);
+;';
+    pwg_query($query);
+
+    $query = '
+CREATE TABLE "'.$prefixeTable.'community_pendings" (
+  image_id INTEGER NOT NULL,
+  state VARCHAR(255) NOT NULL,
+  added_on TIMESTAMP NOT NULL,
+  validated_by INTEGER
+)
+;';
+    pwg_query($query);
+  }
+  else
+  {
+    $query = '
+CREATE TABLE "'.$prefixeTable.'community_permissions" (
+  "id" INTEGER NOT NULL,
+  "type" VARCHAR(255) NOT NULL,
+  "group_id" INTEGER,
+  "user_id" INTEGER,
+  "category_id" INTEGER,
+  "create_subcategories" BOOLEAN default false,
+  "moderated" BOOLEAN default true,
+  PRIMARY KEY ("id")
+)
+;';
+    pwg_query($query);
+
+    $query = '
+CREATE TABLE "'.$prefixeTable.'community_pendings" (
+  image_id INTEGER NOT NULL,
+  state VARCHAR(255) NOT NULL,
+  added_on TIMESTAMP NOT NULL,
+  validated_by INTEGER
+)
+;';
+    pwg_query($query);
+  }
 }
 
 function plugin_uninstall()
 {
-  $query = 'DROP TABLE '.COMMUNITY_TABLE.';';
+  global $prefixeTable;
+  
+  $query = 'DROP TABLE '.$prefixeTable.'community_permissions;';
+  pwg_query($query);
+
+  $query = 'DROP TABLE '.$prefixeTable.'community_pendings;';
   pwg_query($query);
 }
