Global Address Book

Get help from the community here.

Moderator: Developers

Global Address Book

Postby GoAlways » Tue Jun 14, 2011 5:38 am

:?: How is it possible to have a Global Address Book (managed by an administrator) where everyone who is a Group Office user is automatically added to the global address book in "Contacts" at the time when the user's account is created ?

I noticed that in Group Office, when in "Email" and composing a new email and selecting "Address Book", there are tabs for Users, Groups, Contacts, Companies and Addresslists. However when in the "Addressbook", there is only Contacts and Companies. It would be nice if the Address book could also have this "Users" tab

It is possilbe for uses to select any shared "Address Books", and so I have set up the Administrator's address book to be shared with members of the "Internal" group as "Read only", however there does not seem any easy way to add the 200 users to Administrator's address book (other than manually typing in the details into the Contacts list of the Addressbook).

Reading from http://www.group-office.com/wiki/Users, ... ermissions
A few special groups are created by default:

Admins, users of this group will have permission to everything. Usually you don't want to add any user to this group. See above.
Everyone, all users are in this group. Use carefully when granting permissions to this group.
Internal, this group is created by default and new users are commonly added to this group by default. It should contain all company users and not your customers
GoAlways
 
Posts: 80
Joined: Mon Oct 11, 2010 4:41 am

Re: Global Address Book

Postby Intermesh » Tue Jun 14, 2011 7:09 am

This feature will be added later.
Best regards,

Merijn Schering
Intermesh
User avatar
Intermesh
Site Admin
 
Posts: 7086
Joined: Tue Apr 20, 2004 1:06 pm
Location: The Netherlands - Den Bosch

Re: Global Address Book

Postby GoAlways » Wed Jun 15, 2011 1:21 am

Thanks, it will be a worthwhile addition to Group Office. In the mean time, I am thinking of writing a php script to extract data from Users table and insert it into Group Office's admin accounts address book that I am currently (read) sharing with members of the Internal group.

Suggestion, if a Global Address Book is added as another tab to the Addressbook, then I wonder if access/display to Group Office users could be controlled by group membership, e.g. the Internal group, in this way, those who have both Internal and External people who log into Group Office could exclude External users from the internal Global Addressbook ? I do not have need for this feature at the moment, but it seemed to be in line with the overall design of Group Office.
GoAlways
 
Posts: 80
Joined: Mon Oct 11, 2010 4:41 am

Re: Global Address Book

Postby GoAlways » Tue Jul 05, 2011 5:20 am

I have created the script to sync all User's accounts into a Global Address book. If any one is interested to review it, you welcome to make suggested improvements.

I created the Global Address book under the admin account and gave everyone group read access, as per the instructions on the pages;
http://www.group-office.com/w/index.php/Getting_started
4. Creating items that are commonly used for more users such as a global addressbook, shared calendars or a corporate HTML template for outgoing e-mail messages.

http://www.group-office.com/wiki/Addressbook
If you want to create a global shared addressbook it is recommended to add this addressbook as the "admin" user so it won't be deleted along with a regular user when this employee leaves the company for example.


You will need to change a few values for those that match your own installation, like the id for your admin is most likely going to be 1, but it is unlikely that the address book you create to be the Global Address Book is going to be '678', so please change these values to match your installation.
Code: Select all
<?php 
/* Still need code to lock the database tables "go_db_sequence" and "ab_contact", so no one else can create a record while we do.
   To link a user with their corresponding record in the Global Address book, you need to create a new field called 'go_users_id' in the ab_conatacts table.
 */

   /*  Connect to database */
   $host = "localhost";
    $user = "go_db_user";
   $password = "go_db_pwd";
   $dbase = "go_db";

   $DATAb = mysql_connect($host,$user,$password);
   mysql_select_db($dbase,$DATAb);
