Bonjour,

J'ai fait un petit script pour synchroniser les groupes et localisations 
des utilisateurs à partir des ordinateurs qui leurs sont affectés :

Pour faire ce que peut !

$ cat ./glpi/scripts/update_users_groups_from_computers.php

<?php
/*
  * @version $Id: update_users_groups_from_computers.php 1 2013-02-28 
17:00:00Z fguerin $
  -------------------------------------------------------------------------
  GLPI - Gestionnaire Libre de Parc Informatique
  Copyright (C) 2003-2012 by the INDEPNET Development Team.

  http://indepnet.net/   http://glpi-project.org
  -------------------------------------------------------------------------

  LICENSE

  This file is part of GLPI.

  GLPI is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  GLPI is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with GLPI. If not, see <http://www.gnu.org/licenses/>.
  --------------------------------------------------------------------------
  */

// ----------------------------------------------------------------------
// Original Author of file: François GUÉRIN
// Purpose of file: Update users groups_id based on computers groupes_id
// ----------------------------------------------------------------------
ini_set("memory_limit","-1");
ini_set("max_execution_time", "0");


// command line parameters
$dry_run = FALSE;
$silent = FALSE;
$verbose = FALSE;

// 
=============================================================================
// argv parameters
// 
=============================================================================
if ($argv) {
     global $verbose, $silent, $dry_run;
     for ($i=1 ; $i<count($argv) ; $i++) {
       //To be able to use = in search filters, enter \= instead in 
command line
       //Replace the \= by ° not to match the split function
       $arg   = str_replace('\=', '°', $argv[$i]);
       $it    = explode("=",$arg);
       $it[0] = preg_replace('/^--/', '', $it[0]);
       $it[0] = preg_replace('/^-/', '', $it[0]);

       //Replace the ° by = the find the good filter
       $it           = str_replace('°', '=', $it);
       $_GET[$it[0]] = $it[1];
    }

     if (isset($_GET["h"]) || isset($_GET["help"])) {
       usage();
     }

     if (isset($_GET["v"]) || isset($_GET["verbose"])) {
         $verbose = TRUE;
     }

     if (isset($_GET["s"]) || isset($_GET["silent"])) {
         $silent = TRUE;
     }

     if (isset($_GET["d"]) || isset($_GET["dry-run"])) {
         $dry_run = TRUE;
     }

     if (isset($_GET["loop_limit"]) ||  isset($_GET["l"]))) {
         $LOOP_LIMIT =
     }
}


// 
=============================================================================
// Initialization
// 
=============================================================================
define('GLPI_ROOT', '..');
include (GLPI_ROOT . "/inc/includes.php");

// No debug mode
// $_SESSION['glpi_use_mode'] = NORMAL_MODE;
$_SESSION['glpi_use_mode'] = NORMAL_MODE;

// Traces levels
const LEVEL_FATAL      = 0; // Fatal error
const LEVEL_ERROR      = 1; // Error
const LEVEL_WARNING    = 2; // Warning
const LEVEL_INFO       = 3; // Info trace
const LEVEL_DEBUG      = 4; // DEBUG TRACE

$STR_LEVELS = array(LEVEL_FATAL=>'FATAL', LEVEL_ERROR=>'ERROR',
                     LEVEL_WARNING=>'WARNING', LEVEL_INFO=>'INFO',
                     LEVEL_DEBUG=>'DEBUG');

// Curent logging level
$LOGGING_LEVEL = LEVEL_DEBUG;
$LOOP_LIMIT = 0;

if ($LOOP_LIMIT == 0) {
     $LOOP_LIMIT = 9999999;
}


