Bonjour,

voici le diff pour les plugin appliances et databases pour la 0.85
(inclu le code pour utiliser le multi-item de la 0.85 avec mon patch
envoyé la semaine dernière)


David
++
Index: front/database.form.php
===================================================================
--- front/database.form.php	(revision 171)
+++ front/database.form.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -37,72 +37,74 @@
 
 if (isset($_POST["add"])) {
 
-	$database->check(-1,'w',$_POST);
+	$database->check(-1, CREATE,$_POST);
    $newID=$database->add($_POST);
 	Html::back();
-	
+
 } else if (isset($_POST["delete"])) {
 
-	$database->check($_POST['id'],'w');
+	$database->check($_POST['id'], DELETE);
    $database->delete($_POST);
 	$database->redirectToList();
-	
+
 } else if (isset($_POST["restore"])) {
 
-	$database->check($_POST['id'],'w');
+	$database->check($_POST['id'], PURGE);
    $database->restore($_POST);
 	$database->redirectToList();
-	
+
 } else if (isset($_POST["purge"])) {
 
-	$database->check($_POST['id'],'w');
+	$database->check($_POST['id'], PURGE);
    $database->delete($_POST,1);
 	$database->redirectToList();
-	
+
 } else if (isset($_POST["update"])) {
 
-	$database->check($_POST['id'],'w');
+	$database->check($_POST['id'], UPDATE);
    $database->update($_POST);
 	Html::back();
-	
+
 } else if (isset($_POST["additem"])) {
 
 	if (!empty($_POST['itemtype'])&&$_POST['items_id']>0) {
-      $database_item->check(-1,'w',$_POST);
+      $database_item->check(-1, CREATE, $_POST);
       $database_item->addItem($_POST);
 	}
 	Html::back();
-	
+
 } else if (isset($_POST["deleteitem"])) {
 
 	foreach ($_POST["item"] as $key => $val) {
          $input = array('id' => $key);
          if ($val==1) {
-            $database_item->check($key,'w');
+            $database_item->check($key, PURGE);
             $database_item->delete($input);
          }
 		}
 	Html::back();
-	
+
 } else if (isset($_POST["deletedatabases"])) {
 
 	$input = array('id' => $_POST["id"]);
-   $database_item->check($_POST["id"],'w');
+   $database_item->check($_POST["id"], PURGE);
 	$database_item->delete($input);
 	Html::back();
-	
+
 } else {
 
-	$database->checkGlobal("r");
-	
+	$database->checkGlobal(READ);
+
 	$plugin = new Plugin();
-	if ($plugin->isActivated("environment"))
-		Html::header(PluginDatabasesDatabase::getTypeName(2),'',"plugins","environment","databases");
-	else
-		Html::header(PluginDatabasesDatabase::getTypeName(2),'',"plugins","databases");
+	if ($plugin->isActivated("environment")) {
+      Html::header(PluginDatabasesDatabase::getTypeName(2),
+                     '',"assets","pluginenvironmentdisplay","databases");
+   } else {
+      Html::header(PluginDatabasesDatabase::getTypeName(2), '', "assets",
+                   "plugindatabasesmenu");
+   }
+	$database->display($_GET);
 
-	$database->showForm($_GET["id"]);
-
 	Html::footer();
 }
 
Index: front/database.php
===================================================================
--- front/database.php	(revision 171)
+++ front/database.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -30,17 +30,16 @@
 include ('../../../inc/includes.php');
 
 $plugin = new Plugin();
-if ($plugin->isActivated("environment"))
-	Html::header(PluginDatabasesDatabase::getTypeName(2),'',"plugins","environment","databases");
-else
-	Html::header(PluginDatabasesDatabase::getTypeName(2),'',"plugins","databases");
-
+if ($plugin->isActivated("environment")) {
+   Html::header(PluginWebapplicationsWebapplication::getTypeName(2)
+                  ,'',"assets","pluginenvironmentdisplay","databases");
+} else {
+   Html::header(PluginDatabasesDatabase::getTypeName(2), '', "assets","plugindatabasesmenu");
+}
 $database = new PluginDatabasesDatabase();
 
-if ($database->canView() || Session::haveRight("config","w")) {
-
+if ($database->canView() || Session::haveRight("config", UPDATE)) {
 	Search::show('PluginDatabasesDatabase');
-
 } else {
 	Html::displayRightError();
 }
Index: hook.php
===================================================================
--- hook.php	(revision 171)
+++ hook.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -29,16 +29,16 @@
 
 function plugin_databases_install() {
    global $DB;
-   
+
    include_once (GLPI_ROOT."/plugins/databases/inc/profile.class.php");
-   
+
    $update=false;
    if (!TableExists("glpi_plugin_sgbd") && !TableExists("glpi_plugin_databases_databases")) {
-      
+
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/empty-1.5.0.sql");
 
    } else if (TableExists("glpi_plugin_sgbd") && !TableExists("glpi_plugin_sgbd_instances")) {
-      
+
       $update=true;
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.1.sql");
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.2.0.sql");
@@ -46,7 +46,7 @@
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.3.0.sql");
 
    } else if (TableExists("glpi_plugin_sgbd") && !TableExists("glpi_dropdown_plugin_sgbd_category")) {
-      
+
       $update=true;
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.2.0.sql");
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.2.1.sql");
@@ -53,24 +53,24 @@
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.3.0.sql");
 
    } else if (TableExists("glpi_plugin_sgbd") && !FieldExists("glpi_plugin_sgbd","helpdesk_visible")) {
-      
+
       $update=true;
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.2.1.sql");
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.3.0.sql");
 
    } else if (!TableExists("glpi_plugin_databases_databases")) {
-      
+
       $update=true;
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.3.0.sql");
 
    }
    //from 1.3 version
-   if (TableExists("glpi_plugin_databases_databases") 
+   if (TableExists("glpi_plugin_databases_databases")
       && !FieldExists("glpi_plugin_databases_databases","users_id_tech")) {
       $DB->runFile(GLPI_ROOT ."/plugins/databases/sql/update-1.5.0.sql");
    }
-   
-   
+
+
    if ($update) {
       $query_="SELECT *
             FROM `glpi_plugin_databases_profiles` ";
@@ -85,11 +85,11 @@
 
          }
       }
-      
+
       $query="ALTER TABLE `glpi_plugin_databases_profiles`
                DROP `name` ;";
       $result=$DB->query($query);
-      
+
       $query = "SELECT `entities_id`,`is_recursive`,`id` FROM `glpi_plugin_databases_databases` ";
       $result = $DB->query($query);
       $number = $DB->numrows($result);
@@ -100,7 +100,7 @@
                   AND `is_recursive` = '".$data["is_recursive"]."'
                   WHERE `plugin_databases_databases_id` = '".$data["id"]."' ";
             $DB->query($query) or die($DB->error());
-            
+
             $query = "UPDATE `glpi_plugin_databases_scripts`
                   SET `entities_id` = '".$data["entities_id"]."'
                   AND `is_recursive` = '".$data["is_recursive"]."'
@@ -108,19 +108,19 @@
             $DB->query($query) or die($DB->error());
          }
       }
-      
+
       Plugin::migrateItemType(
          array(2400=>'PluginDatabasesDatabase'),
          array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences",
                "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"),
          array("glpi_plugin_databases_databases_items"));
-      
+
       Plugin::migrateItemType(
          array(1200 => "PluginAppliancesAppliance",1300 => "PluginWebapplicationsWebapplication"),
          array("glpi_plugin_databases_databases_items"));
 	}
-	
-   PluginDatabasesProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
+
+   PluginDatabasesProfile::initProfile($_SESSION['glpiactiveprofile']['id']);
    return true;
 }
 
@@ -136,11 +136,11 @@
 					"glpi_plugin_databases_scripts",
 					"glpi_plugin_databases_databases_items",
 					"glpi_plugin_databases_profiles");
-  
+
    foreach($tables as $table)
 		$DB->query("DROP TABLE IF EXISTS `$table`;");