//   exit();  // For testing only - Test database access to this point.

   /* Get a list of all the company names and company ID numbers from the ab_companies table  */
   $query_companies = "Select id, name  FROM ab_companies ";
   global $result_companies;
   $result_companies = mysql_query($query_companies);
                        
   /* Get all the active users from the go_users table  */
   $query_users = "Select *  FROM go_users WHERE enabled = '1'";
   $result_users = mysql_query($query_users);
   // print "Number of go_users are ".mysql_num_rows($result_users)."\n\n";
   while($go_users = mysql_fetch_array($result_users))
   {
      /* Select Contacts from ab_contacts Global Address book records */
      $query_contacts = "Select ab_contacts.*, ab_companies.name AS company FROM ab_contacts LEFT JOIN ab_companies ON (ab_contacts.company_id = ab_companies.id ) WHERE ab_contacts.addressbook_id = '678' AND ab_contacts.user_id = '1' AND ab_contacts.go_users_id = '$go_users[id]'";      
      $result_contacts = mysql_query($query_contacts);
      // print "Number of ab_contacts records are ".mysql_num_rows($result_contacts)."\n\n";
      //   exit();
      if(mysql_num_rows($result_contacts) > 0)
      {   /* there should only be one record */
         $contacts_users=mysql_fetch_array($result_contacts);
         /* check record details to see if any chages had been made */
         $Changes = false;
         $id = 0;
         $UpdateCmd = "UPDATE ab_contacts SET ";
         if (strcmp($go_users['first_name'], $contacts_users['first_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " first_name = '".mysql_real_escape_string($go_users['first_name'])."',";
         }
         if (strcmp($go_users['middle_name'], $contacts_users['middle_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " middle_name = '".mysql_real_escape_string($go_users['middle_name'])."',";
         }
         if (strcmp($go_users['last_name'], $contacts_users['last_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " last_name = '".mysql_real_escape_string($go_users['last_name'])."',";
         }
         if (strcmp($go_users['initials'], $contacts_users['initials']) != 0) {
            $Changes = true; $UpdateCmd .=  " initials = '".mysql_real_escape_string($go_users['initials'])."',";
         }
         if (strcmp($go_users['title'], $contacts_users['title']) != 0)    {
            $Changes = true; $UpdateCmd .=  " title = '".mysql_real_escape_string($go_users['title'])."',";
         }
         if (strcmp($go_users['sex'], $contacts_users['sex']) != 0) {
            $Changes = true; $UpdateCmd .=  " sex = '".$go_users['sex']."',";
         }
/*         if (strcmp($go_users['birthday'], $contacts_users['birthday']) != 0)   //  For security reasons, providing birthday is too personal for a Global Address book
         {
            $Changes = true; $UpdateCmd .=  " birthday = '".$go_users['birthday']."',";
         }  */
         if (strcmp($go_users['email'], $contacts_users['email']) != 0) {
            $Changes = true; $UpdateCmd .=  " email = '".mysql_real_escape_string($go_users['email'])."',";
         }
         $company_id = "";
         if (strcmp($go_users['company'], $contacts_users['company']) != 0) {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) { $Changes = true;  $UpdateCmd .=  " company_id = '".$company_id."',"; }
            else { print  " Could not find company  '".($go_users['company'])."' for user#, '".$go_users['id']."\n\n"; }
         }   
         if (strcmp($go_users['department'], $contacts_users['department']) != 0) {
            $Changes = true; $UpdateCmd .=  " department = '".mysql_real_escape_string($go_users['department'])."',";
         }
         if (strcmp($go_users['function'], $contacts_users['function']) != 0) {
            $Changes = true; $UpdateCmd .=  " function = '".mysql_real_escape_string($go_users['function'])."',";
         }
         if (strcmp($go_users['home_phone'], $contacts_users['home_phone']) != 0) {
            $Changes = true; $UpdateCmd .=  " home_phone = '".mysql_real_escape_string($go_users['home_phone'])."',";
         }
         if (strcmp($go_users['work_phone'], $contacts_users['work_phone']) != 0) {
            $Changes = true; $UpdateCmd .=  " work_phone = '".mysql_real_escape_string($go_users['work_phone'])."',";
         }
         if (strcmp($go_users['fax'], $contacts_users['fax']) != 0) {
            $Changes = true; $UpdateCmd .=  " fax = '".mysql_real_escape_string($go_users['fax'])."',";
         }
         if (strcmp($go_users['cellular'], $contacts_users['cellular']) != 0) {
            $Changes = true; $UpdateCmd .=  " cellular = '".mysql_real_escape_string($go_users['cellular'])."',";
         }
         if (strcmp($go_users['country'], $contacts_users['country']) != 0) {
            $Changes = true; $UpdateCmd .=  " country = '".mysql_real_escape_string($go_users['country'])."',";
         }
         if (strcmp($go_users['state'], $contacts_users['state']) != 0) {
            $Changes = true; $UpdateCmd .=  " state = '".mysql_real_escape_string($go_users['state'])."',";
         }
         if (strcmp($go_users['city'], $contacts_users['city']) != 0) {
            $Changes = true; $UpdateCmd .=  " city = '".mysql_real_escape_string($go_users['city'])."',";
         }
         if (strcmp($go_users['address'], $contacts_users['address']) != 0) {
            $Changes = true; $UpdateCmd .=  " address = '".mysql_real_escape_string($go_users['address'])."',";
         }
         if (strcmp($go_users['address_no'], $contacts_users['address_no']) != 0) {
            $Changes = true; $UpdateCmd .=  " address_no = '".mysql_real_escape_string($go_users['address_no'])."',";
         }
         if ($Changes)
         {   // do we really want email_allowed to be updated? what does it do anyway?, so we will set it back to what it oringinally was. 
            // Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook
            // To link this user with their corresponding record in the Global Address book, you need to create a new field called 'go_users_id' in the ab_conatacts table.
            $UpdateCmd .=  " email_allowed = '$contacts_users[email_allowed]' WHERE addressbook_id = '678' AND user_id = '1' AND go_users_id = '$go_users[id]'";
            $update_result = mysql_query($UpdateCmd);
            print $UpdateCmd."\n\n";
            //exit();  /* For testing only - tests one record at a time. */
         }
      }
      else
      {      /* this user does not yet have a Global Addressbook Contact record, so lets insert a new record for them.  */
         /* Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook */
         $newid = nextSegNo("ab_contacts");
         $InsertCmd = "INSERT INTO ab_contacts SET id = '$newid', user_id = '1', addressbook_id = '678' , go_users_id = '$go_users[id]', ";
         if (!empty($go_users['first_name']))  $InsertCmd .=  " first_name = '".mysql_real_escape_string($go_users['first_name'])."',";   
         if (!empty($go_users['middle_name'])) $InsertCmd .=  " middle_name = '".mysql_real_escape_string($go_users['middle_name'])."',";
         if (!empty($go_users['last_name'])) $InsertCmd .=  " last_name = '".mysql_real_escape_string($go_users['last_name'])."',";
         if (!empty($go_users['initials'])) $InsertCmd .=  " initials = '".mysql_real_escape_string($go_users['initials'])."',";
         if (!empty($go_users['title'])) $InsertCmd .=  " title = '".mysql_real_escape_string($go_users['title'])."',";
         if (!empty($go_users['sex'])) $InsertCmd .=  " sex = '".$go_users['sex']."',";
//         if (is_date($go_users['birthday'])) $InsertCmd .=  " birthday = '".$go_users['birthday']."',";  //  For security reasons, providing birthday is too personal for a Global Address book
         if (!empty($go_users['email'])) $InsertCmd .=  " email = '".mysql_real_escape_string($go_users['email'])."',";
         if (!empty($go_users['company']))  /* company is a dropdown list */
         {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) { $InsertCmd .=  " company_id = '".$company_id."',"; }
            else { $InsertCmd .=  " comment = '".mysql_real_escape_string($go_users['company'])."',"; }
         }   
         if (!empty($go_users['department'])) { $InsertCmd .=  " department = '".mysql_real_escape_string($go_users['department'])."',"; }
         if (!empty($go_users['function'])) { $InsertCmd .=  " function = '".mysql_real_escape_string($go_users['function'])."',"; }
         if (!empty($go_users['home_phone'])) { $InsertCmd .=  " home_phone = '".mysql_real_escape_string($go_users['home_phone'])."',"; }
         if (!empty($go_users['work_phone'])) { $InsertCmd .=  " work_phone = '".mysql_real_escape_string($go_users['work_phone'])."',";    }
         if (!empty($go_users['fax']))    { $InsertCmd .=  " fax = '".mysql_real_escape_string($go_users['fax'])."',"; }
         if (!empty($go_users['cellular'])) { $InsertCmd .=  " cellular = '".mysql_real_escape_string($go_users['cellular'])."',"; }
         if (!empty($go_users['country'])) { $InsertCmd .=  " country = '".mysql_real_escape_string($go_users['country'])."',"; }
         if (!empty($go_users['state'])) { $InsertCmd .=  " state = '".mysql_real_escape_string($go_users['state'])."',"; }
         if (!empty($go_users['city'])) { $InsertCmd .=  " city = '".mysql_real_escape_string($go_users['city'])."',"; }
         if (!empty($go_users['address'])) { $InsertCmd .=  " address = '".mysql_real_escape_string($go_users['address'])."',"; }
         if (!empty($go_users['address_no'])) { $InsertCmd .=  " address_no = '".mysql_real_escape_string($go_users['address_no'])."',"; }
         $InsertCmd .=  " email_allowed = '1' ";  /* By default set email_allowed to true */
         $Insert_result = mysql_query($InsertCmd);
         print $InsertCmd."\n\n";
         //exit();  /* For testing only - tests one record at a time. */
      }   /* end of Update/Insert Contact details for this User.  */
   }
      
function nextSegNo($tableName)
{    /* as found in base_db.class.inc.php */
   /* WARNING: need to lock the database just now so no one else can create a record, but I have not done this yet,! */
   $query_seq = "Select * FROM go_db_sequence WHERE seq_name = '$tableName' ";      
   $result_seq= mysql_query($query_seq);
   if (mysql_num_rows($result_seq) > 0) {
      $result_rec = mysql_fetch_array($result_seq);
      $newID =  $result_rec['nextid'] + 1;
      $sql_result = mysql_query("UPDATE go_db_sequence   SET nextid = '$newID'  WHERE seq_name = '$tableName' ");      
      return $newID;
   } else { print ">>>>>> We had a major database error attempting to update the '".$tableName."' sequence number!";  exit(3); }
}

function companyID($companies, $company_name)   
{
   $query_companies = "Select id, name  FROM ab_companies ";
   $result_companies = mysql_query($query_companies);

   $company_id = 0;
   $company_name = trim($company_name);  /* $result_companies*/
   while($companydetails = mysql_fetch_array($result_companies))
   {
      $company = trim($companydetails['name']);
//         print "Company ++> '".$company."'  \n";
      if (strcasecmp($company_name, $company) == 0 )
      {
         $company_id = $companydetails['id'];
//         print "=====> ".$company_id."  ".$company_name."  = ".$companydetails['name']."\n";
         return $company_id;
      }
   }
   print "-----> '".$company_name."' not found \n";   // Print out all company names which could not be matched, so we can create Company records as required.
   return $company_id;
}
function is_date( $str )
{
   $stamp = strtotime( $str );
   if (!is_numeric($stamp)) return FALSE;
   $month = date( 'm', $stamp );
   $day   = date( 'd', $stamp );
   $year  = date( 'Y', $stamp );
    if (checkdate($month, $day, $year))  return TRUE; 
   return FALSE;
}

?>

[/code]
GoAlways
 
Posts: 80
Joined: Mon Oct 11, 2010 4:41 am

Re: Global Address Book

Postby Methleraner » Wed Jul 06, 2011 9:07 am

Yeah .. It works great !!!

Thanks :)

Now i must to do this by hand. It is possible to execute this file automatically?
Methleraner
 
Posts: 41
Joined: Tue Jun 28, 2011 10:25 am

Re: Global Address Book

Postby GoAlways » Wed Jul 06, 2011 11:32 pm

Methleraner,
I set up an CRON job to automatically run this for me each day under the administrator account, after my backup processes have run. It could be run each hour if you wanted, but I decided that once per day was satisfactory for my needs.

I am not great with VI so I use NANO as my editor;
Code: Select all
export EDITOR=/usr/bin/nano
crontab -e

This is an explaination of the CRON file
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * command to be executed

An extract from root's cron file;
Code: Select all
# m h  dom mon dow   command
5 6 * * * /usr/bin/php /root/syncuserstoaddressbook.php >> /var/log/users2addressbook.log


It may not be required but I restarted the CRON process to ensure that it can read my changes and I have not made too obvious error.
Code: Select all
/etc/init.d/cron restart


Then check that all is OK

Code: Select all
/etc/init.d/cron restart
tail /var/log/syslog


The listing should have something like

Code: Select all
Jul  7 09:21:15 web3 /usr/sbin/cron[24490]: (CRON) STARTUP (fork ok)



The above is brief, however I hope it is a good guide for you.
GoAlways
 
Posts: 80
Joined: Mon Oct 11, 2010 4:41 am

Re: Global Address Book

Postby orca » Tue Sep 06, 2011 10:42 pm

Thanks a lot! It works great!
This will be a great workaround until the global addressbook is inplemented by intermesh.

Suggestion: A great feature would be removing deactivated or deleted users from the global addressbook automatically by the script.
orca
 
Posts: 16
Joined: Mon Jan 17, 2011 10:40 pm

Re: Global Address Book

Postby GoAlways » Sat Sep 10, 2011 6:43 pm

Orca, That is a good point, I new I would have to do this sometime, but at the time I was quite busy. I will make the changes and post back soon. Also I should point out, I forgot the ZIP code. I will post my updated code once I have the "remove if not active" working.
GoAlways
 
Posts: 80
Joined: Mon Oct 11, 2010 4:41 am

Re: Global Address Book

Postby GoAlways » Thu Sep 15, 2011 10:57 am

Orca, I have added code to delete contacts who were added from the go_users table by this sync script, if they are no longer active in the go_users table or have been deleted from the go_users table, which means that any contacts added manually by the Owner of this addressbook should not be deleted.

This is the code that I am currently using, so it should work reasonably well.

I had found a few bugs from earlier posted code, so please review this and update if you have been using the above code. One bug was I forgot to sync the ZIP code, as stated earlier.

You may prefer to sync different User fields to the Global Addressbook than the fields that I have chosen, hopefully this is not too difficult for anyone. Our Users do not enter their personal (home) details, so I am using their accounts Personal details as their work address, and if this does not differ from their company details then their Company details should be the same data as their personal details. One day I intend to write code which automatically copies from their Personal details to their Company details, if their company details are not entered.


Code: Select all
<?php

/*  Connect to database */

   $host = "localhost";   //localhost or the name of your MySQL database server
    $user = "groupoffice";   // the userid of the account you use to access your GroupOffice database
   $password = "yourPassword";  // The password of the account you use to access your GroupOffice database
   $dbase = "groupofficedb";   // The name of your GroupOffice database

   $addressbookOwnerID = '1';            // This is usually the UserID of the Group Office Admin accout that is sharing their address book as a Global Address book
   $addressbookToSync_id =  '676';      // The ID of which calendar is being shared globally to all uses as the Global Address book
   
   $DATAb = mysql_connect($host,$user,$password);
   mysql_select_db($dbase,$DATAb);
//   exit();
   /* need to lock the database tables "next sequence and ab_contact ?? just now so no one else can create a record */
   /* Get a list of all the company names and ID numbers from the go_users table  */
   $query_companies = "Select id, name  FROM ab_companies ";
   global $result_companies;
   $result_companies = mysql_query($query_companies);
                        
   /* Get all the active users from the go_users table  */
   $query_users = "Select *  FROM go_users WHERE enabled = '1' ORDER BY go_users.id ASC";
   $result_users = mysql_query($query_users);
   // print "Number of go_users are ".mysql_num_rows($result_users)."\n\n";
   while($go_users = mysql_fetch_array($result_users))
   {
      // print  "\nUserID: $go_users[id],  $go_users[first_name] $go_users[last_name] -> ";
      /* Select Contacts from ab_contacts Global Address book records */
      $query_contacts = "Select ab_contacts.*, ab_companies.name AS company FROM ab_contacts LEFT JOIN ab_companies ON (ab_contacts.company_id = ab_companies.id ) WHERE ab_contacts.addressbook_id = '$addressbookToSync_id' AND ab_contacts.user_id = '$addressbookOwnerID' AND ab_contacts.go_users_id = '$go_users[id]' ";      
      $result_contacts = mysql_query($query_contacts);
      // print "Number of ab_contacts records are ".mysql_num_rows($result_contacts)."\n\n";      // for debugging, not required for normal logging.
      //   exit();
      if(mysql_num_rows($result_contacts) > 0)
      {   /* there should only be one record */
         $contacts_users=mysql_fetch_array($result_contacts);
         /* check record details to see if any chages had been made */
         $Changes = false;
         // print " UPDATE: ";   // for debugging, not required for normal logging.
         $id = 0;
         $UpdateCmd = "UPDATE ab_contacts SET ";
         if (strcmp($go_users['first_name'], $contacts_users['first_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " first_name = '".mysql_real_escape_string($go_users['first_name'])."',";
         }
         if (strcmp($go_users['middle_name'], $contacts_users['middle_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " middle_name = '".mysql_real_escape_string($go_users['middle_name'])."',";
         }
         if (strcmp($go_users['last_name'], $contacts_users['last_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " last_name = '".mysql_real_escape_string($go_users['last_name'])."',";
         }
         if (strcmp($go_users['initials'], $contacts_users['initials']) != 0) {
            $Changes = true; $UpdateCmd .=  " initials = '".mysql_real_escape_string($go_users['initials'])."',";
         }
         if (strcmp($go_users['title'], $contacts_users['title']) != 0)    {
            $Changes = true; $UpdateCmd .=  " title = '".mysql_real_escape_string($go_users['title'])."',";
         }
         if (strcmp($go_users['sex'], $contacts_users['sex']) != 0) {
            $Changes = true; $UpdateCmd .=  " sex = '".$go_users['sex']."',";
         }
/*         if (strcmp($go_users['birthday'], $contacts_users['birthday']) != 0)   //  For security reasons, providing birthday is too personal for a Global Address book
         {
            $Changes = true; $UpdateCmd .=  " birthday = '".$go_users['birthday']."',";
         }  */
         if (strcmp($go_users['email'], $contacts_users['email']) != 0) {
            $Changes = true; $UpdateCmd .=  " email = '".mysql_real_escape_string($go_users['email'])."',";
         }
         $company_id = "";
         if (strcmp($go_users['company'], $contacts_users['company']) != 0) {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) { $Changes = true;  $UpdateCmd .=  " company_id = '".$company_id."',"; }
            else {
               print  "\nUserID: $go_users[id],  $go_users[first_name] $go_users[last_name] -> ";  // disable if debugging
               print  " Could not find company  '".($go_users['company'])."' -> "; }
         }   
         if (strcmp($go_users['department'], $contacts_users['department']) != 0) {
            $Changes = true; $UpdateCmd .=  " department = '".mysql_real_escape_string($go_users['department'])."',";
         }
         if (strcmp($go_users['function'], $contacts_users['function']) != 0) {
            $Changes = true; $UpdateCmd .=  " function = '".mysql_real_escape_string($go_users['function'])."',";
         }
         if (strcmp($go_users['home_phone'], $contacts_users['home_phone']) != 0) {
            $Changes = true; $UpdateCmd .=  " home_phone = '".mysql_real_escape_string($go_users['home_phone'])."',";
         }
         if (strcmp($go_users['work_phone'], $contacts_users['work_phone']) != 0) {
            $Changes = true; $UpdateCmd .=  " work_phone = '".mysql_real_escape_string($go_users['work_phone'])."',";
         }
         if (strcmp($go_users['fax'], $contacts_users['fax']) != 0) {
            $Changes = true; $UpdateCmd .=  " fax = '".mysql_real_escape_string($go_users['fax'])."',";
         }
         if (strcmp($go_users['cellular'], $contacts_users['cellular']) != 0) {
            $Changes = true; $UpdateCmd .=  " cellular = '".mysql_real_escape_string($go_users['cellular'])."',";
         }
         if (strcmp($go_users['country'], $contacts_users['country']) != 0) {
            $Changes = true; $UpdateCmd .=  " country = '".mysql_real_escape_string($go_users['country'])."',";
         }
         if (strcmp($go_users['state'], $contacts_users['state']) != 0) {
            $Changes = true; $UpdateCmd .=  " state = '".mysql_real_escape_string($go_users['state'])."',";
         }
         if (strcmp($go_users['zip'], $contacts_users['zip']) != 0) {
            $Changes = true; $UpdateCmd .=  " zip = '".mysql_real_escape_string($go_users['zip'])."',";
         }
         if (strcmp($go_users['city'], $contacts_users['city']) != 0) {
            $Changes = true; $UpdateCmd .=  " city = '".mysql_real_escape_string($go_users['city'])."',";
         }
         if (strcmp($go_users['address'], $contacts_users['address']) != 0) {
            $Changes = true; $UpdateCmd .=  " address = '".mysql_real_escape_string($go_users['address'])."',";
         }
         if (strcmp($go_users['address_no'], $contacts_users['address_no']) != 0) {
            $Changes = true; $UpdateCmd .=  " address_no = '".mysql_real_escape_string($go_users['address_no'])."',";
         }
         if ($Changes)
         {   // do we really want email_allowed to be updated? what does it do anyway?, so we will set it back to what it oringinally was. 
            // Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook
            // To link this user with their corresponding record in the Global Address book, you need to create a new field called 'go_users_id' in the ab_conatacts table.
            $UpdateCmd .=  " email_allowed = '$contacts_users[email_allowed]' WHERE addressbook_id = '$addressbookToSync_id' AND user_id = '$addressbookOwnerID' AND go_users_id = '$go_users[id]'";
            $update_result = mysql_query($UpdateCmd);
            print $UpdateCmd."\n\n";
            //exit();  /* For testing only - tests one record at a time. */
         } else {
              // print  " ab_contacts record '$contacts_users[id]' did not require changes. ($UpdateCmd)\n";  // for debugging, not required for normal logging.
         }
      }
      else
      {      /* this user does not yet have a Global Addressbook Contact record, so lets insert a new record for them.  */
         /* Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook */
         print " INSERT: ";
         $newid = nextSegNo("ab_contacts");
         $InsertCmd = "INSERT INTO ab_contacts SET id = '$newid', user_id = '$addressbookOwnerID', addressbook_id = '$addressbookToSync_id' , go_users_id = '$go_users[id]', ";
         if (!empty($go_users['first_name']))  $InsertCmd .=  " first_name = '".mysql_real_escape_string($go_users['first_name'])."',";   
         if (!empty($go_users['middle_name'])) $InsertCmd .=  " middle_name = '".mysql_real_escape_string($go_users['middle_name'])."',";
         if (!empty($go_users['last_name'])) $InsertCmd .=  " last_name = '".mysql_real_escape_string($go_users['last_name'])."',";
         if (!empty($go_users['initials'])) $InsertCmd .=  " initials = '".mysql_real_escape_string($go_users['initials'])."',";
         if (!empty($go_users['title'])) $InsertCmd .=  " title = '".mysql_real_escape_string($go_users['title'])."',";
         if (!empty($go_users['sex'])) $InsertCmd .=  " sex = '".$go_users['sex']."',";
//         if (is_date($go_users['birthday'])) $InsertCmd .=  " birthday = '".$go_users['birthday']."',";  //  For security reasons, providing birthday is too personal for a Global Address book
         if (!empty($go_users['email'])) $InsertCmd .=  " email = '".mysql_real_escape_string($go_users['email'])."',";
         if (!empty($go_users['company']))  /* company is a dropdown list */
         {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) { $InsertCmd .=  " company_id = '".$company_id."',"; }
            else { $InsertCmd .=  " comment = '".mysql_real_escape_string($go_users['company'])."',"; }
         }   
         if (!empty($go_users['department'])) { $InsertCmd .=  " department = '".mysql_real_escape_string($go_users['department'])."',"; }
         if (!empty($go_users['function'])) { $InsertCmd .=  " function = '".mysql_real_escape_string($go_users['function'])."',"; }
         if (!empty($go_users['home_phone'])) { $InsertCmd .=  " home_phone = '".mysql_real_escape_string($go_users['home_phone'])."',"; }
         if (!empty($go_users['work_phone'])) { $InsertCmd .=  " work_phone = '".mysql_real_escape_string($go_users['work_phone'])."',";    }
         if (!empty($go_users['fax']))    { $InsertCmd .=  " fax = '".mysql_real_escape_string($go_users['fax'])."',"; }
         if (!empty($go_users['cellular'])) { $InsertCmd .=  " cellular = '".mysql_real_escape_string($go_users['cellular'])."',"; }
         if (!empty($go_users['country'])) { $InsertCmd .=  " country = '".mysql_real_escape_string($go_users['country'])."',"; }
         if (!empty($go_users['state'])) { $InsertCmd .=  " state = '".mysql_real_escape_string($go_users['state'])."',"; }
         if (!empty($go_users['zip'])) { $InsertCmd .=  " zip = '".mysql_real_escape_string($go_users['zip'])."',"; }
         if (!empty($go_users['city'])) { $InsertCmd .=  " city = '".mysql_real_escape_string($go_users['city'])."',"; }
         if (!empty($go_users['address'])) { $InsertCmd .=  " address = '".mysql_real_escape_string($go_users['address'])."',"; }
         if (!empty($go_users['address_no'])) { $InsertCmd .=  " address_no = '".mysql_real_escape_string($go_users['address_no'])."',"; }
         $InsertCmd .=  " email_allowed = '1', iso_address_format = 'AU' ";  /* By default set email_allowed to true */
         $Insert_result = mysql_query($InsertCmd);
         print "\n".$InsertCmd."\n\n";
         //exit();  /* For testing only - tests one record at a time. */
      }   /* end of Update/Insert Contact details for this User.  */
   }

   print "\nChecking for users who should be removed from the Contacts Addressbook\n";
   /* Delete contacts who were added from the go_users table by the sync process if they are no longer active in the go_users table or
      have been deleted from the go_users table, which means that any contacts added specifically by the Owner of this addressbook, should not be deleted.
       The code "ab_contacts.first_name AS fname, ab_contacts.last_name AS sname," is only required for debugging purposes, and could be removed if you wanted to.
   */
   $query_contacts = "SELECT ne.* FROM (SELECT    ab_contacts.id as ab_id, ab_contacts.first_name AS fname, ab_contacts.last_name AS sname, 
                           ab_contacts.go_users_id AS go_user_id, go_users.enabled AS enabled
                        FROM ab_contacts LEFT JOIN go_users ON (ab_contacts.go_users_id = go_users.id)
                        WHERE ab_contacts.go_users_id > 0 AND ab_contacts.addressbook_id = '$addressbookToSync_id'  AND ab_contacts.user_id = '$addressbookOwnerID'
               ) ne  WHERE   ne.enabled = '0' OR ne.enabled IS NULL";
   $result_users_contacts = mysql_query($query_contacts);
   while($ab_user = mysql_fetch_array($result_users_contacts))
   {
      /* Note: Check for "ab_contacts.addressbook_id = '$addressbookToSync_id'  AND ab_contacts.user_id = '$addressbookOwnerID' " should not be required, but I included for extra assurance I am not deleteing from someone else's addressbook */
      $DeleteCmd = "DELETE FROM ab_contacts WHERE ab_contacts.id = '".$ab_user['ab_id']."' AND ab_contacts.addressbook_id = '".$addressbookToSync_id."'  AND ab_contacts.user_id = '".$addressbookOwnerID."' ";
      $update_result = mysql_query($DeleteCmd);
      print "$ab_user[fname] $ab_user[sname]  - ".$DeleteCmd."\n";  // Remark this line out if you do not want the extra logging.
   }
   Print "\n============ Global Addressbook synchronisation completed ====================\n\n\n";
#===== PHP Functions below =================================================================================================================
function nextSegNo($tableName)
{    /* as found in base_db.class.inc.php */
   /* WARNING: need to lock the database just now so no one else can create a record, but I have not done this yet,! */
   $query_seq = "Select * FROM go_db_sequence WHERE seq_name = '$tableName' ";      
   $result_seq= mysql_query($query_seq);
   if (mysql_num_rows($result_seq) > 0) {
      $result_rec = mysql_fetch_array($result_seq);
      $newID =  $result_rec['nextid'] + 1;
      $sql_result = mysql_query("UPDATE go_db_sequence   SET nextid = '$newID'  WHERE seq_name = '$tableName' ");      
      return $newID;
   } else { print ">>>>>> We had a major database error attempting to update the '".$tableName."' sequence number!";  exit(3); }
}

function companyID($companies, $company_name)   
{
   $query_companies = "Select id, name  FROM ab_companies ";
   $result_companies = mysql_query($query_companies);

   $company_id = 0;
   $company_name = trim($company_name);  /* $result_companies*/
   while($companydetails = mysql_fetch_array($result_companies))
   {
      $company = trim($companydetails['name']);
//         print "Company ++> '".$company."'  \n";
      if (strcasecmp($company_name, $company) == 0 )
      {
         $company_id = $companydetails['id'];
//         print "=====> ".$company_id."  ".$company_name."  = ".$companydetails['name']."\n";
         return $company_id;
      }
   }
//   print "-----> '".$company_name."' not found \n";   // Print out all company names which could not be matched, so we can create Company records as required.
   return $company_id;
}
function is_date( $str )
{
   $stamp = strtotime( $str );
   if (!is_numeric($stamp)) return FALSE;
   $month = date( 'm', $stamp );
   $day   = date( 'd', $stamp );
   $year  = date( 'Y', $stamp );
    if (checkdate($month, $day, $year))  return TRUE; 
   return FALSE;
}

?>


I hope this code helps others, please refer to my earlier postings on how to run this script via a cron job.

I look forward to when the "Addressbook" module in Group Office can include the Users Contact details just as the "E-mail" module addressbook does, and my above script is no longer required.
GoAlways
 
Posts: 80
Joined: Mon Oct 11, 2010 4:41 am

Re: Global Address Book

Postby Methleraner » Thu Oct 27, 2011 8:08 am

I get an Error

INSERT: >>>>>> We had a major database error attempting to update the 'ab_contacts' sequence number!

I don't now what it mean and what i must do :(

I Use Group Office version 3.7.33
Methleraner
 
Posts: 41
Joined: Tue Jun 28, 2011 10:25 am

Re: Global Address Book

Postby Intermesh » Fri Nov 04, 2011 10:23 am

Run a database check and it will be set correctly.
Best regards,

Merijn Schering
Intermesh
User avatar
Intermesh
Site Admin
 
Posts: 7086
Joined: Tue Apr 20, 2004 1:06 pm
Location: The Netherlands - Den Bosch

Re: Global Address Book

Postby Methleraner » Mon Nov 07, 2011 10:38 am

Thanks :) :oops:
Methleraner
 
Posts: 41
Joined: Tue Jun 28, 2011 10:25 am

Re: Global Address Book

Postby ocb » Fri Mar 02, 2012 3:52 am

Code: Select all
<?php

/*  Connect to database */

   $host = "localhost";   //localhost or the name of your MySQL database server
    $user = "groupoffice";   // the userid of the account you use to access your GroupOffice database
   $password = "yourPassword";  // The password of the account you use to access your GroupOffice database
   $dbase = "groupofficedb";   // The name of your GroupOffice database

   $addressbookOwnerID = '1';            // This is usually the UserID of the Group Office Admin accout that is sharing their address book as a Global Address book
   $addressbookToSync_id =  '676';      // The ID of which calendar is being shared globally to all uses as the Global Address book
   
   $DATAb = mysql_connect($host,$user,$password);
   mysql_select_db($dbase,$DATAb);
//   exit();
   /* need to lock the database tables "next sequence and ab_contact ?? just now so no one else can create a record */
   /* Get a list of all the company names and ID numbers from the go_users table  */
   $query_companies = "Select id, name  FROM ab_companies ";
   global $result_companies;
   $result_companies = mysql_query($query_companies);
                        
   /* Get all the active users from the go_users table  */
   $query_users = "Select *  FROM go_users WHERE enabled = '1' ORDER BY go_users.id ASC";
   $result_users = mysql_query($query_users);
   // print "Number of go_users are ".mysql_num_rows($result_users)."\n\n";
   while($go_users = mysql_fetch_array($result_users))
   {
      // print  "\nUserID: $go_users[id],  $go_users[first_name] $go_users[last_name] -> ";
      /* Select Contacts from ab_contacts Global Address book records */
      $query_contacts = "Select ab_contacts.*, ab_companies.name AS company FROM ab_contacts LEFT JOIN ab_companies ON (ab_contacts.company_id = ab_companies.id ) WHERE ab_contacts.addressbook_id = '$addressbookToSync_id' AND ab_contacts.user_id = '$addressbookOwnerID' AND ab_contacts.go_users_id = '$go_users[id]' ";      
      $result_contacts = mysql_query($query_contacts);
      // print "Number of ab_contacts records are ".mysql_num_rows($result_contacts)."\n\n";      // for debugging, not required for normal logging.
      //   exit();
      if(mysql_num_rows($result_contacts) > 0)
      {   /* there should only be one record */
         $contacts_users=mysql_fetch_array($result_contacts);
         /* check record details to see if any chages had been made */
         $Changes = false;
         // print " UPDATE: ";   // for debugging, not required for normal logging.
         $id = 0;
         $UpdateCmd = "UPDATE ab_contacts SET ";
         if (strcmp($go_users['first_name'], $contacts_users['first_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " first_name = '".mysql_real_escape_string($go_users['first_name'])."',";
         }
         if (strcmp($go_users['middle_name'], $contacts_users['middle_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " middle_name = '".mysql_real_escape_string($go_users['middle_name'])."',";
         }
         if (strcmp($go_users['last_name'], $contacts_users['last_name']) != 0) {
            $Changes = true; $UpdateCmd .=  " last_name = '".mysql_real_escape_string($go_users['last_name'])."',";
         }
         if (strcmp($go_users['initials'], $contacts_users['initials']) != 0) {
            $Changes = true; $UpdateCmd .=  " initials = '".mysql_real_escape_string($go_users['initials'])."',";
         }
         if (strcmp($go_users['title'], $contacts_users['title']) != 0)    {
            $Changes = true; $UpdateCmd .=  " title = '".mysql_real_escape_string($go_users['title'])."',";
         }
         if (strcmp($go_users['sex'], $contacts_users['sex']) != 0) {
            $Changes = true; $UpdateCmd .=  " sex = '".$go_users['sex']."',";
         }
/*         if (strcmp($go_users['birthday'], $contacts_users['birthday']) != 0)   //  For security reasons, providing birthday is too personal for a Global Address book
         {
            $Changes = true; $UpdateCmd .=  " birthday = '".$go_users['birthday']."',";
         }  */
         if (strcmp($go_users['email'], $contacts_users['email']) != 0) {
            $Changes = true; $UpdateCmd .=  " email = '".mysql_real_escape_string($go_users['email'])."',";
         }
         $company_id = "";
         if (strcmp($go_users['company'], $contacts_users['company']) != 0) {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) { $Changes = true;  $UpdateCmd .=  " company_id = '".$company_id."',"; }
            else {
               print  "\nUserID: $go_users[id],  $go_users[first_name] $go_users[last_name] -> ";  // disable if debugging
               print  " Could not find company  '".($go_users['company'])."' -> "; }
         }   
         if (strcmp($go_users['department'], $contacts_users['department']) != 0) {
            $Changes = true; $UpdateCmd .=  " department = '".mysql_real_escape_string($go_users['department'])."',";
         }
         if (strcmp($go_users['function'], $contacts_users['function']) != 0) {
            $Changes = true; $UpdateCmd .=  " function = '".mysql_real_escape_string($go_users['function'])."',";
         }
         if (strcmp($go_users['home_phone'], $contacts_users['home_phone']) != 0) {
            $Changes = true; $UpdateCmd .=  " home_phone = '".mysql_real_escape_string($go_users['home_phone'])."',";
         }
         if (strcmp($go_users['work_phone'], $contacts_users['work_phone']) != 0) {
            $Changes = true; $UpdateCmd .=  " work_phone = '".mysql_real_escape_string($go_users['work_phone'])."',";
         }
         if (strcmp($go_users['fax'], $contacts_users['fax']) != 0) {
            $Changes = true; $UpdateCmd .=  " fax = '".mysql_real_escape_string($go_users['fax'])."',";
         }
         if (strcmp($go_users['cellular'], $contacts_users['cellular']) != 0) {
            $Changes = true; $UpdateCmd .=  " cellular = '".mysql_real_escape_string($go_users['cellular'])."',";
         }
         if (strcmp($go_users['country'], $contacts_users['country']) != 0) {
            $Changes = true; $UpdateCmd .=  " country = '".mysql_real_escape_string($go_users['country'])."',";
         }
         if (strcmp($go_users['state'], $contacts_users['state']) != 0) {
            $Changes = true; $UpdateCmd .=  " state = '".mysql_real_escape_string($go_users['state'])."',";
         }
         if (strcmp($go_users['zip'], $contacts_users['zip']) != 0) {
            $Changes = true; $UpdateCmd .=  " zip = '".mysql_real_escape_string($go_users['zip'])."',";
         }
         if (strcmp($go_users['city'], $contacts_users['city']) != 0) {
            $Changes = true; $UpdateCmd .=  " city = '".mysql_real_escape_string($go_users['city'])."',";
         }
         if (strcmp($go_users['address'], $contacts_users['address']) != 0) {
            $Changes = true; $UpdateCmd .=  " address = '".mysql_real_escape_string($go_users['address'])."',";
         }
         if (strcmp($go_users['address_no'], $contacts_users['address_no']) != 0) {
            $Changes = true; $UpdateCmd .=  " address_no = '".mysql_real_escape_string($go_users['address_no'])."',";
         }
         if ($Changes)
         {   // do we really want email_allowed to be updated? what does it do anyway?, so we will set it back to what it oringinally was. 
            // Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook
            // To link this user with their corresponding record in the Global Address book, you need to create a new field called 'go_users_id' in the ab_conatacts table.
            $UpdateCmd .=  " email_allowed = '$contacts_users[email_allowed]' WHERE addressbook_id = '$addressbookToSync_id' AND user_id = '$addressbookOwnerID' AND go_users_id = '$go_users[id]'";
            $update_result = mysql_query($UpdateCmd);
            print $UpdateCmd."\n\n";
            //exit();  /* For testing only - tests one record at a time. */
         } else {
              // print  " ab_contacts record '$contacts_users[id]' did not require changes. ($UpdateCmd)\n";  // for debugging, not required for normal logging.
         }
      }
      else
      {      /* this user does not yet have a Global Addressbook Contact record, so lets insert a new record for them.  */
         /* Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook */
         print " INSERT: ";
         $newid = nextSegNo("ab_contacts");
         $InsertCmd = "INSERT INTO ab_contacts SET id = '$newid', user_id = '$addressbookOwnerID', addressbook_id = '$addressbookToSync_id' , go_users_id = '$go_users[id]', ";
         if (!empty($go_users['first_name']))  $InsertCmd .=  " first_name = '".mysql_real_escape_string($go_users['first_name'])."',";   
         if (!empty($go_users['middle_name'])) $InsertCmd .=  " middle_name = '".mysql_real_escape_string($go_users['middle_name'])."',";
         if (!empty($go_users['last_name'])) $InsertCmd .=  " last_name = '".mysql_real_escape_string($go_users['last_name'])."',";
         if (!empty($go_users['initials'])) $InsertCmd .=  " initials = '".mysql_real_escape_string($go_users['initials'])."',";
         if (!empty($go_users['title'])) $InsertCmd .=  " title = '".mysql_real_escape_string($go_users['title'])."',";
         if (!empty($go_users['sex'])) $InsertCmd .=  " sex = '".$go_users['sex']."',";
//         if (is_date($go_users['birthday'])) $InsertCmd .=  " birthday = '".$go_users['birthday']."',";  //  For security reasons, providing birthday is too personal for a Global Address book
         if (!empty($go_users['email'])) $InsertCmd .=  " email = '".mysql_real_escape_string($go_users['email'])."',";
         if (!empty($go_users['company']))  /* company is a dropdown list */
         {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) { $InsertCmd .=  " company_id = '".$company_id."',"; }
            else { $InsertCmd .=  " comment = '".mysql_real_escape_string($go_users['company'])."',"; }
         }   
         if (!empty($go_users['department'])) { $InsertCmd .=  " department = '".mysql_real_escape_string($go_users['department'])."',"; }
         if (!empty($go_users['function'])) { $InsertCmd .=  " function = '".mysql_real_escape_string($go_users['function'])."',"; }
         if (!empty($go_users['home_phone'])) { $InsertCmd .=  " home_phone = '".mysql_real_escape_string($go_users['home_phone'])."',"; }
         if (!empty($go_users['work_phone'])) { $InsertCmd .=  " work_phone = '".mysql_real_escape_string($go_users['work_phone'])."',";    }
         if (!empty($go_users['fax']))    { $InsertCmd .=  " fax = '".mysql_real_escape_string($go_users['fax'])."',"; }
         if (!empty($go_users['cellular'])) { $InsertCmd .=  " cellular = '".mysql_real_escape_string($go_users['cellular'])."',"; }
         if (!empty($go_users['country'])) { $InsertCmd .=  " country = '".mysql_real_escape_string($go_users['country'])."',"; }
         if (!empty($go_users['state'])) { $InsertCmd .=  " state = '".mysql_real_escape_string($go_users['state'])."',"; }
         if (!empty($go_users['zip'])) { $InsertCmd .=  " zip = '".mysql_real_escape_string($go_users['zip'])."',"; }
         if (!empty($go_users['city'])) { $InsertCmd .=  " city = '".mysql_real_escape_string($go_users['city'])."',"; }
         if (!empty($go_users['address'])) { $InsertCmd .=  " address = '".mysql_real_escape_string($go_users['address'])."',"; }
         if (!empty($go_users['address_no'])) { $InsertCmd .=  " address_no = '".mysql_real_escape_string($go_users['address_no'])."',"; }
         $InsertCmd .=  " email_allowed = '1', iso_address_format = 'AU' ";  /* By default set email_allowed to true */
         $Insert_result = mysql_query($InsertCmd);
         print "\n".$InsertCmd."\n\n";
         //exit();  /* For testing only - tests one record at a time. */
      }   /* end of Update/Insert Contact details for this User.  */
   }

   print "\nChecking for users who should be removed from the Contacts Addressbook\n";
   /* Delete contacts who were added from the go_users table by the sync process if they are no longer active in the go_users table or
      have been deleted from the go_users table, which means that any contacts added specifically by the Owner of this addressbook, should not be deleted.
       The code "ab_contacts.first_name AS fname, ab_contacts.last_name AS sname," is only required for debugging purposes, and could be removed if you wanted to.
   */
   $query_contacts = "SELECT ne.* FROM (SELECT    ab_contacts.id as ab_id, ab_contacts.first_name AS fname, ab_contacts.last_name AS sname, 
                           ab_contacts.go_users_id AS go_user_id, go_users.enabled AS enabled
                        FROM ab_contacts LEFT JOIN go_users ON (ab_contacts.go_users_id = go_users.id)
                        WHERE ab_contacts.go_users_id > 0 AND ab_contacts.addressbook_id = '$addressbookToSync_id'  AND ab_contacts.user_id = '$addressbookOwnerID'
               ) ne  WHERE   ne.enabled = '0' OR ne.enabled IS NULL";
   $result_users_contacts = mysql_query($query_contacts);
   while($ab_user = mysql_fetch_array($result_users_contacts))
   {
      /* Note: Check for "ab_contacts.addressbook_id = '$addressbookToSync_id'  AND ab_contacts.user_id = '$addressbookOwnerID' " should not be required, but I included for extra assurance I am not deleteing from someone else's addressbook */
      $DeleteCmd = "DELETE FROM ab_contacts WHERE ab_contacts.id = '".$ab_user['ab_id']."' AND ab_contacts.addressbook_id = '".$addressbookToSync_id."'  AND ab_contacts.user_id = '".$addressbookOwnerID."' ";
      $update_result = mysql_query($DeleteCmd);
      print "$ab_user[fname] $ab_user[sname]  - ".$DeleteCmd."\n";  // Remark this line out if you do not want the extra logging.
   }
   Print "\n============ Global Addressbook synchronisation completed ====================\n\n\n";
#===== PHP Functions below =================================================================================================================
function nextSegNo($tableName)
{    /* as found in base_db.class.inc.php */
   /* WARNING: need to lock the database just now so no one else can create a record, but I have not done this yet,! */
   $query_seq = "Select * FROM go_db_sequence WHERE seq_name = '$tableName' ";      
   $result_seq= mysql_query($query_seq);
   if (mysql_num_rows($result_seq) > 0) {
      $result_rec = mysql_fetch_array($result_seq);
      $newID =  $result_rec['nextid'] + 1;
      $sql_result = mysql_query("UPDATE go_db_sequence   SET nextid = '$newID'  WHERE seq_name = '$tableName' ");      
      return $newID;
   } else { print ">>>>>> We had a major database error attempting to update the '".$tableName."' sequence number!";  exit(3); }
}

function companyID($companies, $company_name)   
{
   $query_companies = "Select id, name  FROM ab_companies ";
   $result_companies = mysql_query($query_companies);

   $company_id = 0;
   $company_name = trim($company_name);  /* $result_companies*/
   while($companydetails = mysql_fetch_array($result_companies))
   {
      $company = trim($companydetails['name']);
//         print "Company ++> '".$company."'  \n";
      if (strcasecmp($company_name, $company) == 0 )
      {
         $company_id = $companydetails['id'];
//         print "=====> ".$company_id."  ".$company_name."  = ".$companydetails['name']."\n";
         return $company_id;
      }
   }
//   print "-----> '".$company_name."' not found \n";   // Print out all company names which could not be matched, so we can create Company records as required.
   return $company_id;
}
function is_date( $str )
{
   $stamp = strtotime( $str );
   if (!is_numeric($stamp)) return FALSE;
   $month = date( 'm', $stamp );
   $day   = date( 'd', $stamp );
   $year  = date( 'Y', $stamp );
    if (checkdate($month, $day, $year))  return TRUE; 
   return FALSE;
}

?>




Thanks a lot!
ocb
 
Posts: 1
Joined: Fri Mar 02, 2012 3:50 am

Re: Global Address Book

Postby schwarzkopf » Fri Jun 01, 2012 1:05 pm

Thanks for your script GoAlways!

I modified it:
* use source_id in ab_contacts
* Add flag $syncBirthday
* Use database config from /etc/groupoffice/config.php
* Add excludeUser_ids for exclude admin and system users

Or have GO this feature in the meantime?



Code: Select all
<?php
/*
 * Orginal from GoAlways, see http://www.group-office.com/forum/viewtopic.php?f=6&t=7338
 *
 *
 * @author: GoAlways
 * Klaus Schwarzkopf <schwarzkopf@sensortherm.de>
 * Changes:
 *
 * use source_id in ab_contacts
 * Add flag $syncBirthday
 * Use database config from /etc/groupoffice/config.php
 * Add excludeUser_ids for exclude admin and system users
 */

/* For cron: crontab -e
 *
 * 0 22 * * * root /usr/bin/php /root/bin/users2addressbook.php >> /var/log/users2addressbook.log
 */

require_once('/etc/groupoffice/config.php');


/*  Connect to database */

$addressbookOwnerID = '1';           // This is usually the UserID of the Group Office Admin accout that is sharing their address book as a Global Address book
$addressbookToSync_id = '31';       // The ID of which calendar is being shared globally to all uses as the Global Address book
$syncBirthday = TRUE;                // TRUE or FALSE;  For security reasons, providing birthday is too personal for a Global Address book

$excludeUser_ids = array(1, 4, 28);          //For admin and system accounts

$DATAb = mysql_connect($config['db_host'], $config['db_user'], $config['db_pass']);
mysql_select_db($config['db_name'], $DATAb);
//   exit();
/* need to lock the database tables "next sequence and ab_contact ?? just now so no one else can create a record */
/* Get a list of all the company names and ID numbers from the go_users table  */
$query_companies = "Select id, name  FROM ab_companies ";
global $result_companies;
$result_companies = mysql_query($query_companies) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");

$SearchCmd = "";
foreach ($excludeUser_ids as  $excludeUser_id) {
    $SearchCmd .= " AND go_users.id != $excludeUser_id ";
}
/* Get all the active users from the go_users table  */
$query_users = "Select *  FROM go_users WHERE enabled = '1' $SearchCmd ORDER BY go_users.id ASC";
$result_users = mysql_query($query_users) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
// print "Number of go_users are ".mysql_num_rows($result_users)."\n\n";
while ($go_users = mysql_fetch_array($result_users)) {
    // print  "\nUserID: $go_users[id],  $go_users[first_name] $go_users[last_name] -> ";
    /* Select Contacts from ab_contacts Global Address book records */
    $query_contacts = "Select ab_contacts.*, ab_companies.name AS company FROM ab_contacts LEFT JOIN ab_companies ON (ab_contacts.company_id = ab_companies.id ) WHERE ab_contacts.addressbook_id = '$addressbookToSync_id' AND ab_contacts.user_id = '$addressbookOwnerID' AND ab_contacts.source_id = '$go_users[id]' ";
   
    //echo $query_contacts;
    $result_contacts = mysql_query($query_contacts) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
    // print "Number of ab_contacts records are ".mysql_num_rows($result_contacts)."\n\n";      // for debugging, not required for normal logging.
    //   exit();
    if (mysql_num_rows($result_contacts) > 0) { /* there should only be one record */
        $contacts_users = mysql_fetch_array($result_contacts);
        /* check record details to see if any chages had been made */
        $Changes = false;
        // print " UPDATE: ";   // for debugging, not required for normal logging.
        $id = 0;
        $UpdateCmd = "UPDATE ab_contacts SET ";
        if (strcmp($go_users['first_name'], $contacts_users['first_name']) != 0) {
            $Changes = true;
            $UpdateCmd .= " first_name = '" . mysql_real_escape_string($go_users['first_name']) . "',";
        }
        if (strcmp($go_users['middle_name'], $contacts_users['middle_name']) != 0) {
            $Changes = true;
            $UpdateCmd .= " middle_name = '" . mysql_real_escape_string($go_users['middle_name']) . "',";
        }
        if (strcmp($go_users['last_name'], $contacts_users['last_name']) != 0) {
            $Changes = true;
            $UpdateCmd .= " last_name = '" . mysql_real_escape_string($go_users['last_name']) . "',";
        }
        if (strcmp($go_users['initials'], $contacts_users['initials']) != 0) {
            $Changes = true;
            $UpdateCmd .= " initials = '" . mysql_real_escape_string($go_users['initials']) . "',";
        }
        if (strcmp($go_users['title'], $contacts_users['title']) != 0) {
            $Changes = true;
            $UpdateCmd .= " title = '" . mysql_real_escape_string($go_users['title']) . "',";
        }
        if (strcmp($go_users['sex'], $contacts_users['sex']) != 0) {
            $Changes = true;
            $UpdateCmd .= " sex = '" . $go_users['sex'] . "',";
        }
        if ($syncBirthday) //  For security reasons, providing birthday is too personal for a Global Address book
            if (strcmp($go_users['birthday'], $contacts_users['birthday']) != 0) {
                $Changes = true;
                $UpdateCmd .= " birthday = '" . $go_users['birthday'] . "',";
            }

        if (strcmp($go_users['email'], $contacts_users['email']) != 0) {
            $Changes = true;
            $UpdateCmd .= " email = '" . mysql_real_escape_string($go_users['email']) . "',";
        }
        $company_id = "";
        if (strcmp($go_users['company'], $contacts_users['company']) != 0) {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) {
                $Changes = true;
                $UpdateCmd .= " company_id = '" . $company_id . "',";
            } else {
                print "\nUserID: $go_users[id],  $go_users[first_name] $go_users[last_name] -> ";  // disable if debugging
                print " Could not find company  '" . ($go_users['company']) . "' -> ";
            }
        }
        if (strcmp($go_users['department'], $contacts_users['department']) != 0) {
            $Changes = true;
            $UpdateCmd .= " department = '" . mysql_real_escape_string($go_users['department']) . "',";
        }
        if (strcmp($go_users['function'], $contacts_users['function']) != 0) {
            $Changes = true;
            $UpdateCmd .= " function = '" . mysql_real_escape_string($go_users['function']) . "',";
        }
        if (strcmp($go_users['home_phone'], $contacts_users['home_phone']) != 0) {
            $Changes = true;
            $UpdateCmd .= " home_phone = '" . mysql_real_escape_string($go_users['home_phone']) . "',";
        }
        if (strcmp($go_users['work_phone'], $contacts_users['work_phone']) != 0) {
            $Changes = true;
            $UpdateCmd .= " work_phone = '" . mysql_real_escape_string($go_users['work_phone']) . "',";
        }
        if (strcmp($go_users['fax'], $contacts_users['fax']) != 0) {
            $Changes = true;
            $UpdateCmd .= " fax = '" . mysql_real_escape_string($go_users['fax']) . "',";
        }
        if (strcmp($go_users['cellular'], $contacts_users['cellular']) != 0) {
            $Changes = true;
            $UpdateCmd .= " cellular = '" . mysql_real_escape_string($go_users['cellular']) . "',";
        }
        if (strcmp($go_users['country'], $contacts_users['country']) != 0) {
            $Changes = true;
            $UpdateCmd .= " country = '" . mysql_real_escape_string($go_users['country']) . "',";
        }
        if (strcmp($go_users['state'], $contacts_users['state']) != 0) {
            $Changes = true;
            $UpdateCmd .= " state = '" . mysql_real_escape_string($go_users['state']) . "',";
        }
        if (strcmp($go_users['zip'], $contacts_users['zip']) != 0) {
            $Changes = true;
            $UpdateCmd .= " zip = '" . mysql_real_escape_string($go_users['zip']) . "',";
        }
        if (strcmp($go_users['city'], $contacts_users['city']) != 0) {
            $Changes = true;
            $UpdateCmd .= " city = '" . mysql_real_escape_string($go_users['city']) . "',";
        }
        if (strcmp($go_users['address'], $contacts_users['address']) != 0) {
            $Changes = true;
            $UpdateCmd .= " address = '" . mysql_real_escape_string($go_users['address']) . "',";
        }
        if (strcmp($go_users['address_no'], $contacts_users['address_no']) != 0) {
            $Changes = true;
            $UpdateCmd .= " address_no = '" . mysql_real_escape_string($go_users['address_no']) . "',";
        }
        if ($Changes) {   // do we really want email_allowed to be updated? what does it do anyway?, so we will set it back to what it oringinally was. 
            // Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook
            // To link this user with their corresponding record in the Global Address book, you need to create a new field called 'user_id' in the ab_conatacts table.
            $UpdateCmd .= " email_allowed = '$contacts_users[email_allowed]' WHERE addressbook_id = '$addressbookToSync_id' AND user_id = '$addressbookOwnerID' AND source_id = '$go_users[id]'";
            $update_result = mysql_query($UpdateCmd) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
            print $UpdateCmd . "\n\n";
            //exit();  /* For testing only - tests one record at a time. */
        } else {
            // print  " ab_contacts record '$contacts_users[id]' did not require changes. ($UpdateCmd)\n";  // for debugging, not required for normal logging.
        }
    } else { /* this user does not yet have a Global Addressbook Contact record, so lets insert a new record for them.  */
        /* Set the user_id and addressbook_id of your adminstrator's shared addressbook which you use as your Global Addressbook */
        print " INSERT: ";
        $newid = nextSegNo("ab_contacts");
        $InsertCmd = "INSERT INTO ab_contacts SET id = '$newid', user_id = '$addressbookOwnerID', addressbook_id = '$addressbookToSync_id' , source_id = '$go_users[id]', ";
        if (!empty($go_users['first_name']))
            $InsertCmd .= " first_name = '" . mysql_real_escape_string($go_users['first_name']) . "',";
        if (!empty($go_users['middle_name']))
            $InsertCmd .= " middle_name = '" . mysql_real_escape_string($go_users['middle_name']) . "',";
        if (!empty($go_users['last_name']))
            $InsertCmd .= " last_name = '" . mysql_real_escape_string($go_users['last_name']) . "',";
        if (!empty($go_users['initials']))
            $InsertCmd .= " initials = '" . mysql_real_escape_string($go_users['initials']) . "',";
        if (!empty($go_users['title']))
            $InsertCmd .= " title = '" . mysql_real_escape_string($go_users['title']) . "',";
        if (!empty($go_users['sex']))
            $InsertCmd .= " sex = '" . $go_users['sex'] . "',";
        if ($syncBirthday) //  For security reasons, providing birthday is too personal for a Global Address book
            if (is_date($go_users['birthday']))
                $InsertCmd .= " birthday = '" . $go_users['birthday'] . "',"; 
        if (!empty($go_users['email']))
            $InsertCmd .= " email = '" . mysql_real_escape_string($go_users['email']) . "',";
        if (!empty($go_users['company'])) /* company is a dropdown list */ {
            $company_id = companyID($result_companies, $go_users['company']);
            if ($company_id > 0) {
                $InsertCmd .= " company_id = '" . $company_id . "',";
            } else {
                $InsertCmd .= " comment = '" . mysql_real_escape_string($go_users['company']) . "',";
            }
        }
        if (!empty($go_users['department'])) {
            $InsertCmd .= " department = '" . mysql_real_escape_string($go_users['department']) . "',";
        }
        if (!empty($go_users['function'])) {
            $InsertCmd .= " function = '" . mysql_real_escape_string($go_users['function']) . "',";
        }
        if (!empty($go_users['home_phone'])) {
            $InsertCmd .= " home_phone = '" . mysql_real_escape_string($go_users['home_phone']) . "',";
        }
        if (!empty($go_users['work_phone'])) {
            $InsertCmd .= " work_phone = '" . mysql_real_escape_string($go_users['work_phone']) . "',";
        }
        if (!empty($go_users['fax'])) {
            $InsertCmd .= " fax = '" . mysql_real_escape_string($go_users['fax']) . "',";
        }
        if (!empty($go_users['cellular'])) {
            $InsertCmd .= " cellular = '" . mysql_real_escape_string($go_users['cellular']) . "',";
        }
        if (!empty($go_users['country'])) {
            $InsertCmd .= " country = '" . mysql_real_escape_string($go_users['country']) . "',";
        }
        if (!empty($go_users['state'])) {
            $InsertCmd .= " state = '" . mysql_real_escape_string($go_users['state']) . "',";
        }
        if (!empty($go_users['zip'])) {
            $InsertCmd .= " zip = '" . mysql_real_escape_string($go_users['zip']) . "',";
        }
        if (!empty($go_users['city'])) {
            $InsertCmd .= " city = '" . mysql_real_escape_string($go_users['city']) . "',";
        }
        if (!empty($go_users['address'])) {
            $InsertCmd .= " address = '" . mysql_real_escape_string($go_users['address']) . "',";
        }
        if (!empty($go_users['address_no'])) {
            $InsertCmd .= " address_no = '" . mysql_real_escape_string($go_users['address_no']) . "',";
        }
        $InsertCmd .= " email_allowed = '1', iso_address_format = 'AU' ";  /* By default set email_allowed to true */
        $Insert_result = mysql_query($InsertCmd) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
        print "\n" . $InsertCmd . "\n\n";
        //exit();  /* For testing only - tests one record at a time. */
    } /* end of Update/Insert Contact details for this User.  */
}

print "\nChecking for users who should be removed from the Contacts Addressbook\n";
/* Delete contacts who were added from the go_users table by the sync process if they are no longer active in the go_users table or
  have been deleted from the go_users table, which means that any contacts added specifically by the Owner of this addressbook, should not be deleted.
  The code "ab_contacts.first_name AS fname, ab_contacts.last_name AS sname," is only required for debugging purposes, and could be removed if you wanted to.
 */
$SearchCmd = "";
foreach ($excludeUser_ids as  $excludeUser_id) {
    $SearchCmd .= " OR ne.ab_source_id = $excludeUser_id ";
}

$query_contacts = "SELECT ne.* FROM (SELECT    ab_contacts.id as ab_id, ab_contacts.first_name AS fname, ab_contacts.last_name AS sname, 
                           ab_contacts.user_id AS go_user_id, go_users.enabled AS enabled, ab_contacts.source_id AS ab_source_id
                        FROM ab_contacts LEFT JOIN go_users ON (ab_contacts.user_id = go_users.id)
                        WHERE ab_contacts.user_id > 0 AND ab_contacts.addressbook_id = '$addressbookToSync_id'  AND ab_contacts.user_id = '$addressbookOwnerID'
               ) ne  WHERE   ne.enabled = '0' OR ne.enabled IS NULL $SearchCmd";

//echo $query_contacts;

$result_users_contacts = mysql_query($query_contacts) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
while ($ab_user = mysql_fetch_array($result_users_contacts)) {
    /* Note: Check for "ab_contacts.addressbook_id = '$addressbookToSync_id'  AND ab_contacts.user_id = '$addressbookOwnerID' " should not be required, but I included for extra assurance I am not deleteing from someone else's addressbook */
    $DeleteCmd = "DELETE FROM ab_contacts WHERE ab_contacts.id = '" . $ab_user['ab_id'] . "' AND ab_contacts.addressbook_id = '" . $addressbookToSync_id . "'  AND ab_contacts.user_id = '" . $addressbookOwnerID . "' ";
    $update_result = mysql_query($DeleteCmd);
    print "$ab_user[fname] $ab_user[sname]  - " . $DeleteCmd . "\n";  // Remark this line out if you do not want the extra logging.
}
Print "\n============ Global Addressbook synchronisation completed ====================\n\n\n";
#===== PHP Functions below =================================================================================================================

function nextSegNo($tableName) { /* as found in base_db.class.inc.php */
    /* WARNING: need to lock the database just now so no one else can create a record, but I have not done this yet,! */
    $query_seq = "Select * FROM go_db_sequence WHERE seq_name = '$tableName' ";
    $result_seq = mysql_query($query_seq) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
    if (mysql_num_rows($result_seq) > 0) {
        $result_rec = mysql_fetch_array($result_seq);
        $newID = $result_rec['nextid'] + 1;
        $sql_result = mysql_query("UPDATE go_db_sequence   SET nextid = '$newID'  WHERE seq_name = '$tableName' ") or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
        return $newID;
    } else {
        /* No sequence in table, so create an entry */
        $query_seq_new = "INSERT INTO go_db_sequence (`seq_name` ,`nextid`)VALUES ('ab_contacts',  '$tableName');";
        $result = mysql_query($query_seq_new) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");
        return 0;
        //print ">>>>>> We had a major database error attempting to update the '".$tableName."' sequence number!";  exit(3);
    }
}

function companyID($companies, $company_name) {
    $query_companies = "Select id, name  FROM ab_companies ";
    $result_companies = mysql_query($query_companies) or die(__FILE__ . ': ' . __LINE__ . ': ' . mysql_error() . "\n");

    $company_id = 0;
    $company_name = trim($company_name);  /* $result_companies */
    while ($companydetails = mysql_fetch_array($result_companies)) {
        $company = trim($companydetails['name']);
//         print "Company ++> '".$company."'  \n";
        if (strcasecmp($company_name, $company) == 0) {
            $company_id = $companydetails['id'];
//         print "=====> ".$company_id."  ".$company_name."  = ".$companydetails['name']."\n";
            return $company_id;
        }
    }
//   print "-----> '".$company_name."' not found \n";   // Print out all company names which could not be matched, so we can create Company records as required.
    return $company_id;
}

function is_date($str) {
    $stamp = strtotime($str);
    if (!is_numeric($stamp))
        return FALSE;
    $month = date('m', $stamp);
    $day = date('d', $stamp);
    $year = date('Y', $stamp);
    if (checkdate($month, $day, $year))
        return TRUE;
    return FALSE;
}

?>
schwarzkopf
 
Posts: 11
Joined: Fri May 11, 2012 7:45 am


Return to General help

Who is online

Users browsing this forum: No registered users and 0 guests

cron