// Queries
const SELECT_COMPUTERS = "SELECT * FROM `glpi_computers` ORDER BY `id`;";
const SELECT_GROUP = 'SELECT * FROM `glpi_groups` WHERE `id` = \'%d\';';
const SELECT_USER = 'SELECT * FROM `glpi_users` WHERE `id` = \'%d\';';
const SELECT_LOCATION = 'SELECT * FROM `glpi_locations` WHERE `id` = 
\'%d\';';
const SELECT_GROUPS_USERS = 'SELECT * FROM `glpi_groups_users` WHERE 
`groups_id` = \'%d\' AND `users_id` = \'%d\';'; // (groups_id, users_id)
const INSERT_GROUPS_USERS = 'INSERT INTO `glpi_groups_users` (`id`, 
`groups_id`, `users_id`, `is_dynamic`, `is_manager`, `is_userdelegate`) 
VALUES (NULL, \'%d\', \'%d\', 0, 0, 0);'; // (groups_id; users_id)


// tests connection state
// TODO: Does not work !
if ($DB->connected) {
     ldebug("main: DB CONNECTED !");
} else {
     print_trace(LEVEL_ERROR, "main: DB connection FAILED !");
     exit(2);
}


// 
=============================================================================
// Main program
// 
=============================================================================
// Looks for users ans groups from computers
ldebug("main: $query = *".SELECT_COMPUTERS."* !");
$result = $DB->query(SELECT_COMPUTERS);
// ldebug("main: \$result = *$result* !");
if ($result) {
    if ($DB->numrows($result)>0) {
       $count = 0;
       $count_update_user = 0;
       $count_update_group = 0;
       $count_update_location = 0;

       while ($data=$DB->fetch_array($result))  {

           ldebug('main: $data = '.array2str($data));

           if ($count >= $LOOP_LIMIT) {
                 linfo('main: $LOOP_LIMIT atteint !');
                 break;
           }

           // Loop limit
           $count += 1;
           // DEBUG $data
           // ldebug('main: computer \$data : '.array2str($data));
           // $current_computer->$fields = array();
           $current_computer = new Computer();
           foreach ($data as $key => $val) {
               // ldebug(sprintf('main: computer \$key (%s) => \$val 
(%s)', $key, $val));
               if (! is_int($key)) {
                   $current_computer->fields[$key] = $val;
               }
           }
           // ldebug('main: computer : 
'.array2str($current_computer->fields));

           if ($current_computer != NULL) {
               ldebug('main: computer found : 
'.$current_computer->fields['name']);
           } else {
               print_trace(LEVEL_WARNING, 'main: NO computer found !');
               continue;
           }

           // Loading user from DB
           $current_user = get_user($current_computer->fields['users_id']);
           $current_location = 
get_location($current_computer->fields['locations_id']);
           $current_group = 
get_group($current_computer->fields['groups_id']);

           // Traces
           ldebug(sprintf("main: \$computer = %s / \$user = %s / \$group 
= %s /  \$location = %s",
             $current_computer->fields['name'],
             $current_user->fields['name'],
             $current_group->fields['name'],
             $current_location->fields['name']));

           if ($current_user == NULL) {
               linfo('main: No user defined, nothing to do.');
               continue;
           }

           $count_update_user += 1;
           if ($current_group != NULL)  {
               $users_id = $current_user->fields['id'];
               $groups_id = $current_group->fields['id'];

               $groups = Group_User::getUserGroups($users_id);
               // ldebug('main: groups = '.array2str($groups));
               $found = FALSE;
               foreach ($groups as $group) {
                   if ($group->fields['id'] == $groups_id) {
                       $found = TRUE;
                       ldebug('main: group found : '.$group->fields['id']);
                       break;
                   }
               }

               if (! $found) {
                   $count_update_group += 1;

                   // Check for unicity
                   $query = sprintf(SELECT_GROUPS_USERS, $groups_id, 
$users_id);
                   $result_group_select = $DB->query($query);
                   if ($count_rows=$DB->numrows($result_group)>0){
                       lwarning('main: Group '.$groups_id.' already 
defined for user '.$users_id.' / $count_rows = '.$count_rows);
                       continue;
                   }


                   $query = sprintf(INSERT_GROUPS_USERS, $groups_id, 
$users_id);
                   ldebug('main: Group update query : *'.$query.'*');


                   if (! $dry_run) {
                       try {
                         $result_group_insert = $DB->query($query);
                       } catch (Exception $e) {
                         lwarning($e);
                       }
                       ldebug('main: \$result = '.$result);
                   }
               }
           }
           if ($current_location != NULL)  {
               $count_update_location += 1;
               if (! $dry_run) {
                   $change = 
array('locations_id'=>$current_location->fields['id']);
                   $current_user->updateInDB($change);
               }
           }
       }
       // Affichage des traces de fin
       linfo("main: OK DONE !");
       linfo('main: Nombre total d\'utilisateurs mis à jour : 
'.$count_update_user);
       linfo('main: Nombre total de groupes mis à jour : 
'.$count_update_group);
       linfo('main: Nombre total de localisations mis à jour : 
'.$count_update_location);
       exit(0);
     } else {
         lwarning("main: NO DATA !");
         exit(1);
     }
} else  {
     lfatal("main: Unable to fetch DATA : ");
     exit(2);
}


// BD Accessors
function get_user($users_id) {
     global $DB;
     $user = new User();
     $query = sprintf(SELECT_USER, $users_id);
     // ldebug('get_user() users_id = '.$users_id);
     $result = $DB->query($query);
     if ($result && $DB->numrows($result) == 1) {
         $data = $DB->fetch_array($result);
         // ldebug('get_user() $data = '.array2str($data));
         foreach($data as $key => $val) {
             if (! is_int($key)) {
                 $user->fields[$key] = $val;
             }
         }
         return $user;
     } else {
         return NULL;
     }
}

function get_group($groups_id) {
     global $DB;
     $group = new Group();
     $query = sprintf(SELECT_GROUP, $groups_id);
     // ldebug('get_group() groups_id = '.$groups_id);
     $result = $DB->query($query);
     if ($result && $DB->numrows($result) == 1) {
         $data = $DB->fetch_array($result);
         // ldebug('get_group() $data = '.array2str($data));
         foreach($data as $key => $val) {
             if (! is_int($key)) {
                 $group->fields[$key] = $val;
             }
         }
         return $group;
     } else {
         return NULL;
     }
}

function get_location($locations_id) {
     global $DB;
     $location = new Location();
     $query = sprintf(SELECT_LOCATION, $locations_id);
     // ldebug('get_location() locations_id = '.$locations_id);
     $result = $DB->query($query);
     if ($result && $DB->numrows($result) == 1) {
         $data = $DB->fetch_array($result);
         // ldebug('get_location() $data = '.array2str($data));
         foreach($data as $key => $val) {
             if (! is_int($key)) {
                 $location->fields[$key] = $val;
             }
         }
         return $location;
     } else {
         return NULL;
     }
}



// 
=============================================================================
// Utilities
// 
=============================================================================

// print traces if needed and if not silent mode
function print_trace($level, $text) {
     global $silent, $LOGGING_LEVEL, $STR_LEVELS;

     // Verify if logging is possibel and in asked logging level < 
$LOGGING_LEVEL
     if ((! $silent) && ($level <= $LOGGING_LEVEL)) {
         echo $STR_LEVELS[$level]."::".$text  . "\n";
         return true;
     }
     return false;

}

// log as DEBUG
function ldebug($text) {
     return print_trace(LEVEL_DEBUG, $text);
}

// log as INFO
function linfo($text) {
     return print_trace(LEVEL_INFO, $text);
}

// log as WARNING
function lwarning($text) {
     return print_trace(LEVEL_WARNING, $text);
}

// log as ERROR
function lerror($text) {
     return print_trace(LEVEL_ERROR, $text);
}

// log as FATAL
function lfatal($text) {
     return print_trace(LEVEL_FATAL, $text);
}

// Display an array as a string {'foo': 'bar', [...]}
function array2str($array) {
     $output = "{";
     foreach ($array as $key => $val) {
         if (is_array($val)) {
              return '\''.$key.'\': '.array2str($val);
         }
         $output .= '\''.$key.'\': \''.$val.'\', ';
     }
     return $output."}";
}

// print usage and exit
function usage() {
    echo "Usage : php -q -f update_users_groups_from_computers.php 
[-dvsh]\n";
    echo "   Arguments:";
    echo "    -h --help : Do not perform any operation";
    echo "    -d --dry-run : Do not perform any operation";
    echo "    -v --verbose : Verbose (debugging purpose)";
    echo "    -s --silent : Verbose (debugging purpose)";
    exit(0);
}
?>

-- 
François GUÉRIN
D.I.T -- Service Applications
Mairie de Tourcoing
(0)3 20 23 38 48

_______________________________________________
Glpi-dev mailing list
[email protected]
https://mail.gna.org/listinfo/glpi-dev

Reply via email to