-   
-   //old versions	
+
+   //old versions
    $tables = array("glpi_plugin_sgbd",
 					"glpi_dropdown_plugin_sgbd_type",
 					"glpi_dropdown_plugin_sgbd_server_type",
@@ -153,7 +153,7 @@
 
 	foreach($tables as $table)
 		$DB->query("DROP TABLE IF EXISTS `$table`;");
-		
+
    $tables_glpi = array("glpi_displaypreferences",
 					"glpi_documents_items",
 					"glpi_bookmarks",
@@ -186,12 +186,128 @@
 
 function plugin_databases_AssignToTicket($types) {
 
-	if (plugin_databases_haveRight("open_ticket","1"))
+   if (Session::haveRight("plugin_databases_open_ticket", "1")) {
 		$types['PluginDatabasesDatabase']=PluginDatabasesDatabase::getTypeName(2);
-
+      $types['PluginDatabasesDatabase_Item'] = _n('Database item', 'Databases item', 2, 'databases');
+   }
 	return $types;
 }
 
+
+function plugin_databases_AssignToTicketDropdown($data) {
+   global $DB, $CFG_GLPI;
+
+   if ($data['itemtype'] == 'PluginDatabasesDatabase') {
+      $table = getTableForItemType($data["itemtype"]);
+      $rand = mt_rand();
+      $field_id = Html::cleanId("dropdown_".$data['myname'].$rand);
+
+      $p = array('itemtype'            => $data["itemtype"],
+                 'entity_restrict'     => $data['entity_restrict'],
+                 'table'               => $table,
+                 'myname'              => $data["myname"]);
+
+      if(isset($data["used"]) && !empty($data["used"])){
+         if(isset($data["used"][$data["itemtype"]])){
+            $p["used"] = $data["used"][$data["itemtype"]];
+         }
+      }
+
+      echo Html::jsAjaxDropdown($data['myname'], $field_id,
+                                 $CFG_GLPI['root_doc']."/ajax/getDropdownFindNum.php",
+                                 $p);
+      // Auto update summary of active or just solved tickets
+      $params = array('items_id' => '__VALUE__',
+                      'itemtype' => $data['itemtype']);
+
+      Ajax::updateItemOnSelectEvent($field_id,"item_ticket_selection_information",
+                                    $CFG_GLPI["root_doc"]."/ajax/ticketiteminformation.php",
+                                    $params);
+
+   } else if ($data['itemtype'] == 'PluginDatabasesDatabase_Item') {
+      $sql = "SELECT `glpi_plugin_databases_databases`.`name`, "
+              . "    `items_id`, `itemtype`, `glpi_plugin_databases_databases_items`.`id` "
+              . " FROM `glpi_plugin_databases_databases_items`"
+              . " LEFT JOIN `glpi_plugin_databases_databases`"
+              . "    ON `plugin_databases_databases_id` = `glpi_plugin_databases_databases`.`id`";
+
+      $result = $DB->query($sql);
+      $elements = array();
+      while ($res = $DB->fetch_array($result)) {
+         $itemtype = $res['itemtype'];
+         $item = new $itemtype;
+         $item->getFromDB($res['items_id']);
+         $elements[$res['name']][$res['id']] = $item->getName();
+      }
+      Dropdown::showFromArray('items_id', $elements, array());
+   }
+}
+
+
+function plugin_databases_AssignToTicketDisplay($data) {
+   global $DB;
+
+   if ($data['itemtype'] == 'PluginDatabasesDatabase_Item') {
+      $paDatabase = new PluginDatabasesDatabase();
+      $item = new PluginDatabasesDatabase_Item();
+      $itemtype = $data['data']['itemtype'];
+      $iteminv = new $itemtype;
+      $iteminv->getFromDB($data['data']['items_id']);
+      $paDatabase->getFromDB($data['data']['plugin_databases_databases_id']);
+
+      echo "<tr class='tab_bg_1'>";
+      if ($data['canedit']) {
+         echo "<td width='10'>";
+         Html::showMassiveActionCheckBox('Item_Ticket', $data['data']["IDD"]);
+         echo "</td>";
+      }
+      $typename = "<i>".PluginDatabasesDatabase::getTypeName()."</i><br/>".
+              $iteminv->getTypeName();
+      echo "<td class='center top' rowspan='1'>".$typename."</td>";
+      echo "<td class='center'>";
+      echo "<i>".Dropdown::getDropdownName("glpi_entities", $paDatabase->fields['entities_id'])."</i>";
+      echo "<br/>";
+      echo Dropdown::getDropdownName("glpi_entities", $iteminv->fields['entities_id']);
+      echo "</td>";
+
+      $linkDatabase     = Toolbox::getItemTypeFormURL('PluginDatabasesDatabase');
+      $namelinkDatabase = "<a href=\"".$linkDatabase."?id=".
+              $paDatabase->fields['id']."\">".$paDatabase->getName()."</a>";
+      $link     = Toolbox::getItemTypeFormURL($data['data']['itemtype']);
+      $namelink = "<a href=\"".$link."?id=".$data['data']['items_id']."\">".$iteminv->getName()."</a>";
+      echo "<td class='center".
+               (isset($iteminv->fields['is_deleted']) && $iteminv->fields['is_deleted'] ? " tab_bg_2_2'" : "'");
+      echo "><i>".$namelinkDatabase."</i><br/>".$namelink;
+      echo "</td>";
+      echo "<td class='center'><i>".(isset($paDatabase->fields["serial"])? "".$paDatabase->fields["serial"]."" :"-").
+              "</i><br/>".(isset($iteminv->fields["serial"])? "".$iteminv->fields["serial"]."" :"-").
+           "</td>";
+      echo "<td class='center'>".
+             "<i>".(isset($iteminv->fields["otherserial"])? "".$iteminv->fields["otherserial"]."" :"-")."</i><br/>".
+             (isset($iteminv->fields["otherserial"])? "".$iteminv->fields["otherserial"]."" :"-")."</td>";
+      echo "</tr>";
+      return false;
+   }
+   return true;
+}
+
+
+function plugin_databases_AssignToTicketGiveItem($data) {
+   if ($data['itemtype'] == 'PluginDatabasesDatabase_Item') {
+      $paDatabase = new PluginDatabasesDatabase();
+      $paDatabase_item = new PluginDatabasesDatabase_Item();
+
+      $paDatabase_item->getFromDB($data['name']);
+      $itemtype = $paDatabase_item->fields['itemtype'];
+      $paDatabase->getFromDB($paDatabase_item->fields['plugin_databases_databases_id']);
+      $item = new $itemtype;
+      $item->getFromDB($paDatabase_item->fields['items_id']);
+      return $item->getLink(array('comments' => true))." (".
+              $paDatabase->getLink(array('comments' => true)).")";
+   }
+}
+
+
 // Define dropdown relations
 function plugin_databases_getDatabaseRelations() {
 
@@ -252,51 +368,63 @@
    $sopt=array();
 
    if (in_array($itemtype, PluginDatabasesDatabase::getTypes(true))) {
-      if (plugin_databases_haveRight("databases","r")) {
-    
-         $sopt[2410]['table']='glpi_plugin_databases_databases';
-         $sopt[2410]['field']='name';
-         $sopt[2410]['name']= PluginDatabasesDatabase::getTypeName(2)." - ".__('Name');
-         $sopt[2410]['forcegroupby']=true;
-         $sopt[2410]['datatype']='itemlink';
-         $sopt[2410]['massiveaction']  = false;
-         $sopt[2410]['itemlink_type']='PluginDatabasesDatabase';
-         $sopt[2410]['joinparams']     = array('beforejoin'
+      if (Session::haveRight("plugin_databases", READ)) {
+
+         $sopt[2410]['table']         ='glpi_plugin_databases_databases';
+         $sopt[2410]['field']         ='name';
+         $sopt[2410]['name']          = PluginDatabasesDatabase::getTypeName(2)." - ".__('Name');
+         $sopt[2410]['forcegroupby']  = true;
+         $sopt[2410]['datatype']      = 'itemlink';
+         $sopt[2410]['massiveaction'] = false;
+         $sopt[2410]['itemlink_type'] = 'PluginDatabasesDatabase';
+         $sopt[2410]['joinparams']    = array('beforejoin'
                                                 => array('table'      => 'glpi_plugin_databases_databases_items',
                                                          'joinparams' => array('jointype' => 'itemtype_item')));
-         
-                                                         
-         $sopt[2411]['table']='glpi_plugin_databases_databasecategories';
-         $sopt[2411]['field']='name';
-         $sopt[2411]['name']= PluginDatabasesDatabase::getTypeName(2)." - ".PluginDatabasesDatabaseCategory::getTypeName(1);
-         $sopt[2411]['forcegroupby']=true;
-         $sopt[2411]['joinparams']     = array('beforejoin' => array(
+
+
+         $sopt[2411]['table']        = 'glpi_plugin_databases_databasecategories';
+         $sopt[2411]['field']        = 'name';
+         $sopt[2411]['name']         = PluginDatabasesDatabase::getTypeName(2)." - ".PluginDatabasesDatabaseCategory::getTypeName(1);
+         $sopt[2411]['forcegroupby'] = true;
+         $sopt[2411]['joinparams']   = array('beforejoin' => array(
                                                    array('table'      => 'glpi_plugin_databases_databases',
                                                          'joinparams' => $sopt[2410]['joinparams'])));
          $sopt[2411]['datatype']       = 'dropdown';
          $sopt[2411]['massiveaction']  = false;
 
-         $sopt[2412]['table']='glpi_plugin_databases_servertypes';
-         $sopt[2412]['field']='name';
-         $sopt[2412]['name']= PluginDatabasesDatabase::getTypeName(2)." - ".PluginDatabasesServerType::getTypeName(1);
-         $sopt[2412]['forcegroupby']=true;
-         $sopt[2412]['joinparams']     = array('beforejoin' => array(
+         $sopt[2412]['table']        = 'glpi_plugin_databases_servertypes';
+         $sopt[2412]['field']        = 'name';
+         $sopt[2412]['name']         = PluginDatabasesDatabase::getTypeName(2)." - ".PluginDatabasesServerType::getTypeName(1);
+         $sopt[2412]['forcegroupby'] = true;
+         $sopt[2412]['joinparams']   = array('beforejoin' => array(
                                                    array('table'      => 'glpi_plugin_databases_databases',
                                                          'joinparams' => $sopt[2410]['joinparams'])));
          $sopt[2412]['datatype']       = 'dropdown';
          $sopt[2412]['massiveaction']  = false;
-                                                         
-         $sopt[2413]['table']='glpi_plugin_databases_databasetypes';
-         $sopt[2413]['field']='name';
-         $sopt[2413]['name']= PluginDatabasesDatabase::getTypeName(2)." - ".PluginDatabasesDatabaseType::getTypeName(1);
-         $sopt[2413]['forcegroupby']=true;
-         $sopt[2413]['joinparams']     = array('beforejoin' => array(
+
+         $sopt[2413]['table']        = 'glpi_plugin_databases_databasetypes';
+         $sopt[2413]['field']        = 'name';
+         $sopt[2413]['name']         = PluginDatabasesDatabase::getTypeName(2)." - ".PluginDatabasesDatabaseType::getTypeName(1);
+         $sopt[2413]['forcegroupby'] = true;
+         $sopt[2413]['joinparams']   = array('beforejoin' => array(
                                                    array('table'      => 'glpi_plugin_databases_databases',
                                                          'joinparams' => $sopt[2410]['joinparams'])));
          $sopt[2413]['datatype']       = 'dropdown';
          $sopt[2413]['massiveaction']  = false;
       }
-	}
+   }
+   if ($itemtype == 'Ticket') {
+      if (Session::haveRight("plugin_databases", READ)) {
+         $sopt[2414]['table']         = 'glpi_plugin_databases_databases';
+         $sopt[2414]['field']         = 'name';
+         $sopt[2414]['linkfield']     = 'items_id';
+         $sopt[2414]['datatype']      = 'itemlink';
+         $sopt[2414]['massiveaction'] = false;
+         $sopt[2414]['name']          = __('Database', 'databases')." - ".
+                                        __('Name');
+      }
+   }
+
 	return $sopt;
 }
 
@@ -322,7 +450,7 @@
 				for ($i=0 ; $i < $number_device ; $i++) {
 					$column = "name";
 					$itemtype = $DB->result($result_device, $i, "itemtype");
-					
+
 					if (!class_exists($itemtype)) {
                   continue;
                }
@@ -360,6 +488,24 @@
          return $out;
          break;
 
+      case 'glpi_plugin_databases_databases.name':
+         if ($type == 'Ticket') {
+            $databases_id = array();
+            if ($data['raw']["ITEM_$num"] != '') {
+               $databases_id = explode('$$$$', $data['raw']["ITEM_$num"]);
+            } else {
+               $databases_id = explode('$$$$', $data['raw']["ITEM_".$num."_2"]);
+            }
+            $ret = array();
+            $paDatabase = new PluginDatabasesDatabase();
+            foreach ($databases_id as $ap_id) {
+               $paDatabase->getFromDB($ap_id);
+               $ret[] = $paDatabase->getLink();
+            }
+            return implode('<br>', $ret);
+         }
+         break;
+
 	}
 	return "";
 }
@@ -378,9 +524,9 @@
 function plugin_databases_MassiveActionsDisplay($options=array()) {
 
 	$database=new PluginDatabasesDatabase;
-	
+
    if (in_array($options['itemtype'], PluginDatabasesDatabase::getTypes(true))) {
-        
+
       $database->dropdownDatabases("plugin_databases_databases_id");
       echo "<input type=\"submit\" name=\"massiveaction\" class=\"submit\" value=\""._sx('button', 'Post')."\" >";
 	}
@@ -388,11 +534,11 @@
 }
 
 function plugin_databases_MassiveActionsProcess($data) {
-   
+
    $res = array('ok' => 0,
             'ko' => 0,
             'noright' => 0);
-            
+
    $database_item = new PluginDatabasesDatabase_Item();
 
 	switch ($data['action']) {
@@ -425,4 +571,118 @@
    $INJECTABLE_TYPES['PluginDatabasesDatabaseInjection'] = 'databases';
 }
 
+
+function plugin_databases_addSelect($type,$id,$num) {
+
+   $searchopt = &Search::getOptions($type);
+   $table = $searchopt[$id]["table"];
+   $field = $searchopt[$id]["field"];
+//echo "add select : ".$table.".".$field."<br/>";
+   switch ($type) {
+
+      case 'Ticket':
+
+         if ($table.".".$field == "glpi_plugin_databases_databases.name") {
+            return " GROUP_CONCAT(DISTINCT `glpi_plugin_databases_databases`.`id` SEPARATOR '$$$$') AS ITEM_$num, "
+                    . " GROUP_CONCAT(DISTINCT `glpi_plugin_databases_databases_bis`.`id` SEPARATOR '$$$$') AS ITEM_".$num."_2,";
+         }
+         break;
+   }
+}
+
+
+
+function plugin_databases_addLeftJoin($itemtype,$ref_table,$new_table,$linkfield,&$already_link_tables) {
+
+   switch ($itemtype) {
+
+      case 'Ticket':
+         return " LEFT JOIN `glpi_plugin_databases_databases` AS glpi_plugin_databases_databases
+            ON (`glpi_items_tickets`.`items_id` = `glpi_plugin_databases_databases`.`id`
+                  AND `glpi_items_tickets`.`itemtype`='PluginDatabasesDatabase')
+
+         LEFT JOIN `glpi_plugin_databases_databases_items`
+            ON (`glpi_items_tickets`.`items_id` = `glpi_plugin_databases_databases_items`.`id`
+                  AND `glpi_items_tickets`.`itemtype`='PluginDatabasesDatabase_Item')
+         LEFT JOIN `glpi_plugin_databases_databases` AS glpi_plugin_databases_databases_bis
+            ON (`glpi_plugin_databases_databases_items`.`plugin_databases_databases_id` = `glpi_plugin_databases_databases_bis`.`id`)";
+         break;
+
+   }
+   return "";
+}
+
+
+
+function plugin_databases_addWhere($link,$nott,$type,$id,$val,$searchtype) {
+
+   $searchopt = &Search::getOptions($type);
+   $table = $searchopt[$id]["table"];
+   $field = $searchopt[$id]["field"];
+
+   switch ($type) {
+
+      case 'Ticket':
+         if ($table.".".$field == "glpi_plugin_databases_databases.name") {
+            $out = '';
+            switch ($searchtype) {
+               case "contains" :
+                  $SEARCH = Search::makeTextSearch($val, $nott);
+                  break;
+
+               case "equals" :
+                  if ($nott) {
+                     $SEARCH = " <> '$val'";
+                  } else {
+                     $SEARCH = " = '$val'";
+                  }
+                  break;
+
+               case "notequals" :
+                  if ($nott) {
+                     $SEARCH = " = '$val'";
+                  } else {
+                     $SEARCH = " <> '$val'";
+                  }
+                  break;
+
+            }
+            if (in_array($searchtype, array('equals', 'notequals'))) {
+               if ($table != getTableForItemType($type) || $type == 'States') {
+                  $out = " $link (`glpi_plugin_databases_databases`.`id`".$SEARCH;
+               } else {
+                  $out = " $link (`glpi_plugin_databases_databases`.`$field`".$SEARCH;
+               }
+               if ($searchtype=='notequals') {
+                  $nott = !$nott;
+               }
+               // Add NULL if $val = 0 and not negative search
+               // Or negative search on real value
+               if ((!$nott && $val==0) || ($nott && $val != 0)) {
+                  $out .= " OR `glpi_plugin_databases_databases`.`id` IS NULL";
+               }
+//               $out .= ')';
+               $out1 = $out;
+               $out = str_replace(" ".$link." (", " ".$link." ", $out);
+            } else {
+               $out = Search::makeTextCriteria("`glpi_plugin_databases_databases`.".$field,$val,$nott,$link);
+               $out1 = $out;
+               $out = preg_replace("/^ $link/", $link.' (', $out);
+            }
+            $out2 = $out." OR ";
+            $out2 .= str_replace("`glpi_plugin_databases_databases`",
+                                 "`glpi_plugin_databases_databases_bis`", $out1)." ";
+            $out2 = str_replace("OR   AND", "OR", $out2);
+            $out2 = str_replace("OR   OR", "OR", $out2);
+            $out2 = str_replace("AND   OR", "OR", $out2);
+            $out2 = str_replace("OR  AND", "OR", $out2);
+            $out2 = str_replace("OR  OR", "OR", $out2);
+            $out2 = str_replace("AND  OR", "OR", $out2);
+            return $out2.")";
+         }
+         break;
+   }
+}
+
+
 ?>
\ No newline at end of file
Index: inc/database.class.php
===================================================================
--- inc/database.class.php	(revision 171)
+++ inc/database.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -32,24 +32,17 @@
 }
 
 class PluginDatabasesDatabase extends CommonDBTM {
-	
+
    public $dohistory=true;
-   
+   static $rightname = "plugin_databases";
+
    static $types = array('Computer','Software');
-   
+
    static function getTypeName($nb=0) {
 
       return _n('Database', 'Databases', $nb, 'databases');
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
 
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
-   
    function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
 
       if ($item->getType()=='Supplier') {
@@ -70,13 +63,13 @@
       }
       return true;
    }
-   
+
    static function countForItem(CommonDBTM $item) {
 
       return countElementsInTable('glpi_plugin_databases_databases',
                                   "`suppliers_id` = '".$item->getID()."'");
    }
-   
+
 	//clean if databases are deleted
 	function cleanDBonPurge() {
 
@@ -83,11 +76,11 @@
 		$temp = new PluginDatabasesDatabase_Item();
 		$temp->deleteByCriteria(array('plugin_databases_databases_id' => $this->fields['id']));
 	}
-	
+
 	function getSearchOptions() {
 
       $tab                       = array();
-    
+
       $tab['common']             = self::getTypeName(2);
 
       $tab[1]['table']           = $this->getTable();
@@ -95,22 +88,22 @@
       $tab[1]['name']            = __('Name');
       $tab[1]['datatype']        = 'itemlink';
       $tab[1]['itemlink_type']   = $this->getType();
-      
+
       $tab[2]['table']           = 'glpi_plugin_databases_databasecategories';
       $tab[2]['field']           = 'name';
       $tab[2]['name']            = PluginDatabasesDatabaseCategory::getTypeName(1);
       $tab[2]['datatype']        = 'dropdown';
-      
+
       $tab[3]['table']           = 'glpi_plugin_databases_servertypes';
       $tab[3]['field']           = 'name';
       $tab[3]['name']            = PluginDatabasesServerType::getTypeName(1);
       $tab[3]['datatype']        = 'dropdown';
-      
+
       $tab[4]['table']           = 'glpi_locations';
       $tab[4]['field']           = 'completename';
       $tab[4]['name']            = __('Location');
       $tab[4]['datatype']        = 'dropdown';
-      
+
       $tab[5]['table']           = 'glpi_suppliers';
       $tab[5]['field']           = 'name';
       $tab[5]['name']            = __('Supplier');
@@ -120,7 +113,7 @@
       $tab[6]['field']           = 'name';
       $tab[6]['name']            = __('Editor', 'databases');
       $tab[6]['datatype']        = 'dropdown';
-      
+
       $tab[7]['table']           = 'glpi_plugin_databases_databases_items';
       $tab[7]['field']           = 'items_id';
       $tab[7]['nosearch']        = true;
@@ -128,22 +121,22 @@
       $tab[7]['name']            = _n('Associated item' , 'Associated items', 2);
       $tab[7]['forcegroupby']    = true;
       $tab[7]['joinparams']      = array('jointype' => 'child');
-      
+
       $tab[8]['table']           = $this->getTable();
       $tab[8]['field']           = 'is_recursive';
       $tab[8]['name']            = __('Child entities');
       $tab[8]['datatype']        = 'bool';
-      
+
       $tab[9]['table']           = $this->getTable();
       $tab[9]['field']           = 'comment';
       $tab[9]['name']            = __('Comments');
       $tab[9]['datatype']        = 'text';
-      
+
       $tab[10]['table']          = 'glpi_plugin_databases_databasetypes';
       $tab[10]['field']          = 'name';
       $tab[10]['name']           = PluginDatabasesDatabaseType::getTypeName(1);
       $tab[10]['datatype']       = 'dropdown';
-      
+
       $tab[11]['table']          = 'glpi_users';
       $tab[11]['field']          = 'name';
       $tab[11]['linkfield']      = 'users_id_tech';
@@ -150,7 +143,7 @@
       $tab[11]['name']           = __('Technician in charge of the hardware');
       $tab[11]['datatype']       = 'dropdown';
       $tab[11]['right']          = 'interface';
-      
+
       $tab[12]['table']          = 'glpi_groups';
       $tab[12]['field']          = 'name';
       $tab[12]['linkfield']      = 'groups_id_tech';
@@ -157,18 +150,18 @@
       $tab[12]['name']           = __('Group in charge of the hardware');
       $tab[12]['condition']      = '`is_assign`';
       $tab[12]['datatype']       = 'dropdown';
-      
+
       $tab[13]['table']          = $this->getTable();
       $tab[13]['field']          = 'is_helpdesk_visible';
       $tab[13]['name']           = __('Associable to a ticket');
       $tab[13]['datatype']       = 'bool';
-      
+
       $tab[14]['table']          = $this->getTable();
       $tab[14]['field']          = 'date_mod';
       $tab[14]['massiveaction']  = false;
       $tab[14]['name']           = __('Last update');
       $tab[14]['datatype']       = 'datetime';
-      
+
       $tab[30]['table']          = $this->getTable();
       $tab[30]['field']          = 'id';
       $tab[30]['name']           = __('ID');
@@ -181,11 +174,12 @@
 
       return $tab;
    }
-   
+
 	//define header form
 	function defineTabs($options=array()) {
 
       $ong = array();
+      $this->addDefaultFormTab($ong);
       $this->addStandardTab('PluginDatabasesDatabase_Item', $ong, $options);
       $this->addStandardTab('PluginDatabasesInstance', $ong, $options);
       $this->addStandardTab('PluginDatabasesScript', $ong, $options);
@@ -197,7 +191,7 @@
 
       return $ong;
    }
-   
+
    /*
     * Return the SQL command to retrieve linked object
     *
@@ -208,13 +202,14 @@
               FROM `glpi_plugin_databases_databases_items`
               WHERE `plugin_databases_databases_id`='" . $this->fields['id']."'";
    }
-   
+
 	function showForm ($ID, $options=array()) {
 
       $this->initForm($ID, $options);
-      $this->showTabs($options);
       $this->showFormHeader($options);
 
+      $canedit = $this->can($ID, UPDATE);
+
       echo "<tr class='tab_bg_1'>";
 
       echo "<td>".__('Name')."</td>";
@@ -221,7 +216,7 @@
       echo "<td>";
       Html::autocompletionTextField($this,"name");
       echo "</td>";
-      
+
       echo "<td>".PluginDatabasesDatabaseCategory::getTypeName(1)."</td>";
       echo "<td>";
       Dropdown::show('PluginDatabasesDatabaseCategory', array('name' => "plugin_databases_databasecategories_id",
@@ -228,27 +223,27 @@
                                                                'value' => $this->fields["plugin_databases_databasecategories_id"],
                                                                'entity' => $this->fields["entities_id"]));
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td>".__('Location')."</td>";
       echo "<td>";
       Location::dropdown(array('value'  => $this->fields["locations_id"],
                                'entity' => $this->fields["entities_id"]));
       echo "</td>";
-      
+
       echo "<td>".PluginDatabasesServerType::getTypeName(1)."</td>";
       echo "<td>";
       Dropdown::show('PluginDatabasesServerType', array('name' => "plugin_databases_servertypes_id",
                                                       'value' => $this->fields["plugin_databases_servertypes_id"]));
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td>".__('Technician in charge of the hardware')."</td><td>";
       User::dropdown(array('name' => "users_id_tech",
                            'value' => $this->fields["users_id_tech"],
@@ -255,18 +250,18 @@
                            'entity' => $this->fields["entities_id"],
                            'right' => 'interface'));
       echo "</td>";
-      
+
       echo "<td>".PluginDatabasesDatabaseType::getTypeName(1)."</td>";
       echo "<td>";
       Dropdown::show('PluginDatabasesDatabaseType', array('name' => "plugin_databases_databasetypes_id",
-                                                         'value' => $this->fields["plugin_databases_databasetypes_id"], 
+                                                         'value' => $this->fields["plugin_databases_databasetypes_id"],
                                                          'entity' => $this->fields["entities_id"]));
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td>".__('Group in charge of the hardware')."</td><td>";
       Group::dropdown(array('name'      => 'groups_id_tech',
                             'value'     => $this->fields['groups_id_tech'],
@@ -273,22 +268,22 @@
                             'entity'    => $this->fields['entities_id'],
                             'condition' => '`is_assign`'));
       echo "</td>";
-      
+
       echo "<td>".__('Editor', 'databases')."</td>";
       echo "<td>";
       Dropdown::show('Manufacturer', array('name' => "manufacturers_id",
-                                             'value' => $this->fields["manufacturers_id"], 
+                                             'value' => $this->fields["manufacturers_id"],
                                              'entity' => $this->fields["entities_id"]));
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td>".__('Supplier')."</td>";
       echo "<td>";
       Dropdown::show('Supplier', array('name' => "suppliers_id",
-                                       'value' => $this->fields["suppliers_id"], 
+                                       'value' => $this->fields["suppliers_id"],
                                        'entity' => $this->fields["entities_id"]));
       echo "</td>";
 
@@ -295,19 +290,19 @@
       echo "<td>" . __('Associable to a ticket') . "</td><td>";
       Dropdown::showYesNo('is_helpdesk_visible',$this->fields['is_helpdesk_visible']);
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td class='center' colspan = '4'>";
       printf(__('Last update on %s'), Html::convDateTime($this->fields["date_mod"]));
       echo "</td>";
 
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td colspan = '4'>";
       echo "<table cellpadding='2' cellspacing='2' border='0'><tr><td>";
       echo __('Comments')."</td></tr>";
@@ -316,15 +311,14 @@
       echo "<textarea cols='125' rows='3' name='comment'>".$this->fields["comment"]."</textarea>";
       echo "</td></tr></table>";
       echo "</td>";
-      
+
       echo "</tr>";
 
       $this->showFormButtons($options);
-      $this->addDivForTabs();
 
       return true;
 	}
-	
+
 	function dropdownDatabases($myname,$entity_restrict='',$used=array()) {
       global $DB,$CFG_GLPI;
 
@@ -377,7 +371,7 @@
 
       return $rand;
    }
-   
+
    /**
     * For other plugins, add a type to the linkable types
     *
@@ -420,14 +414,14 @@
       }
       return $types;
    }
-   
+
    function showPluginFromSupplier($ID,$withtemplate='') {
       global $DB,$CFG_GLPI;
-    
+
       $item = new Supplier();
       $canread = $item->can($ID,'r');
       $canedit = $item->can($ID,'w');
-      
+
       $query = "SELECT `glpi_plugin_databases_databases`.* "
         ."FROM `glpi_plugin_databases_databases` "
         ." LEFT JOIN `glpi_entities` ON (`glpi_entities`.`id` = `glpi_plugin_databases_databases`.`entities_id`) "
@@ -434,16 +428,16 @@
         ." WHERE `suppliers_id` = '$ID' "
         . getEntitiesRestrictRequest(" AND ","glpi_plugin_databases_databases",'','',$this->maybeRecursive());
       $query.= " ORDER BY `glpi_plugin_databases_databases`.`name` ";
-    
+
       $result = $DB->query($query);
       $number = $DB->numrows($result);
-    
+
       if (Session::isMultiEntitiesMode()) {
          $colsup=1;
       } else {
          $colsup=0;
       }
-    
+
       if ($withtemplate!=2) echo "<form method='post' action=\"".$CFG_GLPI["root_doc"]."/plugins/databases/front/database.form.php\">";
 
       echo "<div align='center'><table class='tab_cadre_fixe'>";
Index: inc/database_item.class.php
===================================================================
--- inc/database_item.class.php	(revision 171)
+++ inc/database_item.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -40,23 +40,13 @@
    static public $itemtype_2 = 'itemtype';
    static public $items_id_2 = 'items_id';
 
-   /**
-    * Have I the global right to "create" the Object
-    *
-    * @return booleen
-    **/
-   public static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
 
-   /**
-    * Have I the global right to "view" the Object
-    * Default is true and check entity if the objet is entity assign
-    *
-    * @return booleen
-    **/
-   public static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
+   static function getTypeName($nb=0) {
+
+      if ($nb > 1) {
+         return _n('Database item', 'Databases items', 2, 'databases');
+      }
+      return _n('Database item', 'Databases items', 1, 'databases');
    }
 
    /**
@@ -99,7 +89,7 @@
             return _n('Associated item','Associated items',2);
 
          } else if (in_array($item->getType(), PluginDatabasesDatabase::getTypes(true))
-                    && plugin_databases_haveRight('databases', 'r')) {
+                    && Session::haveRight('plugin_databases', READ)) {
             if ($_SESSION['glpishow_count_on_tabs']) {
                return self::createTabEntry(PluginDatabasesDatabase::getTypeName(2), self::countForItem($item));
             }
@@ -123,16 +113,16 @@
    public static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
 
       if ($item->getType()=='PluginDatabasesDatabase') {
-         
+
          self::showForDatabase($item);
 
       } else if (in_array($item->getType(), PluginDatabasesDatabase::getTypes(true))) {
-         
+
             self::showForITem($item);
       }
       return true;
    }
-   
+
    static function countForDatabase(PluginDatabasesDatabase $item) {
 
       $types = implode("','", $item->getTypes());
@@ -151,12 +141,12 @@
                                   "`itemtype`='".$item->getType()."'
                                    AND `items_id` = '".$item->getID()."'");
    }
-   
+
 	function getFromDBbyDatabasesAndItem($plugin_databases_databases_id,$items_id,$itemtype) {
 		global $DB;
-		
+
 		$query = "SELECT * FROM `".$this->getTable()."` " .
-			"WHERE `plugin_databases_databases_id` = '" . $plugin_databases_databases_id . "' 
+			"WHERE `plugin_databases_databases_id` = '" . $plugin_databases_databases_id . "'
 			AND `itemtype` = '" . $items_id . "'
 			AND `items_id` = '" . $itemtype . "'";
 		if ($result = $DB->query($query)) {
@@ -172,22 +162,22 @@
 		}
 		return false;
 	}
-	
+
 	function addItem($values) {
 
       $this->add(array('plugin_databases_databases_id'=>$values["plugin_databases_databases_id"],
 								'items_id'=>$values["items_id"],
 								'itemtype'=>$values["itemtype"]));
-    
+
    }
 
    function deleteItemByDatabasesAndItem($plugin_databases_databases_id,$items_id,$itemtype) {
-    
+
       if ($this->getFromDBbyDatabasesAndItem($plugin_databases_databases_id,$items_id,$itemtype)) {
          $this->delete(array('id'=>$this->fields["id"]));
       }
    }
-   
+
    /**
     * @since version 0.84
    **/
@@ -210,11 +200,11 @@
       global $DB;
 
       $instID = $database->fields['id'];
-      if (!$database->can($instID,'r'))   return false;
-      
+      if (!$database->can($instID, READ))   return false;
+
       $rand=mt_rand();
 
-      $canedit=$database->can($instID,'w');
+      $canedit=$database->can($instID, UPDATE);
 
       $query = "SELECT DISTINCT `itemtype`
              FROM `glpi_plugin_databases_databases_items`
@@ -251,7 +241,7 @@
          Html::closeForm();
          echo "</div>" ;
       }
-      
+
       echo "<div class='spaced'>";
       if ($canedit && $number) {
          Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
@@ -352,7 +342,7 @@
       }
       echo "</div>";
    }
-   
+
    /**
    * Show databases associated to an item
    *
@@ -369,11 +359,11 @@
       if ($item->isNewID($ID)) {
          return false;
       }
-      if (!plugin_databases_haveRight('databases', 'r')) {
+      if (!Session::haveRight('plugin_databases', READ)) {
          return false;
       }
 
-      if (!$item->can($item->fields['id'],'r')) {
+      if (!$item->can($item->fields['id'], READ)) {
          return false;
       }
 
@@ -440,10 +430,10 @@
          $result = $DB->query($q);
          $nb     = $DB->result($result,0,0);
 
-         echo "<div class='firstbloc'>";       
-         
-         
-         if (plugin_databases_haveRight('databases', 'r')
+         echo "<div class='firstbloc'>";
+
+
+         if (Session::haveRight('plugin_databases', READ)
              && ($nb > count($used))) {
             echo "<form name='database_form$rand' id='database_form$rand' method='post'
                    action='".Toolbox::getItemTypeFormURL('PluginDatabasesDatabase')."'>";
@@ -502,7 +492,7 @@
                                         sprintf(__('%1$s = %2$s'),
                                                 $item->getTypeName(1), $item->getName()));
 
-         
+
          foreach  ($databases as $data) {
             $databaseID        = $data["id"];
             $link             = NOT_AVAILABLE;
@@ -512,7 +502,7 @@
             }
 
             Session::addToNavigateListItems('PluginDatabasesDatabase', $databaseID);
-            
+
             $used[$databaseID]   = $databaseID;
             $assocID             = $data["assocID"];
 
Index: inc/databasecategory.class.php
===================================================================
--- inc/databasecategory.class.php	(revision 171)
+++ inc/databasecategory.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -32,19 +32,13 @@
 }
 
 class PluginDatabasesDatabaseCategory extends CommonDropdown {
-   
+
+   static $rightname = "plugin_databases";
+
    static function getTypeName($nb=0) {
 
       return _n('Category','Categories',$nb, 'databases');
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
-
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
 }
 
 ?>
\ No newline at end of file
Index: inc/databasetype.class.php
===================================================================
--- inc/databasetype.class.php	(revision 171)
+++ inc/databasetype.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -33,20 +33,14 @@
 
 // Class for a Dropdown
 class PluginDatabasesDatabaseType extends CommonDropdown {
-   
+
+   static $rightname = "entity_dropdown";
+
    static function getTypeName($nb=0) {
 
       return _n('Type','Types',$nb);
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
 
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
-   
    static function transfer($ID, $entity) {
       global $DB;
 
Index: inc/instance.class.php
===================================================================
--- inc/instance.class.php	(revision 171)
+++ inc/instance.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -33,23 +33,17 @@
 
 class PluginDatabasesInstance extends CommonDBChild {
 
+   static $rightname = "plugin_databases";
+
    // From CommonDBChild
    static public $itemtype = 'PluginDatabasesDatabase';
    static public $items_id = 'plugin_databases_databases_id';
-   
+
 	static function getTypeName($nb=0) {
 
       return _n('Instance','Instances',$nb, 'databases');
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
 
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
-   
    function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
 
       if ($item->getType()=='PluginDatabasesDatabase') {
@@ -64,27 +58,27 @@
 
       if ($item->getType()=='PluginDatabasesDatabase') {
          $self = new self();
-         
+
          $self->showInstances($item);
-         $self->showForm("", array('plugin_databases_databases_id' => $item->getField('id'), 
+         $self->showForm("", array('plugin_databases_databases_id' => $item->getField('id'),
                                     'target' => $CFG_GLPI['root_doc']."/plugins/databases/front/instance.form.php"));
       }
       return true;
    }
-   
+
    function post_getEmpty () {
       $this->fields["port"]='0';
    }
-   
+
    function prepareInputForAdd($input) {
       // Not attached to reference -> not added
-      if (!isset($input['plugin_databases_databases_id']) 
+      if (!isset($input['plugin_databases_databases_id'])
             || $input['plugin_databases_databases_id'] <= 0) {
          return false;
       }
       return $input;
    }
-   
+
 	function showForm ($ID, $options=array()) {
 
 		if (!$this->canView()) return false;
@@ -93,7 +87,7 @@
       if (isset($options['plugin_databases_databases_id'])) {
          $plugin_databases_databases_id = $options['plugin_databases_databases_id'];
       }
-      
+
 		if ($ID > 0) {
          $this->check($ID,'r');
       } else {
@@ -105,7 +99,7 @@
                       'is_recursive' => $database->isRecursive());
          $this->check(-1,'w',$input);
       }
-      
+
       if ($ID > 0) {
          $this->showTabs($options);
       }
@@ -114,7 +108,7 @@
       echo "<input type='hidden' name='plugin_databases_databases_id' value='$plugin_databases_databases_id'>";
       echo "<input type='hidden' name='entities_id' value='".$this->fields["entities_id"]."'>";
       echo "<input type='hidden' name='is_recursive' value='".$this->fields["is_recursive"]."'>";
-      
+
       echo "<tr class='tab_bg_1'>";
 
       echo "<td>".__('Name')."</td>";
@@ -121,28 +115,28 @@
       echo "<td>";
       Html::autocompletionTextField($this,"name");
       echo "</td>";
-      
+
       echo "<td>".__('Port')."</td>";
       echo "<td>";
       Html::autocompletionTextField($this,"port");
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td>".__('Path', 'databases')."</td>";
       echo "<td>";
       Html::autocompletionTextField($this,"path");
       echo "</td>";
-      
+
       echo "<td></td>";
       echo "<td></td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td colspan = '4'>";
       echo "<table cellpadding='2' cellspacing='2' border='0'><tr><td>";
       echo __('Comments')."</td></tr>";
@@ -151,9 +145,9 @@
       echo "<textarea cols='125' rows='3' name='comment'>".$this->fields["comment"]."</textarea>";
       echo "</td></tr></table>";
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       $options['candel'] = false;
       $this->showFormButtons($options);
       if ($ID > 0) {
@@ -162,7 +156,7 @@
 
       return true;
 	}
-	
+
 	/**
     * @since version 0.84
    **/
@@ -172,7 +166,7 @@
       $forbidden[] = 'update';
       return $forbidden;
    }
-	
+
 	function showInstances(PluginDatabasesDatabase $database) {
       global $DB,$CFG_GLPI;
 
Index: inc/profile.class.php
===================================================================
--- inc/profile.class.php	(revision 171)
+++ inc/profile.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -31,20 +31,10 @@
 	die("Sorry. You can't access directly to this file");
 }
 
-class PluginDatabasesProfile extends CommonDBTM {
+class PluginDatabasesProfile extends Profile {
 
-   static function getTypeName($nb=0) {
-      return __('Rights management', 'databases');
-   }
-   
-   static function canCreate() {
-      return Session::haveRight('profile', 'w');
-   }
+   static $rightname = "profile";
 
-   static function canView() {
-      return Session::haveRight('profile', 'r');
-   }
-   
    function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
 
       if ($item->getType()=='Profile') {
@@ -55,118 +45,202 @@
 
 
    static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
-      global $CFG_GLPI;
 
       if ($item->getType()=='Profile') {
-         $ID = $item->getField('id');
+         $ID = $item->getID();
          $prof = new self();
-         
-         if (!$prof->getFromDBByProfile($item->getField('id'))) {
-            $prof->createAccess($item->getField('id'));
-         }
-         $prof->showForm($item->getField('id'), array('target' => 
-                           $CFG_GLPI["root_doc"]."/plugins/databases/front/profile.form.php"));
+
+         self::addDefaultProfileInfos($ID,
+                                    array('plugin_databases'               => 0,
+                                          'plugin_databases_open_ticket'   => 0));
+         $prof->showForm($ID);
       }
       return true;
    }
-   
-	//if profile deleted
-	static function purgeProfiles(Profile $prof) {
-      $plugprof = new self();
-      $plugprof->deleteByCriteria(array('profiles_id' => $prof->getField("id")));
+
+   static function createFirstAccess($ID) {
+      //85
+      self::addDefaultProfileInfos($ID,
+                                   array('plugin_databases'             => 127,
+                                         'plugin_databases_open_ticket' => 1), true);
    }
-   
-   function getFromDBByProfile($profiles_id) {
-		global $DB;
-		
-		$query = "SELECT * FROM `".$this->getTable()."`
-					WHERE `profiles_id` = '" . $profiles_id . "' ";
-		if ($result = $DB->query($query)) {
-			if ($DB->numrows($result) != 1) {
-				return false;
-			}
-			$this->fields = $DB->fetch_assoc($result);
-			if (is_array($this->fields) && count($this->fields)) {
-				return true;
-			} else {
-				return false;
-			}
-		}
-		return false;
-	}
-	
-	static function createFirstAccess($ID) {
-      
-      $myProf = new self();
-      if (!$myProf->getFromDBByProfile($ID)) {
 
-         $myProf->add(array(
-            'profiles_id' => $ID,
-            'databases' => 'w',
-            'open_ticket' => '1'));
+    /**
+    * @param $profile
+   **/
+   static function addDefaultProfileInfos($profiles_id, $rights, $drop_existing = false) {
+
+      $profileRight = new ProfileRight();
+      foreach ($rights as $right => $value) {
+         if (countElementsInTable('glpi_profilerights',
+                                   "`profiles_id`='$profiles_id' AND `name`='$right'") && $drop_existing) {
+            $profileRight->deleteByCriteria(array('profiles_id' => $profiles_id, 'name' => $right));
+         }
+         if (!countElementsInTable('glpi_profilerights',
+                                   "`profiles_id`='$profiles_id' AND `name`='$right'")) {
+            $myright['profiles_id'] = $profiles_id;
+            $myright['name']        = $right;
+            $myright['rights']      = $value;
+            $profileRight->add($myright);
+
+            //Add right to the current session
+            $_SESSION['glpiactiveprofile'][$right] = $value;
+         }
       }
    }
-	
-	function createAccess($ID) {
 
-      $this->add(array(
-      'profiles_id' => $ID));
+
+   /**
+    * Show profile form
+    *
+    * @param $items_id integer id of the profile
+    * @param $target value url of target
+    *
+    * @return nothing
+    **/
+   function showForm($profiles_id=0, $openform=TRUE, $closeform=TRUE) {
+
+      echo "<div class='firstbloc'>";
+      if (($canedit = Session::haveRightsOr(self::$rightname, array(CREATE, UPDATE, PURGE)))
+          && $openform) {
+         $profile = new Profile();
+         echo "<form method='post' action='".$profile->getFormURL()."'>";
+      }
+
+      $profile = new Profile();
+      $profile->getFromDB($profiles_id);
+      if ($profile->getField('interface') == 'central') {
+         $rights = $this->getAllRights();
+         $profile->displayRightsChoiceMatrix($rights, array('canedit'       => $canedit,
+                                                         'default_class' => 'tab_bg_2',
+                                                         'title'         => __('General')));
+      }
+      echo "<table class='tab_cadre_fixehov'>";
+      echo "<tr class='tab_bg_1'><th colspan='4'>".__('Helpdesk')."</th></tr>\n";
+
+      $effective_rights = ProfileRight::getProfileRights($profiles_id, array('plugin_databases_open_ticket'));
+      echo "<tr class='tab_bg_2'>";
+      echo "<td width='20%'>".__('Associable items to a ticket')."</td>";
+      echo "<td colspan='5'>";
+      Html::showCheckbox(array('name'    => '_plugin_databases_open_ticket',
+                               'checked' => $effective_rights['plugin_databases_open_ticket']));
+      echo "</td></tr>\n";
+      echo "</table>";
+
+      if ($canedit
+          && $closeform) {
+         echo "<div class='center'>";
+         echo Html::hidden('id', array('value' => $profiles_id));
+         echo Html::submit(_sx('button', 'Save'), array('name' => 'update'));
+         echo "</div>\n";
+         Html::closeForm();
+      }
+      echo "</div>";
    }
-   
-   static function changeProfile() {
-      
-      $prof = new self();
-      if ($prof->getFromDBByProfile($_SESSION['glpiactiveprofile']['id'])) {
-         $_SESSION["glpi_plugin_databases_profile"]=$prof->fields;
-      } else {
-         unset($_SESSION["glpi_plugin_databases_profile"]);
+
+   static function getAllRights($all = false) {
+      $rights = array(
+          array('itemtype'  => 'PluginDatabasesDatabase',
+                'label'     => _n('Database', 'Aplpiances', 2, 'databases'),
+                'field'     => 'plugin_databases'
+          ),
+      );
+
+      if ($all) {
+         $rights[] = array('itemtype' => 'PluginDatabasesDatabase',
+                           'label'    =>  __('Associable items to a ticket'),
+                           'field'    => 'plugin_databases_open_ticket');
       }
+
+      return $rights;
    }
 
-	function showForm ($ID, $options=array()) {
+   /**
+    * Init profiles
+    *
+    **/
 
-		if (!Session::haveRight("profile","r")) return false;
+   static function translateARight($old_right) {
+      switch ($old_right) {
+         case '':
+            return 0;
+         case 'r' :
+            return READ;
+         case 'w':
+            return ALLSTANDARDRIGHT + READNOTE + UPDATENOTE;
+         case '0':
+         case '1':
+            return $old_right;
 
-		$prof = new Profile();
-		if ($ID) {
-			$this->getFromDBByProfile($ID);
-			$prof->getFromDB($ID);
-		}
+         default :
+            return 0;
+      }
+   }
 
-      $this->showFormHeader($options);
+   /**
+   * @since 0.85
+   * Migration rights from old system to the new one for one profile
+   * @param $profiles_id the profile ID
+   */
+   static function migrateOneProfile($profiles_id) {
+      global $DB;
+      //Cannot launch migration if there's nothing to migrate...
+      if (!TableExists('glpi_plugin_databases_profiles')) {
+      return true;
+      }
 
-		echo "<tr class='tab_bg_2'>";
-		
-		echo "<th colspan='4'>".sprintf(__('%1$s - %2$s'), __('Rights management', 'databases'),
-         $prof->fields["name"])."</th>";
-      
-      echo "</tr>";
-		echo "<tr class='tab_bg_2'>";
-		
-		echo "<td>".PluginDatabasesDatabase::getTypeName(2)."</td><td>";
+      foreach ($DB->request('glpi_plugin_databases_profiles',
+                            "`profiles_id`='$profiles_id'") as $profile_data) {
 
-		if ($prof->fields['interface']!='helpdesk') {
-			Profile::dropdownNoneReadWrite("databases",$this->fields["databases"],1,1,1);
-		} else {
-         _e('No access'); // No access;
-		}
-		echo "</td>";
+         $matching = array('databases'    => 'plugin_databases',
+                           'open_ticket' => 'plugin_databases_open_ticket');
+         $current_rights = ProfileRight::getProfileRights($profiles_id, array_values($matching));
+         foreach ($matching as $old => $new) {
+            if (!isset($current_rights[$old])) {
+               $query = "UPDATE `glpi_profilerights`
+                         SET `rights`='".self::translateARight($profile_data[$old])."'
+                         WHERE `name`='$new' AND `profiles_id`='$profiles_id'";
+               $DB->query($query);
+            }
+         }
+      }
+   }
 
-		echo "<td>" . __('Associable items to a ticket') . " - " .
-         PluginDatabasesDatabase::getTypeName(2) . "</td><td>";
-		if ($prof->fields['create_ticket']) {
-			Dropdown::showYesNo("open_ticket",$this->fields["open_ticket"]);
-		} else {
-			echo Dropdown::getYesNo(0);
-		}
-		echo "</td>";
-		echo "</tr>";
+   /**
+   * Initialize profiles, and migrate it necessary
+   */
+   static function initProfile() {
+      global $DB;
+      $profile = new self();
 
-		echo "<input type='hidden' name='id' value=".$this->fields["id"].">";
-      
-		$options['candel'] = false;
-      $this->showFormButtons($options);
-	}
+      //Add new rights in glpi_profilerights table
+      foreach ($profile->getAllRights(true) as $data) {
+         if (countElementsInTable("glpi_profilerights",
+                                  "`name` = '".$data['field']."'") == 0) {
+            ProfileRight::addProfileRights(array($data['field']));
+         }
+      }
+
+      //Migration old rights in new ones
+      foreach ($DB->request("SELECT `id` FROM `glpi_profiles`") as $prof) {
+         self::migrateOneProfile($prof['id']);
+      }
+      foreach ($DB->request("SELECT *
+                           FROM `glpi_profilerights`
+                           WHERE `profiles_id`='".$_SESSION['glpiactiveprofile']['id']."'
+                              AND `name` LIKE '%plugin_databases%'") as $prof) {
+         $_SESSION['glpiactiveprofile'][$prof['name']] = $prof['rights'];
+      }
+   }
+
+
+   static function removeRightsFromSession() {
+      foreach (self::getAllRights(true) as $right) {
+         if (isset($_SESSION['glpiactiveprofile'][$right['field']])) {
+            unset($_SESSION['glpiactiveprofile'][$right['field']]);
+         }
+      }
+   }
 }
 
 ?>
\ No newline at end of file
Index: inc/script.class.php
===================================================================
--- inc/script.class.php	(revision 171)
+++ inc/script.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -33,23 +33,17 @@
 
 class PluginDatabasesScript extends CommonDBChild {
 
+   static $rightname = "plugin_databases";
+
    // From CommonDBChild
    static public $itemtype = 'PluginDatabasesDatabase';
    static public $items_id = 'plugin_databases_databases_id';
-   
+
    static function getTypeName($nb=0) {
 
       return _n('Script','Scripts',$nb, 'databases');
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
 
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
-   
    function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
 
       if ($item->getType()=='PluginDatabasesDatabase') {
@@ -64,32 +58,32 @@
 
       if ($item->getType()=='PluginDatabasesDatabase') {
          $self = new self();
-         
+
          $self->showScripts($item);
-         $self->showForm("", array('plugin_databases_databases_id' => $item->getField('id'), 
+         $self->showForm("", array('plugin_databases_databases_id' => $item->getField('id'),
                                     'target' => $CFG_GLPI['root_doc']."/plugins/databases/front/script.form.php"));
       }
       return true;
    }
-   
+
    function prepareInputForAdd($input) {
       // Not attached to reference -> not added
-      if (!isset($input['plugin_databases_databases_id']) 
+      if (!isset($input['plugin_databases_databases_id'])
                || $input['plugin_databases_databases_id'] <= 0) {
          return false;
       }
       return $input;
    }
-	
+
 	function showForm ($ID, $options=array()) {
 
 		if (!$this->canview()) return false;
-      
+
       $plugin_databases_databases_id = -1;
       if (isset($options['plugin_databases_databases_id'])) {
          $plugin_databases_databases_id = $options['plugin_databases_databases_id'];
       }
-      
+
       if ($ID > 0) {
          $this->check($ID,'r');
       } else {
@@ -110,37 +104,37 @@
       echo "<input type='hidden' name='plugin_databases_databases_id' value='$plugin_databases_databases_id'>";
       echo "<input type='hidden' name='entities_id' value='".$this->fields["entities_id"]."'>";
       echo "<input type='hidden' name='is_recursive' value='".$this->fields["is_recursive"]."'>";
-      
+
       echo "<tr class='tab_bg_1'>";
 
       echo "<td>".__('Name')."</td>";
       echo "<td>";
-      Html::autocompletionTextField($this,"name");	
+      Html::autocompletionTextField($this,"name");
       echo "</td>";
 
       echo "<td>".__('Type')."</td>";
       echo "<td>";
-      Dropdown::show('PluginDatabasesScriptType', 
+      Dropdown::show('PluginDatabasesScriptType',
             array('name' => "plugin_databases_scripttypes_id",
                   'value' => $this->fields["plugin_databases_scripttypes_id"]));
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td>".__('Path', 'databases')."</td>";
       echo "<td>";
       Html::autocompletionTextField($this,"path");
       echo "</td>";
-      
+
       echo "<td></td>";
       echo "<td></td>";
-      
+
       echo "</tr>";
-      
+
       echo "<tr class='tab_bg_1'>";
-      
+
       echo "<td colspan = '4'>";
       echo "<table cellpadding='2' cellspacing='2' border='0'><tr><td>";
       echo __('Comments')."</td></tr>";
@@ -149,9 +143,9 @@
       echo "<textarea cols='125' rows='3' name='comment'>".$this->fields["comment"]."</textarea>";
       echo "</td></tr></table>";
       echo "</td>";
-      
+
       echo "</tr>";
-      
+
       $options['candel'] = false;
       $this->showFormButtons($options);
       if ($ID > 0) {
@@ -160,7 +154,7 @@
 
       return true;
 	}
-	
+
 	/**
     * @since version 0.84
    **/
@@ -170,7 +164,7 @@
       $forbidden[] = 'update';
       return $forbidden;
    }
-   
+
 	function showScripts(PluginDatabasesDatabase $database) {
       global $DB,$CFG_GLPI;
 
Index: inc/scripttype.class.php
===================================================================
--- inc/scripttype.class.php	(revision 171)
+++ inc/scripttype.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -32,19 +32,13 @@
 }
 
 class PluginDatabasesScriptType extends CommonDropdown {
-   
+
+   static $rightname = "plugin_databases";
+
    static function getTypeName($nb=0) {
 
       return _n('Type of script','Types of script', $nb, 'databases');
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
-
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
 }
 
 ?>
\ No newline at end of file
Index: inc/servertype.class.php
===================================================================
--- inc/servertype.class.php	(revision 171)
+++ inc/servertype.class.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-		
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -32,19 +32,12 @@
 }
 
 class PluginDatabasesServerType extends CommonDropdown {
-   
+
+   static $rightname = "plugin_databases";
+
    static function getTypeName($nb=0) {
-
       return _n('Engine','Engines',$nb, 'databases');
    }
-   
-   static function canCreate() {
-      return plugin_databases_haveRight('databases', 'w');
-   }
-
-   static function canView() {
-      return plugin_databases_haveRight('databases', 'r');
-   }
 }
 
 ?>
\ No newline at end of file
Index: setup.php
===================================================================
--- setup.php	(revision 171)
+++ setup.php	(working copy)
@@ -9,7 +9,7 @@
  -------------------------------------------------------------------------
 
  LICENSE
-      
+
  This file is part of databases.
 
  Databases is free software; you can redistribute it and/or modify
@@ -30,46 +30,49 @@
 // Init the hooks of the plugins -Needed
 function plugin_init_databases() {
    global $PLUGIN_HOOKS;
-   
+
    $PLUGIN_HOOKS['csrf_compliant']['databases'] = true;
-   $PLUGIN_HOOKS['change_profile']['databases'] = array('PluginDatabasesProfile','changeProfile');
+   $PLUGIN_HOOKS['change_profile']['databases'] = array('PluginDatabasesProfile', 'initProfile');
    $PLUGIN_HOOKS['assign_to_ticket']['databases'] = true;
-   
+   $PLUGIN_HOOKS['assign_to_ticket_dropdown']['databases'] = true;
+   $PLUGIN_HOOKS['assign_to_ticket_itemtype']['databases'] = array('PluginDatabasesDatabase_Item');
+
    if (Session::getLoginUserID()) {
-      
+
       Plugin::registerClass('PluginDatabasesDatabase', array(
-         'linkgroup_tech_types' => true,
-         'linkuser_tech_types' => true,
-         'document_types' => true,
-         'ticket_types'         => true,
+         'linkgroup_tech_types'   => true,
+         'linkuser_tech_types'    => true,
+         'document_types'         => true,
+         'ticket_types'           => true,
          'helpdesk_visible_types' => true,
-         'addtabon' => 'Supplier'
+         'addtabon'               => 'Supplier'
       ));
-      
       Plugin::registerClass('PluginDatabasesProfile',
-                         array('addtabon' => 'Profile'));
-                         
+                            array('addtabon' => 'Profile'));
+      Plugin::registerClass('PluginDatabasesDatabase_Item',
+                            array('ticket_types' => true));
+
       if (class_exists('PluginAccountsAccount')) {
          PluginAccountsAccount::registerType('PluginDatabasesDatabase');
       }
-      
+
       $plugin = new Plugin();
-      if (!$plugin->isActivated('environment') 
+      if (!$plugin->isActivated('environment')
          && Session::haveRight("plugin_databases", READ)) {
 
          $PLUGIN_HOOKS['menu_toadd']['databases'] = array('assets'   => 'PluginDatabasesMenu');
       }
-      
+
       if (Session::haveRight("plugin_databases", CREATE)) {
          $PLUGIN_HOOKS['use_massive_action']['databases']=1;
       }
-      
+
       if (class_exists('PluginDatabasesDatabase_Item')) { // only if plugin activated
-         $PLUGIN_HOOKS['pre_item_purge']['databases'] 
+         $PLUGIN_HOOKS['pre_item_purge']['databases']
                         = array('Profile'=>array('PluginDatabasesProfile', 'purgeProfiles'));
          $PLUGIN_HOOKS['plugin_datainjection_populate']['databases'] = 'plugin_datainjection_populate_databases';
       }
-      
+
       // End init, when all types are registered
       $PLUGIN_HOOKS['post_init']['databases'] = 'plugin_databases_postinit';
 
@@ -83,12 +86,12 @@
 
    return array (
       'name' => _n('Database', 'Databases', 2, 'databases'),
-      'version' => '1.6.0',
+      'version' => '1.7.0',
       'author'  => "<a href='http://infotel.com/services/expertise-technique/glpi/'>Infotel</a>",
       'oldname' => 'sgbd',
       'license' => 'GPLv2+',
       'homepage'=>'https://forge.indepnet.net/projects/databases',
-      'minGlpiVersion' => '0.84',// For compatibility / no install in version < 0.80
+      'minGlpiVersion' => '0.85',// For compatibility / no install in version < 0.80
    );
 
 }
@@ -95,8 +98,8 @@
 
 // Optional : check prerequisites before install : may print errors or add to message after redirect
 function plugin_databases_check_prerequisites() {
-   if (version_compare(GLPI_VERSION,'0.84','lt') || version_compare(GLPI_VERSION,'0.85','ge')) {
-      _e('This plugin requires GLPI >= 0.84', 'databases');
+   if (version_compare(GLPI_VERSION,'0.85','lt') || version_compare(GLPI_VERSION,'0.86','ge')) {
+      _e('This plugin requires GLPI >= 0.85', 'databases');
       return false;
    }
    return true;
@@ -107,20 +110,6 @@
    return true;
 }
 
-function plugin_databases_haveRight($module,$right) {
-   $matches=array(
-         ""  => array("","r","w"), // ne doit pas arriver normalement
-         "r" => array("r","w"),
-         "w" => array("w"),
-         "1" => array("1"),
-         "0" => array("0","1"), // ne doit pas arriver non plus
-            );
-   if (isset($_SESSION["glpi_plugin_databases_profile"][$module])
-            && in_array($_SESSION["glpi_plugin_databases_profile"][$module],$matches[$right]))
-      return true;
-   else return false;
-}
-
 function plugin_datainjection_migratetypes_databases($types) {
    $types[2400] = 'PluginDatabasesDatabase';
    return $types;
Index: front/appliance.form.php
===================================================================
--- front/appliance.form.php	(revision 216)
+++ front/appliance.form.php	(working copy)
@@ -29,7 +29,7 @@
 
 include ("../../../inc/includes.php");
 
-Plugin::load('appliances',true);
+//Plugin::load('appliances',true);
 
 if (!isset($_GET["id"])) {
    $_GET["id"] = "";
@@ -42,27 +42,27 @@
 $PluginItem       = new PluginAppliancesAppliance_Item();
 
 if (isset($_POST["add"])) {
-   $PluginAppliances->check(-1, 'w', $_POST);
+   $PluginAppliances->check(-1, CREATE, $_POST);
    $newID = $PluginAppliances->add($_POST);
    Html::back();
 
 } else if (isset($_POST["update"])) {
-   $PluginAppliances->check($_POST['id'], 'w');
+   $PluginAppliances->check($_POST['id'], UPDATE);
    $PluginAppliances->update($_POST);
    Html::back();
 
 } else if (isset($_POST["delete"])) {
-   $PluginAppliances->check($_POST['id'], 'w');
+   $PluginAppliances->check($_POST['id'], DELETE);
    $PluginAppliances->delete($_POST);
    Html::redirect($CFG_GLPI["root_doc"]."/plugins/appliances/front/appliance.php");
 
 } else if (isset($_POST["restore"])) {
-   $PluginAppliances->check($_POST['id'],'w');
+   $PluginAppliances->check($_POST['id'], PURGE);
    $PluginAppliances->restore($_POST);
    Html::back();
 
 } else if (isset($_POST["purge"])) {
-   $PluginAppliances->check($_POST['id'], 'w');
+   $PluginAppliances->check($_POST['id'], PURGE);
    $PluginAppliances->delete($_POST, 1);
 
    Html::redirect($CFG_GLPI["root_doc"]."/plugins/appliances/front/appliance.php");
@@ -91,7 +91,7 @@
    Html::back();
 
 } else if (isset($_POST['update_optvalues'])) {
-   $PluginAppliances->check($_POST['plugin_appliances_appliances_id'], 'w');
+   $PluginAppliances->check($_POST['plugin_appliances_appliances_id'], UPDATE);
 
    $Optvalue = new PluginAppliancesOptvalue();
    $Optvalue->updateList($_POST);
@@ -98,9 +98,9 @@
    Html::back();
 
 } else if (isset($_POST["add_opt_val"])){
-   $PluginAppliances->check($_POST['plugin_appliances_appliances_id'], 'r');
+   $PluginAppliances->check($_POST['plugin_appliances_appliances_id'], READ);
    $item = new $_POST['itemtype']();
-   $item->check($_POST['items_id'], 'w');
+   $item->check($_POST['items_id'], UPDATE);
 
    $OptvalueItem = new PluginAppliancesOptvalue_Item();
    $OptvalueItem->updateList($_POST);
@@ -113,7 +113,7 @@
                      'items_id'                        => $_POST['item'],
                      'itemtype'                        => $_POST['itemtype']);
 
-      $PluginItem->check(-1, 'w', $input);
+      $PluginItem->check(-1, CREATE, $input);
       $newID = $PluginItem->add($input);
    }
    Html::back();
@@ -122,7 +122,7 @@
    foreach ($_POST["item"] as $key => $val) {
       $input = array('id' => $key);
       if ($val == 1) {
-         $PluginItem->check($key, 'w');
+         $PluginItem->check($key, PURGE);
          $PluginItem->delete($input);
       }
    }
@@ -130,28 +130,23 @@
 
 } else if (isset($_POST["deleteappliance"])) {
    $input = array('id' => $_POST["id"]);
-   $PluginItem->check($_POST["id"], 'w');
+   $PluginItem->check($_POST["id"], DELETE);
    $PluginItem->delete($input);
    Html::back();
 
 } else {
-   $PluginAppliances->checkGlobal('r');
-   if (!isset($_SESSION['glpi_tab'])) {
-      $_SESSION['glpi_tab'] = 1;
-   }
-   if (isset($_GET['onglet'])) {
-      $_SESSION['glpi_tab'] = $_GET['onglet'];
-   }
+   $PluginAppliances->checkGlobal(READ);
 
+   //check environment meta-plugin installtion for change header
    $plugin = new Plugin();
    if ($plugin->isActivated("environment")) {
-      Html::header(_n('Appliance', 'Appliances', 2, 'appliances'), $_SERVER['PHP_SELF'], "plugins",
-                   "environment", "appliances");
+      Html::header(PluginAppliancesAppliance::getTypeName(2),
+                     '',"assets","pluginenvironmentdisplay","appliances");
    } else {
-      Html::header(_n('Appliance', 'Appliances', 2, 'appliances'), $_SERVER["PHP_SELF"], "plugins",
-                   "appliances");
+      Html::header(PluginAppliancesAppliance::getTypeName(2), '', "assets",
+                   "pluginappliancesmenu");
    }
-   $PluginAppliances->showForm($_GET["id"]);
+   $PluginAppliances->display($_GET);
 
    Html::footer();
 }
Index: front/appliance.php
===================================================================
--- front/appliance.php	(revision 216)
+++ front/appliance.php	(working copy)
@@ -32,15 +32,15 @@
 $plugin = new Plugin();
 
 if ($plugin->isActivated("environment")) {
-   Html::header(_n('Appliance', 'Appliances', 2, 'appliances'), $_SERVER['PHP_SELF'], "plugins",
-                "environment", "appliances");
+   Html::header(PluginWebapplicationsWebapplication::getTypeName(2)
+                  ,'',"assets","pluginenvironmentdisplay","appliances");
 } else {
-   Html::header(_n('Appliance', 'Appliances', 2, 'appliances'), $_SERVER['PHP_SELF'], "plugins",
-                "appliances");
+   Html::header(PluginAppliancesAppliance::getTypeName(2), '', "assets","pluginappliancesmenu");
+
 }
 
-if (plugin_appliances_haveRight("appliance","r")
-    || Session::haveRight("config","w")) {
+if (Session::haveRight("plugin_appliances", READ)
+    || Session::haveRight("config", UPDATE)) {
    Search::show('PluginAppliancesAppliance');
 
 } else {
Index: hook.php
===================================================================
--- hook.php	(revision 216)
+++ hook.php	(working copy)
@@ -72,13 +72,128 @@
 
 function plugin_appliances_AssignToTicket($types) {
 
-   if (plugin_appliances_haveRight("open_ticket","1")) {
+   if (Session::haveRight("plugin_appliances_open_ticket", "1")) {
       $types['PluginAppliancesAppliance'] = _n('Appliance', 'Appliances', 2, 'appliances');
+      $types['PluginAppliancesAppliance_Item'] = _n('Appliance item', 'Appliances item', 2, 'appliances');
    }
    return $types;
 }
 
 
+function plugin_appliances_AssignToTicketDropdown($data) {
+   global $DB, $CFG_GLPI;
+
+   if ($data['itemtype'] == 'PluginAppliancesAppliance') {
+      $table = getTableForItemType($data["itemtype"]);
+      $rand = mt_rand();
+      $field_id = Html::cleanId("dropdown_".$data['myname'].$rand);
+
+      $p = array('itemtype'            => $data["itemtype"],
+                 'entity_restrict'     => $data['entity_restrict'],
+                 'table'               => $table,
+                 'myname'              => $data["myname"]);
+
+      if(isset($data["used"]) && !empty($data["used"])){
+         if(isset($data["used"][$data["itemtype"]])){
+            $p["used"] = $data["used"][$data["itemtype"]];
+         }
+      }
+
+      echo Html::jsAjaxDropdown($data['myname'], $field_id,
+                                 $CFG_GLPI['root_doc']."/ajax/getDropdownFindNum.php",
+                                 $p);
+      // Auto update summary of active or just solved tickets
+      $params = array('items_id' => '__VALUE__',
+                      'itemtype' => $data['itemtype']);
+
+      Ajax::updateItemOnSelectEvent($field_id,"item_ticket_selection_information",
+                                    $CFG_GLPI["root_doc"]."/ajax/ticketiteminformation.php",
+                                    $params);
+
+   } else if ($data['itemtype'] == 'PluginAppliancesAppliance_Item') {
+      $sql = "SELECT `glpi_plugin_appliances_appliances`.`name`, "
+              . "    `items_id`, `itemtype`, `glpi_plugin_appliances_appliances_items`.`id` "
+              . " FROM `glpi_plugin_appliances_appliances_items`"
+              . " LEFT JOIN `glpi_plugin_appliances_appliances`"
+              . "    ON `plugin_appliances_appliances_id` = `glpi_plugin_appliances_appliances`.`id`";
+
+      $result = $DB->query($sql);
+      $elements = array();
+      while ($res = $DB->fetch_array($result)) {
+         $itemtype = $res['itemtype'];
+         $item = new $itemtype;
+         $item->getFromDB($res['items_id']);
+         $elements[$res['name']][$res['id']] = $item->getName();
+      }
+      Dropdown::showFromArray('items_id', $elements, array());
+   }
+}
+
+
+function plugin_appliances_AssignToTicketDisplay($data) {
+   global $DB;
+
+   if ($data['itemtype'] == 'PluginAppliancesAppliance_Item') {
+      $paAppliance = new PluginAppliancesAppliance();
+      $item = new PluginAppliancesAppliance_Item();
+      $itemtype = $data['data']['itemtype'];
+      $iteminv = new $itemtype;
+      $iteminv->getFromDB($data['data']['items_id']);
+      $paAppliance->getFromDB($data['data']['plugin_appliances_appliances_id']);
+
+      echo "<tr class='tab_bg_1'>";
+      if ($data['canedit']) {
+         echo "<td width='10'>";
+         Html::showMassiveActionCheckBox('Item_Ticket', $data['data']["IDD"]);
+         echo "</td>";
+      }
+      $typename = "<i>".PluginAppliancesAppliance::getTypeName()."</i><br/>".
+              $iteminv->getTypeName();
+      echo "<td class='center top' rowspan='1'>".$typename."</td>";
+      echo "<td class='center'>";
+      echo "<i>".Dropdown::getDropdownName("glpi_entities", $paAppliance->fields['entities_id'])."</i>";
+      echo "<br/>";
+      echo Dropdown::getDropdownName("glpi_entities", $iteminv->fields['entities_id']);
+      echo "</td>";
+
+      $linkAppliance     = Toolbox::getItemTypeFormURL('PluginAppliancesAppliance');
+      $namelinkAppliance = "<a href=\"".$linkAppliance."?id=".
+              $paAppliance->fields['id']."\">".$paAppliance->getName()."</a>";
+      $link     = Toolbox::getItemTypeFormURL($data['data']['itemtype']);
+      $namelink = "<a href=\"".$link."?id=".$data['data']['items_id']."\">".$iteminv->getName()."</a>";
+      echo "<td class='center".
+               (isset($iteminv->fields['is_deleted']) && $iteminv->fields['is_deleted'] ? " tab_bg_2_2'" : "'");
+      echo "><i>".$namelinkAppliance."</i><br/>".$namelink;
+      echo "</td>";
+      echo "<td class='center'><i>".(isset($paAppliance->fields["serial"])? "".$paAppliance->fields["serial"]."" :"-").
+              "</i><br/>".(isset($iteminv->fields["serial"])? "".$iteminv->fields["serial"]."" :"-").
+           "</td>";
+      echo "<td class='center'>".
+             "<i>".(isset($iteminv->fields["otherserial"])? "".$iteminv->fields["otherserial"]."" :"-")."</i><br/>".
+             (isset($iteminv->fields["otherserial"])? "".$iteminv->fields["otherserial"]."" :"-")."</td>";
+      echo "</tr>";
+      return false;
+   }
+   return true;
+}
+
+
+function plugin_appliances_AssignToTicketGiveItem($data) {
+   if ($data['itemtype'] == 'PluginAppliancesAppliance_Item') {
+      $paAppliance = new PluginAppliancesAppliance();
+      $paAppliance_item = new PluginAppliancesAppliance_Item();
+
+      $paAppliance_item->getFromDB($data['name']);
+      $itemtype = $paAppliance_item->fields['itemtype'];
+      $paAppliance->getFromDB($paAppliance_item->fields['plugin_appliances_appliances_id']);
+      $item = new $itemtype;
+      $item->getFromDB($paAppliance_item->fields['items_id']);
+      return $item->getLink(array('comments' => true))." (".
+              $paAppliance->getLink(array('comments' => true)).")";
+   }
+}
+
+
 function plugin_appliances_install() {
    global $DB;
 
@@ -133,7 +248,7 @@
    // required cause autoload don't work for unactive plugin'
    include_once(GLPI_ROOT."/plugins/appliances/inc/profile.class.php");
 
-   PluginAppliancesProfile::createAdminAccess($_SESSION['glpiactiveprofile']['id']);
+   PluginAppliancesProfile::initProfile($_SESSION['glpiactiveprofile']['id']);
    return true;
 }
 
@@ -234,7 +349,7 @@
 function plugin_appliances_getAddSearchOptions($itemtype) {
 
    $sopt = array();
-   if (plugin_appliances_haveRight("appliance","r")) {
+   if (Session::haveRight("plugin_appliances", READ)) {
       if (in_array($itemtype, PluginAppliancesAppliance::getTypes(true))) {
          $sopt[1210]['table']          = 'glpi_plugin_appliances_appliances';
          $sopt[1210]['field']          = 'name';
@@ -262,6 +377,15 @@
                                                          'joinparams'
                                                           => $sopt[1210]['joinparams'])));
       }
+      if ($itemtype == 'Ticket') {
+         $sopt[1212]['table']         = 'glpi_plugin_appliances_appliances';
+         $sopt[1212]['field']         = 'name';
+         $sopt[1212]['linkfield']     = 'items_id';
+         $sopt[1212]['datatype']      = 'itemlink';
+         $sopt[1212]['massiveaction'] = false;
+         $sopt[1212]['name']          = __('Appliance', 'appliances')." - ".
+                                        __('Name');
+      }
    }
    return $sopt;
 }
@@ -338,6 +462,26 @@
             }
          }
          return $out;
+         break;
+
+      case 'glpi_plugin_appliances_appliances.name':
+         if ($type == 'Ticket') {
+            $appliances_id = array();
+            if ($data['raw']["ITEM_$num"] != '') {
+               $appliances_id = explode('$$$$', $data['raw']["ITEM_$num"]);
+            } else {
+               $appliances_id = explode('$$$$', $data['raw']["ITEM_".$num."_2"]);
+            }
+            $ret = array();
+            $paAppliance = new PluginAppliancesAppliance();
+            foreach ($appliances_id as $ap_id) {
+               $paAppliance->getFromDB($ap_id);
+               $ret[] = $paAppliance->getLink();
+            }
+            return implode('<br>', $ret);
+         }
+         break;
+
    }
    return "";
 }
@@ -477,4 +621,119 @@
 
    $INJECTABLE_TYPES['PluginAppliancesApplianceInjection'] = 'appliances';
 }
+
+
+
+function plugin_appliances_addSelect($type,$id,$num) {
+
+   $searchopt = &Search::getOptions($type);
+   $table = $searchopt[$id]["table"];
+   $field = $searchopt[$id]["field"];
+//echo "add select : ".$table.".".$field."<br/>";
+   switch ($type) {
+
+      case 'Ticket':
+
+         if ($table.".".$field == "glpi_plugin_appliances_appliances.name") {
+            return " GROUP_CONCAT(DISTINCT `glpi_plugin_appliances_appliances`.`id` SEPARATOR '$$$$') AS ITEM_$num, "
+                    . " GROUP_CONCAT(DISTINCT `glpi_plugin_appliances_appliances_bis`.`id` SEPARATOR '$$$$') AS ITEM_".$num."_2,";
+         }
+         break;
+   }
+}
+
+
+
+function plugin_appliances_addLeftJoin($itemtype,$ref_table,$new_table,$linkfield,&$already_link_tables) {
+
+   switch ($itemtype) {
+
+      case 'Ticket':
+         return " LEFT JOIN `glpi_plugin_appliances_appliances` AS glpi_plugin_appliances_appliances
+            ON (`glpi_items_tickets`.`items_id` = `glpi_plugin_appliances_appliances`.`id`
+                  AND `glpi_items_tickets`.`itemtype`='PluginAppliancesAppliance')
+
+         LEFT JOIN `glpi_plugin_appliances_appliances_items`
+            ON (`glpi_items_tickets`.`items_id` = `glpi_plugin_appliances_appliances_items`.`id`
+                  AND `glpi_items_tickets`.`itemtype`='PluginAppliancesAppliance_Item')
+         LEFT JOIN `glpi_plugin_appliances_appliances` AS glpi_plugin_appliances_appliances_bis
+            ON (`glpi_plugin_appliances_appliances_items`.`plugin_appliances_appliances_id` = `glpi_plugin_appliances_appliances_bis`.`id`)";
+         break;
+
+   }
+   return "";
+}
+
+
+
+function plugin_appliances_addWhere($link,$nott,$type,$id,$val,$searchtype) {
+
+   $searchopt = &Search::getOptions($type);
+   $table = $searchopt[$id]["table"];
+   $field = $searchopt[$id]["field"];
+
+   switch ($type) {
+
+      case 'Ticket':
+         if ($table.".".$field == "glpi_plugin_appliances_appliances.name") {
+            $out = '';
+            switch ($searchtype) {
+               case "contains" :
+                  $SEARCH = Search::makeTextSearch($val, $nott);
+                  break;
+
+               case "equals" :
+                  if ($nott) {
+                     $SEARCH = " <> '$val'";
+                  } else {
+                     $SEARCH = " = '$val'";
+                  }
+                  break;
+
+               case "notequals" :
+                  if ($nott) {
+                     $SEARCH = " = '$val'";
+                  } else {
+                     $SEARCH = " <> '$val'";
+                  }
+                  break;
+
+            }
+            if (in_array($searchtype, array('equals', 'notequals'))) {
+               if ($table != getTableForItemType($type) || $type == 'States') {
+                  $out = " $link (`glpi_plugin_appliances_appliances`.`id`".$SEARCH;
+               } else {
+                  $out = " $link (`glpi_plugin_appliances_appliances`.`$field`".$SEARCH;
+               }
+               if ($searchtype=='notequals') {
+                  $nott = !$nott;
+               }
+               // Add NULL if $val = 0 and not negative search
+               // Or negative search on real value
+               if ((!$nott && $val==0) || ($nott && $val != 0)) {
+                  $out .= " OR `glpi_plugin_appliances_appliances`.`id` IS NULL";
+               }
+//               $out .= ')';
+               $out1 = $out;
+               $out = str_replace(" ".$link." (", " ".$link." ", $out);
+            } else {
+               $out = Search::makeTextCriteria("`glpi_plugin_appliances_appliances`.".$field,$val,$nott,$link);
+               $out1 = $out;
+               $out = preg_replace("/^ $link/", $link.' (', $out);
+            }
+            $out2 = $out." OR ";
+            $out2 .= str_replace("`glpi_plugin_appliances_appliances`",
+                                 "`glpi_plugin_appliances_appliances_bis`", $out1)." ";
+            $out2 = str_replace("OR   AND", "OR", $out2);
+            $out2 = str_replace("OR   OR", "OR", $out2);
+            $out2 = str_replace("AND   OR", "OR", $out2);
+            $out2 = str_replace("OR  AND", "OR", $out2);
+            $out2 = str_replace("OR  OR", "OR", $out2);
+            $out2 = str_replace("AND  OR", "OR", $out2);
+            return $out2.")";
+         }
+         break;
+   }
+}
+
 ?>
\ No newline at end of file
Index: inc/appliance.class.php
===================================================================
--- inc/appliance.class.php	(revision 216)
+++ inc/appliance.class.php	(working copy)
@@ -38,6 +38,7 @@
                          'Printer', 'Software');
 
    public $dohistory = true;
+   static $rightname = "plugin_appliances";
 
 
    static function getTypeName($nb=0) {
@@ -48,17 +49,6 @@
       return _n('Appliance', 'Appliances', 1, 'appliances');
    }
 
-
-   static function canCreate() {
-      return plugin_appliances_haveRight('appliance', 'w');
-   }
-
-
-   static function canView() {
-      return plugin_appliances_haveRight('appliance', 'r');
-   }
-
-
    /**
     * Retrieve an Appliance from the database using its externalid (unique index)
     *
@@ -198,6 +188,7 @@
    function defineTabs($options=array()) {
 
       $ong = array();
+      $this->addDefaultFormTab($ong);
       $this->addStandardTab('PluginAppliancesAppliance_Item', $ong, $options);
       $this->addStandardTab('PluginAppliancesOptvalue', $ong, $options);
       $this->addStandardTab('Ticket', $ong, $options);
@@ -228,19 +219,11 @@
    function showForm ($ID, $options=array()) {
       global $CFG_GLPI;
 
-      if ($ID>0) {
-         $this->check($ID,'r');
-      } else {
-         $this->check(-1, 'w');
-         $this->getEmpty();
-      }
+      $this->initForm($ID, $options);
+      $this->showFormHeader($options);
 
-      $canedit = $this->can($ID,'w');
-      $canrecu = $this->can($ID,'recursive');
+      $canedit = $this->can($ID, UPDATE);
 
-      $this->showTabs($options);
-      $this->showFormHeader($options);
-
       echo "<tr class='tab_bg_1'>";
       echo "<td>".__('Name')."</td><td>";
       Html::autocompletionTextField($this, "name", array('size' => 34));
@@ -349,8 +332,6 @@
       echo "</td></tr>";
 
       $this->showFormButtons($options);
-      echo "<div id='tabcontent'></div>";
-      echo "<script type='text/javascript'>loadDefaultTab();</script>";
 
       return true;
    }
Index: inc/appliance_item.class.php
===================================================================
--- inc/appliance_item.class.php	(revision 216)
+++ inc/appliance_item.class.php	(working copy)
@@ -42,6 +42,15 @@
    static public $items_id_2 = 'items_id';
 
 
+   static function getTypeName($nb=0) {
+
+      if ($nb > 1) {
+         return _n('Appliance item', 'Appliances items', 2, 'appliances');
+      }
+      return _n('Appliance item', 'Appliances items', 1, 'appliances');
+   }
+
+
    function cleanDBonPurge() {
 
       $temp = new PluginAppliancesOptvalue_Item();
@@ -99,8 +108,8 @@
 
       $ID       = $item->getField('id');
       $itemtype = get_Class($item);
-      $canread  = $item->can($ID,'r');
-      $canedit  = $item->can($ID,'w');
+      $canread  = $item->can($ID, READ);
+      $canedit  = $item->can($ID, UPDATE);
 
       $query = "SELECT `glpi_plugin_appliances_appliances_items`.`id` AS entID,
                        `glpi_plugin_appliances_appliances`.*
@@ -333,7 +342,7 @@
       if (!$appli->can($instID,"r")) {
          return false;
       }
-      if (!plugin_appliances_haveRight("appliance","r")) {
+      if (!Session::haveRight("plugin_appliances", READ)) {
          return false;
       }
 
@@ -449,12 +458,12 @@
 
       $instID = $appli->fields['id'];
 
-      if (!$appli->can($instID,"r")) {
+      if (!$appli->can($instID, READ)) {
          return false;
       }
       $rand = mt_rand();
 
-      $canedit = $appli->can($instID,'w');
+      $canedit = $appli->can($instID, UPDATE);
 
       $query = "SELECT DISTINCT `itemtype`
                 FROM `glpi_plugin_appliances_appliances_items`
@@ -626,7 +635,7 @@
             return __('Associated item', 'Associated items', 2);
 
          } else if (in_array($item->getType(), PluginAppliancesAppliance::getTypes(true))
-                    && plugin_appliances_haveRight('appliance', 'r')) {
+                    && Session::haveRight('plugin_appliances', READ)) {
             if ($_SESSION['glpishow_count_on_tabs']) {
                return self::createTabEntry(PluginAppliancesAppliance::getTypeName(2),
                                            self::countForItem($item));
Index: inc/appliancetype.class.php
===================================================================
--- inc/appliancetype.class.php	(revision 216)
+++ inc/appliancetype.class.php	(working copy)
@@ -34,6 +34,7 @@
 
 class PluginAppliancesApplianceType extends CommonDropdown {
 
+   static $rightname = "entity_dropdown";
 
    static function getTypeName($nb=0) {
       return __('Type of appliance', 'appliances');
@@ -40,16 +41,6 @@
    }
 
 
-   static function canCreate() {
-      return Session::haveRight('entity_dropdown', 'w');
-   }
-
-
-   static function canView() {
-      return Session::haveRight('entity_dropdown', 'r');
-   }
-
-
    function prepareInputForAdd($input) {
 
       if (array_key_exists('externalid',$input) && !$input['externalid']) {
Index: inc/profile.class.php
===================================================================
--- inc/profile.class.php	(revision 216)
+++ inc/profile.class.php	(working copy)
@@ -32,140 +32,216 @@
 }
 
 
-class PluginAppliancesProfile extends CommonDBTM {
+class PluginAppliancesProfile extends Profile {
 
+   static $rightname = "profile";
 
-   // if profile deleted
-   static function cleanProfile(Profile $prof) {
+   function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
 
-      $plugprof = new self();
-      $plugprof->delete(array('id' => $prof->getID()));
+      if ($item->getType()=='Profile') {
+            return PluginAppliancesAppliance::getTypeName(2);
+      }
+      return '';
    }
 
 
-   // if profile cloned
-   static function cloneProfile(Profile $prof) {
+   static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
 
-      $plugprof = new self();
-      if ($plugprof->getFromDB($prof->input['_old_id'])) {
-         $input = ToolBox::addslashes_deep($plugprof->fields);
-         $input['id'] = $prof->getID();
-         $plugprof->add($input);
+      if ($item->getType()=='Profile') {
+         $ID = $item->getID();
+         $prof = new self();
+
+         self::addDefaultProfileInfos($ID,
+                                    array('plugin_appliances'               => 0,
+                                          'plugin_appliances_open_ticket'   => 0));
+         $prof->showForm($ID);
       }
+      return true;
    }
 
+   static function createFirstAccess($ID) {
+      //85
+      self::addDefaultProfileInfos($ID,
+                                   array('plugin_appliances'             => 127,
+                                         'plugin_appliances_open_ticket' => 1), true);
+   }
 
-   static function select() {
+    /**
+    * @param $profile
+   **/
+   static function addDefaultProfileInfos($profiles_id, $rights, $drop_existing = false) {
 
-      $prof = new self();
-      if ($prof->getFromDB($_SESSION['glpiactiveprofile']['id'])) {
-         $_SESSION["glpi_plugin_appliances_profiles"] = $prof->fields;
-      } else {
-         unset($_SESSION["glpi_plugin_appliances_profiles"]);
+      $profileRight = new ProfileRight();
+      foreach ($rights as $right => $value) {
+         if (countElementsInTable('glpi_profilerights',
+                                   "`profiles_id`='$profiles_id' AND `name`='$right'") && $drop_existing) {
+            $profileRight->deleteByCriteria(array('profiles_id' => $profiles_id, 'name' => $right));
+         }
+         if (!countElementsInTable('glpi_profilerights',
+                                   "`profiles_id`='$profiles_id' AND `name`='$right'")) {
+            $myright['profiles_id'] = $profiles_id;
+            $myright['name']        = $right;
+            $myright['rights']      = $value;
+            $profileRight->add($myright);
+
+            //Add right to the current session
+            $_SESSION['glpiactiveprofile'][$right] = $value;
+         }
       }
    }
 
 
-   //profiles modification
-   function showForm($ID, $options=array()) {
+   /**
+    * Show profile form
+    *
+    * @param $items_id integer id of the profile
+    * @param $target value url of target
+    *
+    * @return nothing
+    **/
+   function showForm($profiles_id=0, $openform=TRUE, $closeform=TRUE) {
 
-      $target = $this->getFormURL();
-      if (isset($options['target'])) {
-        $target = $options['target'];
+      echo "<div class='firstbloc'>";
+      if (($canedit = Session::haveRightsOr(self::$rightname, array(CREATE, UPDATE, PURGE)))
+          && $openform) {
+         $profile = new Profile();
+         echo "<form method='post' action='".$profile->getFormURL()."'>";
       }
 
-      if (!Session::haveRight("profile","r")) {
-         return false;
+      $profile = new Profile();
+      $profile->getFromDB($profiles_id);
+      if ($profile->getField('interface') == 'central') {
+         $rights = $this->getAllRights();
+         $profile->displayRightsChoiceMatrix($rights, array('canedit'       => $canedit,
+                                                         'default_class' => 'tab_bg_2',
+                                                         'title'         => __('General')));
       }
+      echo "<table class='tab_cadre_fixehov'>";
+      echo "<tr class='tab_bg_1'><th colspan='4'>".__('Helpdesk')."</th></tr>\n";
 
-      $canedit = Session::haveRight("profile", "w");
-      $prof = new Profile();
-      if ($ID) {
-         $this->getFromDB($ID);
-         $prof->getFromDB($ID);
-      }
-      echo "<form action='".$target."' method='post'>";
-      echo "<table class='tab_cadre_fixe'>";
-
-      echo "<tr><th colspan='2'>".sprintf(__('%1$s %2$s'), __('Rights management', 'appliances'),
-                                          $this->fields["name"]);
-      echo "</th></tr>";
-
+      $effective_rights = ProfileRight::getProfileRights($profiles_id, array('plugin_appliances_open_ticket'));
       echo "<tr class='tab_bg_2'>";
-      echo "<td>".__('Appliances', 'appliances')."</td><td>";
+      echo "<td width='20%'>".__('Associable items to a ticket')."</td>";
+      echo "<td colspan='5'>";
+      Html::showCheckbox(array('name'    => '_plugin_appliances_open_ticket',
+                               'checked' => $effective_rights['plugin_appliances_open_ticket']));
+      echo "</td></tr>\n";
+      echo "</table>";
 
-      if ($prof->fields['interface'] != 'helpdesk') {
-         Profile::dropdownNoneReadWrite("appliance", $this->fields["appliance"], 1, 1, 1);
-      } else {
-         _e('No access');
+      if ($canedit
+          && $closeform) {
+         echo "<div class='center'>";
+         echo Html::hidden('id', array('value' => $profiles_id));
+         echo Html::submit(_sx('button', 'Save'), array('name' => 'update'));
+         echo "</div>\n";
+         Html::closeForm();
       }
-      echo "</td></tr>";
+      echo "</div>";
+   }
 
-      echo "<tr class='tab_bg_2'>";
-      echo "<td>".__('Linkable items to a ticket - Appliances')."</td><td>";
-      if ($prof->fields['create_ticket']) {
-         Dropdown::showYesNo("open_ticket", $this->fields["open_ticket"]);
-      } else {
-         echo Dropdown::getYesNo(0);
+   static function getAllRights($all = false) {
+      $rights = array(
+          array('itemtype'  => 'PluginAppliancesAppliance',
+                'label'     => _n('Appliance', 'Aplpiances', 2, 'appliances'),
+                'field'     => 'plugin_appliances'
+          ),
+      );
+
+      if ($all) {
+         $rights[] = array('itemtype' => 'PluginAppliancesAppliance',
+                           'label'    =>  __('Associable items to a ticket'),
+                           'field'    => 'plugin_appliances_open_ticket');
       }
-      echo "</td></tr>";
 
-      if ($canedit) {
-         echo "<tr class='tab_bg_1'>";
-         echo "<td class='center' colspan='2'>";
-         echo "<input type='hidden' name='id' value='".$ID."'>";
-         echo "<input type='submit' name='update_user_profile' value=\""._sx('button', 'Update')."\"
-               class='submit'>";
-         echo "</td></tr>";
-      }
-      echo "</table>";
-      Html::closeForm();
+      return $rights;
    }
 
+   /**
+    * Init profiles
+    *
+    **/
 
-   static function createAdminAccess($ID) {
+   static function translateARight($old_right) {
+      switch ($old_right) {
+         case '':
+            return 0;
+         case 'r' :
+            return READ;
+         case 'w':
+            return ALLSTANDARDRIGHT + READNOTE + UPDATENOTE;
+         case '0':
+         case '1':
+            return $old_right;
 
-      $myProf = new self();
-      if (!$myProf->GetfromDB($ID)) {
-         $Profile = new Profile();
-         $Profile->GetfromDB($ID);
-         $name = $Profile->fields["name"];
-
-         $myProf->add(array('id'          => $ID,
-                            'name'        => $name,
-                            'appliance'   => 'w',
-                            'open_ticket' => '1'));
+         default :
+            return 0;
       }
    }
 
+   /**
+   * @since 0.85
+   * Migration rights from old system to the new one for one profile
+   * @param $profiles_id the profile ID
+   */
+   static function migrateOneProfile($profiles_id) {
+      global $DB;
+      //Cannot launch migration if there's nothing to migrate...
+      if (!TableExists('glpi_plugin_appliances_profiles')) {
+      return true;
+      }
 
-   function createUserAccess($Profile) {
+      foreach ($DB->request('glpi_plugin_appliances_profiles',
+                            "`profiles_id`='$profiles_id'") as $profile_data) {
 
-      return $this->add(array('id'   => $Profile->getField('id'),
-                              'name' => $Profile->getField('name')));
+         $matching = array('appliances'    => 'plugin_appliances',
+                           'open_ticket' => 'plugin_appliances_open_ticket');
+         $current_rights = ProfileRight::getProfileRights($profiles_id, array_values($matching));
+         foreach ($matching as $old => $new) {
+            if (!isset($current_rights[$old])) {
+               $query = "UPDATE `glpi_profilerights`
+                         SET `rights`='".self::translateARight($profile_data[$old])."'
+                         WHERE `name`='$new' AND `profiles_id`='$profiles_id'";
+               $DB->query($query);
+            }
+         }
+      }
    }
 
+   /**
+   * Initialize profiles, and migrate it necessary
+   */
+   static function initProfile() {
+      global $DB;
+      $profile = new self();
 
-   function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
+      //Add new rights in glpi_profilerights table
+      foreach ($profile->getAllRights(true) as $data) {
+         if (countElementsInTable("glpi_profilerights",
+                                  "`name` = '".$data['field']."'") == 0) {
+            ProfileRight::addProfileRights(array($data['field']));
+         }
+      }
 
-      if ($item->getType()=='Profile') {
-         return __('Appliances', 'appliances');
+      //Migration old rights in new ones
+      foreach ($DB->request("SELECT `id` FROM `glpi_profiles`") as $prof) {
+         self::migrateOneProfile($prof['id']);
       }
-      return '';
+      foreach ($DB->request("SELECT *
+                           FROM `glpi_profilerights`
+                           WHERE `profiles_id`='".$_SESSION['glpiactiveprofile']['id']."'
+                              AND `name` LIKE '%plugin_appliances%'") as $prof) {
+         $_SESSION['glpiactiveprofile'][$prof['name']] = $prof['rights'];
+      }
    }
 
 
-   static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
-      global $CFG_GLPI;
-
-      if ($item->getType()=='Profile') {
-         $ID = $item->getField('id');
-         $prof = new self();
-         if ($prof->GetfromDB($ID) || $prof->createUserAccess($item)) {
-            $prof->showForm($ID);
+   static function removeRightsFromSession() {
+      foreach (self::getAllRights(true) as $right) {
+         if (isset($_SESSION['glpiactiveprofile'][$right['field']])) {
+            unset($_SESSION['glpiactiveprofile'][$right['field']]);
          }
       }
-      return true;
    }
+
 }
 ?>
\ No newline at end of file
Index: setup.php
===================================================================
--- setup.php	(revision 216)
+++ setup.php	(working copy)
@@ -47,7 +47,7 @@
    Plugin::registerClass('PluginAppliancesProfile', array('addtabon' => 'Profile'));
    Plugin::registerClass('PluginAppliancesEnvironment');
    Plugin::registerClass('PluginAppliancesApplianceType');
-   Plugin::registerClass('PluginAppliancesAppliance_Item');
+   Plugin::registerClass('PluginAppliancesAppliance_Item', array('ticket_types' => true));
    Plugin::registerClass('PluginAppliancesOptvalue');
    Plugin::registerClass('PluginAppliancesOptvalue_Item');
    Plugin::registerClass('PluginAppliancesRelation');
@@ -77,8 +77,10 @@
 
    $PLUGIN_HOOKS['migratetypes']['appliances'] = 'plugin_datainjection_migratetypes_appliances';
 
-   $PLUGIN_HOOKS['change_profile']['appliances']   = array('PluginAppliancesProfile','select');
+   $PLUGIN_HOOKS['change_profile']['appliances']   = array('PluginAppliancesProfile','initProfile');
    $PLUGIN_HOOKS['assign_to_ticket']['appliances'] = true;
+   $PLUGIN_HOOKS['assign_to_ticket_dropdown']['appliances'] = true;
+   $PLUGIN_HOOKS['assign_to_ticket_itemtype']['appliances'] = array('PluginAppliancesAppliance_Item');
 
    if (class_exists('PluginAppliancesAppliance')) { // only if plugin activated
       $PLUGIN_HOOKS['pre_item_purge']['appliances']
@@ -91,8 +93,18 @@
                                        = 'plugin_datainjection_populate_appliances';
    }
 
-   if (isset($_SESSION["glpiID"])) {
+   //if glpi is loaded
+   if (Session::getLoginUserID()) {
 
+      //if environment plugin is not installed
+      $plugin = new Plugin();
+      if (!$plugin->isActivated('environment')
+         && Session::haveRight("plugin_appliances", READ)) {
+
+         $PLUGIN_HOOKS['menu_toadd']['appliances'] = array('assets' => 'PluginAppliancesMenu');
+      }
+
+
       if (isset($_SESSION["glpi_plugin_environment_installed"])
           && ($_SESSION["glpi_plugin_environment_installed"] == 1)) {
 
@@ -99,7 +111,7 @@
          $_SESSION["glpi_plugin_environment_appliances"] = 1;
 
          // Display a menu entry ?
-         if (plugin_appliances_haveRight("appliance","r")) {
+         if (Session::haveRight("plugin_appliances", READ)) {
             $PLUGIN_HOOKS['menu_entry']['appliances'] = false;
             $PLUGIN_HOOKS['submenu_entry']['environment']['options']['appliances']['title']
                                                       = _n('Appliance', 'Appliances', 2, 'appliances');
@@ -109,7 +121,7 @@
                                                       = '/plugins/appliances/front/appliance.php';
          }
 
-         if (plugin_appliances_haveRight("appliance","w")) {
+         if (Session::haveRight("plugin_appliances", CREATE)) {
             $PLUGIN_HOOKS['submenu_entry']['environment']['options']['appliances']['links']['add']
                                           = '/plugins/appliances/front/appliance.form.php';
             $PLUGIN_HOOKS['use_massive_action']['appliances'] = 1;
@@ -117,12 +129,12 @@
 
        } else {
          // Display a menu entry ?
-         if (plugin_appliances_haveRight("appliance","r")) {
+         if (Session::haveRight("plugin_appliances", READ)) {
             $PLUGIN_HOOKS['menu_entry']['appliances']      = 'front/appliance.php';
             $PLUGIN_HOOKS['submenu_entry']['appliances']['search'] = 'front/appliance.php';
          }
 
-         if (plugin_appliances_haveRight("appliance","w")) {
+         if (Session::haveRight("plugin_appliances", CREATE)) {
             $PLUGIN_HOOKS['submenu_entry']['appliances']['add']
                                                            = 'front/appliance.form.php?new=1';
             $PLUGIN_HOOKS['use_massive_action']['appliances'] = 1;
@@ -144,12 +156,12 @@
 function plugin_version_appliances() {
 
    return array('name'           => __('Appliances', 'appliances'),
-                'version'        => '1.9.1',
+                'version'        => '2.0.0',
                 'oldname'        => 'applicatifs',
                 'author'         => 'Remi Collet, Xavier Caillaud, Nelly Mahu-Lasson',
                 'license'        => 'GPLv2+',
                 'homepage'       => 'https://forge.indepnet.net/projects/show/appliances',
-                'minGlpiVersion' => '0.84');
+                'minGlpiVersion' => '0.85');
 }
 
 
@@ -156,8 +168,8 @@
 // Optional : check prerequisites before install : may print errors or add to message after redirect
 function plugin_appliances_check_prerequisites() {
 
-   if (version_compare(GLPI_VERSION,'0.84','lt') || version_compare(GLPI_VERSION,'0.85','ge')) {
-      echo "This plugin requires GLPI >= 0.84 and GLPI < 0.85";
+   if (version_compare(GLPI_VERSION,'0.85','lt') || version_compare(GLPI_VERSION,'0.86','ge')) {
+      echo "This plugin requires GLPI >= 0.85 and GLPI < 0.86";
       return false;
    }
    return true;
@@ -170,22 +182,6 @@
 }
 
 
-function plugin_appliances_haveRight($module,$right) {
-
-   $matches = array(""  => array("","r","w"), // ne doit pas arriver normalement
-                    "r" => array("r","w"),
-                    "w" => array("w"),
-                    "1" => array("1"),
-                    "0" => array("0", "1")); // ne doit pas arriver non plus
-
-   if (isset($_SESSION["glpi_plugin_appliances_profiles"][$module])
-       && in_array($_SESSION["glpi_plugin_appliances_profiles"][$module],$matches[$right])) {
-      return true;
-   }
-   return false;
-}
-
-
 function plugin_datainjection_migratetypes_appliances($types) {
 
    $types[1200] = 'PluginAppliancesAppliance';
_______________________________________________
Glpi-dev mailing list
Glpi-dev@gna.org
https://mail.gna.org/listinfo/glpi-dev

Reply via email to