<?php
/*
 * This code is part of GOsa (http://www.gosa-project.org)
 * Copyright (C) 2003-2008 GONICUS GmbH
 *
 * ID: $$Id: class_user.inc 13282 2008-12-12 12:31:08Z cajus $$
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*!
  \brief   user plugin
  \author  Cajus Pollmeier <pollmeier@gonicus.de>
  \version 2.00
  \date    24.07.2003

  This class provides the functionality to read and write all attributes
  relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
  from/to the LDAP. It does syntax checking and displays the formulars required.
 */

class user extends plugin
{
  /* Definitions */
  var $plHeadline= "Generic";
  var $plDescription= "Edit organizational user settings";

  /* The attribute gotoLastSystemLogin represents the timestamp of the last 
      successfull login on the users workstation. 
     Read the FAQ to get a hint about how to configure this.
   */
  var $gotoLastSystemLogin = "";

  /* Plugin specific values */
  var $base= "";
  var $orig_base= "";
  var $cn= "";
  var $new_dn= "";
  var $personalTitle= "";
  var $academicTitle= "";
  var $homePostalAddress= "";
  var $homePhone= "";
  var $labeledURI= "";
  var $o= "";
  var $ou= "";
  var $departmentNumber= "";
  var $employeeNumber= "";
  var $employeeType= "";
  var $roomNumber= "";
  var $telephoneNumber= "";
  var $facsimileTelephoneNumber= "";
  var $mobile= "";
  var $pager= "";
  var $l= "";
  var $st= "";
  var $postalAddress= "";
  var $dateOfBirth;
  var $use_dob= "0";
  var $gender="0";
  var $preferredLanguage="0";

  var $jpegPhoto= "*removed*";
  var $photoData= "";
  var $old_jpegPhoto= "";
  var $old_photoData= "";
  var $cert_dialog= FALSE;
  var $picture_dialog= FALSE;
  var $pwObject= NULL;

  var $userPKCS12= "";
  var $userSMIMECertificate= "";
  var $userCertificate= "";
  var $certificateSerialNumber= "";
  var $old_certificateSerialNumber= "";
  var $old_userPKCS12= "";
  var $old_userSMIMECertificate= "";
  var $old_userCertificate= "";

  var $gouvernmentOrganizationalUnit= "";
  var $houseIdentifier= "";
  var $street= "";
  var $postalCode= "";
  var $vocation= "";
  var $ivbbLastDeliveryCollective= "";
  var $gouvernmentOrganizationalPersonLocality= "";
  var $gouvernmentOrganizationalUnitDescription= "";
  var $gouvernmentOrganizationalUnitSubjectArea= "";
  var $functionalTitle= "";
  var $role= "";
  var $publicVisible= "";

  var $orig_dn;
  var $dialog;

  /* variables to trigger password changes */
  var $pw_storage= "md5";
  var $last_pw_storage= "unset";
  var $had_userCertificate= FALSE;

  var $view_logged = FALSE;

  /* attribute list for save action */
  var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
      "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
      "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
      "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
      "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");

  var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
      "gosaAccount");

  /* attributes that are part of the government mode */
  var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
      "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
      "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
      "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
      "postalCode");

  var $multiple_support = TRUE;

  var $governmentmode = FALSE;

  /* constructor, if 'dn' is set, the node loads the given
     'dn' from LDAP */
  function user (&$config, $dn= NULL)
  {
    $this->config= $config;
    /* Configuration is fine, allways */
    if($this->config->get_cfg_value("honourIvbbAttributes") == "true"){
      $this->governmentmode = TRUE;
      $this->attributes=array_merge($this->attributes,$this->govattrs);
    }

    /* Load base attributes */
    plugin::plugin ($config, $dn);

    /*  If gotoLastSystemLogin is available read it from ldap and create a readable
        date time string.
     */
    if(isset($this->attrs['gotoLastSystemLogin'][0]) && preg_match("/^[0-9]*$/",$this->attrs['gotoLastSystemLogin'][0])){
      $this->gotoLastSystemLogin = date("d.m.Y H:i:s", $this->attrs['gotoLastSystemLogin'][0]);
    }

    $this->orig_dn  = $this->dn;
    $this->new_dn   = $dn;

    if ($this->governmentmode){
      /* Fix public visible attribute if unset */
      if (!isset($this->attrs['publicVisible'])){
        $this->publicVisible == "nein";
      }
    }

    /* Load government mode attributes */
    if ($this->governmentmode){
      /* Copy all attributs */
      foreach ($this->govattrs as $val){
        if (isset($this->attrs["$val"][0])){
          $this->$val= $this->attrs["$val"][0];
        }
      }
    }

    /* Create me for new accounts */
    if ($dn == "new"){
      $this->is_account= TRUE;
    }

    /* Make hash default to md5 if not set in config */
    $hash= $this->config->get_cfg_value("passwordDefaultHash", "crypt/md5");

    /* Load data from LDAP? */
    if ($dn !== NULL){

      /* Do base conversation */
      if ($this->dn == "new"){
        $ui= get_userinfo();
        $this->base= dn2base($ui->dn);
      } else {
        $this->base= dn2base($dn);
      }

      /* get password storage type */
      if (isset ($this->attrs['userPassword'][0])){
      	/* Initialize local array */
      	$matches= array();
        if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
          $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
          if(is_object($tmp)){
            $this->pw_storage= $tmp->get_hash(); 
          }

        } else {
          if ($this->attrs['userPassword'][0] != ""){
            $this->pw_storage= "clear";
          } else {
            $this->pw_storage= $hash;
          }
        }
      } else {
        /* Preset with vaule from configuration */
        $this->pw_storage= $hash;
      }

      /* Load extra attributes: certificate and picture */
      $this->load_cert();
      $this->load_picture();
      if ($this->userCertificate != ""){
        $this->had_userCertificate= TRUE;
      }
    }

    /* Reset password storage indicator, used by password_change_needed() */
    if ($dn == "new"){
      $this->last_pw_storage= "unset";
    } else {
      $this->last_pw_storage= $this->pw_storage;
    }

    /* Generate dateOfBirth entry */
    if (isset ($this->attrs['dateOfBirth'])){
      /* This entry is ISO 8601 conform */
      list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
    
      $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
      $this->use_dob= "1";
    } else {
      $this->use_dob= "0";
    }

    /* Put gender attribute to upper case */
    if (isset ($this->attrs['gender'])){
      $this->gender= strtoupper($this->attrs['gender'][0]);
    }
 
    $this->orig_base = $this->base;
  }




  /* execute generates the html output for this node */
  function execute()
  {
    /* Call parent execute */
    plugin::execute();

    /* Log view */
    if($this->is_account && !$this->view_logged){
      $this->view_logged = TRUE;
      new log("view","users/".get_class($this),$this->dn);
    }

    $smarty= get_smarty();
    $smarty->assign("gotoLastSystemLogin",$this->gotoLastSystemLogin);

    /* Fill calendar */
    if ($this->dateOfBirth == "0"){
      $date= getdate();
    } else {
      if(is_array($this->dateOfBirth)){
        $date = $this->dateOfBirth;
  
        // Trigger on dates like 1985-04-01, getdate only understands timestamps
      } else if (!empty($this->dateOfBirth) && !is_numeric($this->dateOfBirth)){
        $date= getdate(strtotime($this->dateOfBirth));

      } else {
        $date = getdate($this->dateOfBirth);
      }
    }

    $days= array();
    for($d= 1; $d<32; $d++){
      $days[$d]= $d;
    }
    $years= array();

    if(($date['year']-100)<1901){
      $start = 1901;
    }else{
      $start = $date['year']-100;
    }

    $end = $start +100;
    
    for($y= $start; $y<=$end; $y++){
      $years[]= $y;
    }
    $years['-']= "-&nbsp;";
    $months= msgPool::months();
    $months['-'] = '-&nbsp;';

    $smarty->assign("day", $date["mday"]);
    $smarty->assign("days", $days);
    $smarty->assign("months", $months);
    $smarty->assign("month", $date["mon"]-1);
    $smarty->assign("years", $years);
    $smarty->assign("year", $date["year"]);

    /* Assign sex */
    $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
    $smarty->assign("gender_list", $sex);
    $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
    $smarty->assign("preferredLanguage_list", $language);

    /* Get random number for pictures */
    srand((double)microtime()*1000000); 
    $smarty->assign("rand", rand(0, 10000));


    /* Do we represent a valid gosaAccount? */
    if (!$this->is_account){
      $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
        msgPool::noValidExtension("GOsa")."</b>";
      return($str);
    }

    /* Base select dialog */
    $once = true;
    foreach($_POST as $name => $value){
      if(preg_match("/^chooseBase/",$name) && $once && $this->acl_is_writeable("base")){
        $once = false;
        $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
        $this->dialog->setCurrentBase($this->base);
      }
    }

    /* Password configure dialog handling */
    if(is_object($this->pwObject) && $this->pwObject->display){
      $output= $this->pwObject->configure();
      if ($output != ""){
        $this->dialog= TRUE;
        return $output;
      }
      $this->dialog= false;
    }

    /* Dialog handling */
    if(is_object($this->dialog)){
      /* Must be called before save_object */
      $this->dialog->save_object();
   
      if($this->dialog->isClosed()){
        $this->dialog = false;
      }elseif($this->dialog->isSelected()){

        /* check if selected base is allowed to move to / create a new object */
        $tmp = $this->get_allowed_bases();
        if(isset($tmp[$this->dialog->isSelected()])){
          $this->base = $this->dialog->isSelected();
        }
        $this->dialog= false;
      }else{
        return($this->dialog->execute());
      }
    }

    /* Want password method editing? */
    if ($this->acl_is_writeable("userPassword")){
      if (isset($_POST['edit_pw_method'])){
        if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
          $temp= passwordMethod::get_available_methods();
          $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
        }
        $this->pwObject->display = TRUE;
        $this->dialog= TRUE;
        return ($this->pwObject->configure());
      }
    }

    /* Want picture edit dialog? */
    if($this->acl_is_writeable("userPicture")) {
      if (isset($_POST['edit_picture'])){
        /* Save values for later recovery, in case some presses
           the cancel button. */
        $this->old_jpegPhoto= $this->jpegPhoto;
        $this->old_photoData= $this->photoData;
        $this->picture_dialog= TRUE;
        $this->dialog= TRUE;
      }
    }

    /* Remove picture? */
    if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
      if (isset($_POST['picture_remove'])){
        $this->set_picture ();
        $this->jpegPhoto= "*removed*";
        $this->is_modified= TRUE;
        return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
      }
    }

    /* Save picture */
    if (isset($_POST['picture_edit_finish'])){

      /* Check for clean upload */
      if ($_FILES['picture_file']['name'] != ""){
        if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
          msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
        }else{
          /* Activate new picture */
          $this->set_picture($_FILES['picture_file']['tmp_name']);
        }
      }
      $this->picture_dialog= FALSE;
      $this->dialog= FALSE;
      $this->is_modified= TRUE;
    }


    /* Cancel picture */
    if (isset($_POST['picture_edit_cancel'])){

      /* Restore values */
      $this->jpegPhoto= $this->old_jpegPhoto;
      $this->photoData= $this->old_photoData;

      /* Update picture */
      session::set('binary',$this->photoData);
      session::set('binarytype',"image/jpeg");
      $this->picture_dialog= FALSE;
      $this->dialog= FALSE;
    }

    /* Toggle dateOfBirth information */
    if (isset($_POST['set_dob'])){
      $this->use_dob= ($this->use_dob == "0")?"1":"0";
    }


    /* Want certificate= */
    if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){

      /* Save original values for later reconstruction */
      foreach (array("certificateSerialNumber", "userCertificate",
            "userSMIMECertificate", "userPKCS12") as $val){

        $oval= "old_$val";
        $this->$oval= $this->$val;
      }

      $this->cert_dialog= TRUE;
      $this->dialog= TRUE;
    }


    /* Cancel certificate dialog */
    if (isset($_POST['cert_edit_cancel'])){

      /* Restore original values in case of 'cancel' */
      foreach (array("certificateSerialNumber", "userCertificate",
            "userSMIMECertificate", "userPKCS12") as $val){

        $oval= "old_$val";
        $this->$val= $this->$oval;
      }
      $this->cert_dialog= FALSE;
      $this->dialog= FALSE;
    }


    /* Remove certificate? */
    if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
      foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
        if (isset($_POST["remove_$val"])){

          /* Reset specified cert*/
          $this->$val= "";
          $this->is_modified= TRUE;
        }
      }
    }

    /* Upload new cert and close dialog? */	
    if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 

      $fail =false;

      if (isset($_POST['cert_edit_finish'])){

        /* for all certificates do */
        foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
            as $val){

          /* Check for clean upload */
          if (array_key_exists($val."_file", $_FILES) &&
              array_key_exists('name', $_FILES[$val."_file"]) &&
              $_FILES[$val."_file"]['name'] != "" &&
              is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
            $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
          }
        }

        /* Save serial number */
        if (isset($_POST["certificateSerialNumber"]) &&
            $_POST["certificateSerialNumber"] != ""){

          if (!tests::is_id($_POST["certificateSerialNumber"])){
            $fail = true;
            msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);

            foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
              if ($this->$cert != ""){
                $smarty->assign("$cert"."_state", "true");
              } else {
                $smarty->assign("$cert"."_state", "");
              }
            }
          }

          $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
          $this->is_modified= TRUE;
        }
        if(!$fail){
          $this->cert_dialog= FALSE;
          $this->dialog= FALSE;
        }
      }
    }
    /* Display picture dialog */
    if ($this->picture_dialog){
      return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
    }

    /* Display cert dialog */
    if ($this->cert_dialog){
      $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
      $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
      $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);

      foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
        if ($this->$cert != ""){
          /* import certificate */
          $certificate = new certificate;
          $certificate->import($this->$cert);
      
          /* Read out data*/
          $timeto   = $certificate->getvalidto_date();
          $timefrom = $certificate->getvalidfrom_date();
         
          
          /* Additional info if start end time is '0' */
          $add_str_info = "";
          if($timeto == 0 && $timefrom == 0){
            $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
          }

          $str = "<table summary=\"\" border=0>
                    <tr>
                      <td style='vertical-align:top'>CN</td>
                      <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
                    </tr>
                  </table><br>".

                  sprintf(_("Certificate is valid from %s to %s and is currently %s."),
                        "<b>".date('d M Y',$timefrom)."</b>",
                        "<b>".date('d M Y',$timeto)."</b>",
                        $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
                                                "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;

          $smarty->assign($cert."info",$str);
          $smarty->assign($cert."_state","true");
        } else {
          $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
          $smarty->assign($cert."_state","");
        }
      }
  
      if($this->governmentmode){
        $smarty->assign("honourIvbbAttributes", "true");
      }else{
        $smarty->assign("honourIvbbAttributes", "false");
      }
      $smarty->assign("governmentmode", $this->governmentmode);
      return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
    }

    /* Prepare password hashes */
    if ($this->pw_storage == ""){
      $this->pw_storage= $this->config->get_cfg_value("hash");
    }

    $temp= passwordMethod::get_available_methods();
    $is_configurable= FALSE;
    $hashes = $temp['name'];
    if(isset($temp[$this->pw_storage])){
      $test= new $temp[$this->pw_storage]($this->config);
      $is_configurable= $test->is_configurable();
    }else{
      new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
    }


    /* Create password methods array */
    $pwd_methods = array();
    foreach($hashes as $id => $name){
      if(!empty($temp['desc'][$id])){
        $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
      }else{
        $pwd_methods[$name] = $name;
      }
    }
 
    /* Load attributes and acl's */
    $ui =get_userinfo();
    foreach($this->attributes as $val){
      $smarty->assign("$val", $this->$val);
      if(in_array($val,$this->multi_boxes)){
        $smarty->assign("use_".$val,TRUE);
      }else{
        $smarty->assign("use_".$val,FALSE);
      }
    }
    foreach(array("base","pw_storage","edit_picture") as $val){
      if(in_array($val,$this->multi_boxes)){
        $smarty->assign("use_".$val,TRUE);
      }else{
        $smarty->assign("use_".$val,FALSE);
      }
    }

    /* Set acls */
    $tmp = $this->plinfo();
    foreach($tmp['plProvidedAcls'] as $val => $translation){
      $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
    }

    $smarty->assign("pwmode", $pwd_methods);
    $smarty->assign("pwmode_select", $this->pw_storage);
    $smarty->assign("pw_configurable", $is_configurable);
    $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
    $smarty->assign("base_select",      $this->base);

    if(!session::is_set('edit')){
      $smarty->assign("CertificatesACL","");
    }else{
      $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
    }
    
    $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
    $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));

    /* Create base acls */
    $tmp = @$this->allowedBasesToMoveTo();
    $smarty->assign("bases", $tmp);

    /* Save government mode attributes */
    if($this->governmentmode){
      $smarty->assign("governmentmode", "true");
      $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
          "internet,ivbv", "internet,testa", "internet,ivbv,testa");
      $smarty->assign("ivbbmodes", $ivbbmodes);
      foreach ($this->govattrs as $val){
        $smarty->assign("$val", $this->$val);
        $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
      }
    } else {
      $smarty->assign("governmentmode", "false");
    }

    /* Special mode for uid */
    $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
    if (isset ($this->dn)){
      if ($this->dn != "new"){
        $uidACL= preg_replace("/w/","",$uidACL);
      }
    }  else {
      $uidACL= preg_replace("/w/","",$uidACL);
    }
    
    $smarty->assign("uidACL", $uidACL);
    $smarty->assign("is_template", $this->is_template);
    $smarty->assign("use_dob", $this->use_dob);

    if (isset($this->parent)){
      if (isset($this->parent->by_object['phoneAccount']) &&
          $this->parent->by_object['phoneAccount']->is_account){
        $smarty->assign("has_phoneaccount", "true");
      } else {
        $smarty->assign("has_phoneaccount", "false");
      }
    } else {
      $smarty->assign("has_phoneaccount", "false");
    }
    $smarty->assign("multiple_support" , $this->multiple_support_active);
    return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
  }


  /* remove object from parent */
  function remove_from_parent()
  {
    /* Only remove valid accounts */
    if(!$this->initially_was_account) return;

    /* Remove password extension */
    $temp= passwordMethod::get_available_methods();

    /* Remove password method from user account */
    if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
      $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
      $this->pwObject->remove_from_parent();
    }

    /* Remove user */
    $ldap= $this->config->get_ldap_link();
    $ldap->rmdir ($this->dn);
    if (!$ldap->success()){
      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
    }
  
    new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
  
    /* Delete references to groups */
    $ldap->cd ($this->config->current['BASE']);
    $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
    while ($ldap->fetch()){
      $g= new group($this->config, $ldap->getDN());
      $g->removeUser($this->uid);
      $g->save ();
    }

    /* Delete references to object groups */
    $ldap->cd ($this->config->current['BASE']);
    $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
    while ($ldap->fetch()){
      $og= new ogroup($this->config, $ldap->getDN());
      unset($og->member[$this->dn]);
      $og->save ();
    }

    /* If needed, let the password method do some cleanup */
    $tmp = new passwordMethod($this->config);
    $available = $tmp->get_available_methods();
    if (in_array_ics($this->pw_storage, $available['name'])){
      $test= new $available[$this->pw_storage]($this->config);
      $test->attrs= $this->attrs;
      $test->dn= $this->dn;
      $test->remove_from_parent();
    }

    /* Remove ACL dependencies too */
    $tmp = new acl($this->config,$this->parent,$this->dn);
    $tmp->remove_acl();

    /* Optionally execute a command after we're done */
    $this->handle_post_events("remove",array("uid" => $this->uid));
  }


  /* Save data to object */
  function save_object()
  {
    if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){

      /* Make a backup of the current selected base */
      $base_tmp = $this->base;

      /* Parents save function */
      plugin::save_object ();

      /* Save government mode attributes */
      if ($this->governmentmode){
        foreach ($this->govattrs as $val){
          if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
            $data= stripcslashes($_POST["$val"]);
            if ($data != $this->$val){
              $this->is_modified= TRUE;
            }
            $this->$val= $data;
          }
        }
      }

      /* In template mode, the uid is autogenerated... */
      if ($this->is_template){
        $this->uid= strtolower($this->sn);
        $this->givenName= $this->sn;
      }

      /* Save base and pw_storage, since these are no LDAP attributes */
      if (isset($_POST['base'])){

        $tmp = $this->get_allowed_bases();
        if(isset($tmp[$_POST['base']])){
          $base= validate($_POST['base']);
          if ($base != $this->base){
            $this->is_modified= TRUE;
          }
          $this->base= $base;
        }else{
          $this->base = $base_tmp;
          msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
        }
      }

      /* Get pw_storage mode */
      if (isset($_POST['pw_storage'])){
        foreach(array("pw_storage") as $val){
          if(isset($_POST[$val])){
            $data= validate($_POST[$val]);
            if ($data != $this->$val){
              $this->is_modified= TRUE;
            }
            $this->$val= $data;
          }
        }
      }

      if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
        if ($this->acl_is_writeable("userPassword")){
          $temp= passwordMethod::get_available_methods();
          if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
            foreach($temp as $id => $data){
              if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
                $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
                break;
              }
            }
          }
        }
      }

      /* Save current cn
       */
      $this->cn = $this->givenName." ".$this->sn;
    }
  }

  function rebind($ldap, $referral)
  {
    $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
    if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
      $this->error = "Success";
      $this->hascon=true;
      $this->reconnect= true;
      return (0);
    } else {
      $this->error = "Could not bind to " . $credentials['ADMIN'];
      return NULL;
    }
  }

  
  /* Save data to LDAP, depending on is_account we save or delete */
  function save()
  {
    /* Only force save of changes .... 
       If this attributes aren't changed, avoid saving.
     */
    if($this->gender=="0") $this->gender ="";
    if($this->preferredLanguage=="0") $this->preferredLanguage ="";

    /* First use parents methods to do some basic fillup in $this->attrs */
    plugin::save ();

    if ($this->use_dob == "1"){
      /* If it is an array, the generic page has never been loaded - so there's no difference. Using an array would cause an error btw. */
      if(!is_array($this->attrs['dateOfBirth'])) {
        $this->attrs['dateOfBirth'] = date("Y-m-d", $this->dateOfBirth);
      }
    }

    /* Remove additional objectClasses */
    $tmp= array();
    foreach ($this->attrs['objectClass'] as $key => $set){
      $found= false;
      foreach (array("ivbbentry", "gosaUserTemplate") as $val){
        if (preg_match ("/^$set$/i", $val)){
          $found= true;
          break;
        }
      }
      if (!$found){
        $tmp[]= $set;
      }
    }

    /* Replace the objectClass array. This is done because of the
       separation into government and normal mode. */
    $this->attrs['objectClass']= $tmp;

    /* Add objectClasss for template mode? */
    if ($this->is_template){
      $this->attrs['objectClass'][]= "gosaUserTemplate";
    }

    /* Hard coded government mode? */
    if ($this->governmentmode){
      $this->attrs['objectClass'][]= "ivbbentry";

      /* Copy standard attributes */
      foreach ($this->govattrs as $val){
        if ($this->$val != ""){
          $this->attrs["$val"]= $this->$val;
        } elseif (!$this->is_new) {
          $this->attrs["$val"]= array();
        }
      }

      /* Remove attribute if set to "nein" */
      if ($this->publicVisible == "nein"){
        $this->attrs['publicVisible']= array();
        if($this->is_new){
          unset($this->attrs['publicVisible']);
        }else{
          $this->attrs['publicVisible']=array();
        }

      }

    }

    /* Special handling for attribute userCertificate needed */
    if ($this->userCertificate != ""){
      $this->attrs["userCertificate;binary"]= $this->userCertificate;
      $remove_userCertificate= false;
    } else {
      $remove_userCertificate= true;
    }

    /* Special handling for dateOfBirth value */
    if ($this->use_dob != "1"){
      if ($this->is_new) {
        unset($this->attrs["dateOfBirth"]);
      } else {
        $this->attrs["dateOfBirth"]= array();
      }
    }
    if (!$this->gender){
      if ($this->is_new) {
        unset($this->attrs["gender"]);
      } else {
        $this->attrs["gender"]= array();
      }
    }
    if (!$this->preferredLanguage){
      if ($this->is_new) {
        unset($this->attrs["preferredLanguage"]);
      } else {
        $this->attrs["preferredLanguage"]= array();
      }
    }

    /* Special handling for attribute jpegPhote needed, scale image via
       image magick to 147x200 pixels and inject resulting data. */
    if ($this->jpegPhoto == "*removed*"){
    
      /* Reset attribute to avoid writing *removed* as value */    
      $this->attrs["jpegPhoto"] = array();

    } else {

      /* Fallback if there's no image magick inside PHP */
      if (!function_exists("imagick_blob2image")){
        /* Get temporary file name for conversation */
        $fname = tempnam (TEMP_DIR, "GOsa");
  
        /* Open file and write out photoData */
        $fp = fopen ($fname, "w");
        fwrite ($fp, $this->photoData);
        fclose ($fp);

        /* Build conversation query. Filename is generated automatically, so
           we do not need any special security checks. Exec command and save
           output. For PHP safe mode, you'll need a configuration which respects
           image magick as executable... */
        $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
        @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
            $query, "Execute");
  
        /* Read data written by convert */
        $output= "";
        $sh= popen($query, 'r');
        while (!feof($sh)){
          $output.= fread($sh, 4096);
        }
        pclose($sh);

        unlink($fname);

        /* Save attribute */
        $this->attrs["jpegPhoto"] = $output;

      } else {

        /* Load the new uploaded Photo */
        if(!$handle  =  imagick_blob2image($this->photoData))  {
          new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
        }

        /* Resizing image to 147x200 and blur */
        if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
          new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
        }

        /* Converting image to JPEG */
        if(!imagick_convert($handle,"JPEG")) {
          new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
        }

        /* Creating binary Code for the Image */
        if(!$dump = imagick_image2blob($handle)){
          new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
        }

        /* Sending Image */
        $output=  $dump;

        /* Save attribute */
        $this->attrs["jpegPhoto"] = $output;
      }

    }

    /* This only gets called when user is renaming himself */
    $ldap= $this->config->get_ldap_link();
    if ($this->dn != $this->new_dn){

      /* Write entry on new 'dn' */
      $this->update_acls($this->dn,$this->new_dn);
      $this->move($this->dn, $this->new_dn);

      /* Happen to use the new one */
      change_ui_dn($this->dn, $this->new_dn);
      $this->dn= $this->new_dn;
    }


    /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
       new entries. So do a check first... */
    $ldap->cat ($this->dn, array('dn'));
    if ($ldap->fetch()){
      $mode= "modify";
    } else {
      $mode= "add";
      $ldap->cd($this->config->current['BASE']);
      $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
    }

    /* Set password to some junk stuff in case of templates */
    if ($this->is_template){
      $temp= passwordMethod::get_available_methods();
      foreach($temp as $id => $data){
        if(isset($data['name']) && $data['name'] == $this->pw_storage){
          $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
          $tmp->set_hash($this->pw_storage);
          $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
          break;
        }
      }
    }

    @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
        $this->attributes, "Save via $mode");

    /* Finally write data with selected 'mode' */
    $this->cleanup();

    /* Update current locale settings, if we have edited ourselves */
    $ui = session::get('ui');
    if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
      $ui->language = $this->preferredLanguage;
      session::set('ui',$ui);
      session::set('Last_init_lang',"update");
    }

    $ldap->cd ($this->dn);
    $ldap->$mode ($this->attrs);
    if (!$ldap->success()){
      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
      return (1);
    }

    /* Remove ACL dependencies too */
    if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
      $tmp = new acl($this->config,$this->parent,$this->dn);
      $tmp->update_acl_membership($this->orig_dn,$this->dn);
    }

    if($mode == "modify"){
      new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
    }else{
      new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
    }

    /* Remove cert? 
       For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
       to work around myself. */
    if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){

      /* Reset array, assemble new, this should be reworked */
      $this->attrs= array();
      $this->attrs['userCertificate;binary']= array();

      /* Prepare connection */
      if (!($ds = ldap_connect($this->config->current['SERVER']))) {
        die ("Could not connect to LDAP server");
      }
      ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
      if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
        ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ds, array(&$this, "rebind"));
      }
      if($this->config->get_cfg_value("ldapTLS") == "true"){
        ldap_start_tls($ds);
      }
      if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
              $this->config->current['PASSWORD']))) {
        die ("Could not bind to LDAP");
      }

      /* Modify using attrs */
      ldap_mod_del($ds,$this->dn,$this->attrs);
      ldap_close($ds);
    }

    /* If needed, let the password method do some cleanup */
    if ($this->pw_storage != $this->last_pw_storage){
      $tmp = new passwordMethod($this->config);
      $available = $tmp->get_available_methods();
      if (in_array_ics($this->last_pw_storage, $available['name'])){
        $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
        $test->attrs= $this->attrs;
        $test->remove_from_parent();
      }
    }

    /* Maybe the current password method want's to do some changes... */
    if (is_object($this->pwObject)){
      $this->pwObject->save($this->dn);
    }

    /* Optionally execute a command after we're done */
    if ($mode == "add"){
      $this->handle_post_events("add", array("uid" => $this->uid));
    } elseif ($this->is_modified){
      $this->handle_post_events("modify", array("uid" => $this->uid));
    }

    return (0);
  }

  
  function update_new_dn()
  {
    $pt= "";
    if($this->config->get_cfg_value("personalTitleInDN") == "true"){
      if(!empty($this->personalTitle)){
        $pt = $this->personalTitle." ";
      }
    }
    $this->cn= $pt.$this->givenName." ".$this->sn;

    /* Permissions for that base? */
    if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
      $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
    } else {
      /* Don't touch dn, if cn hasn't changed */
      if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
          $this->orig_base == $this->base ){
        $this->new_dn= $this->dn;
      } else {
        $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
      }
    }
  }
  

  /* Check formular input */
  function check()
  {
    /* Call common method to give check the hook */
    $message= plugin::check();

    /* Configurable password methods should be configured initially. 
     */ 
    if($this->last_pw_storage != $this->pw_storage){
      $temp= passwordMethod::get_available_methods();
      foreach($temp['name'] as $id => $name){
        if($name == $this->pw_storage){
          if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
            $message[] = _("The selected password method requires initial configuration!");
          }
          break;
        }
      }
    }

    $this->update_new_dn();

    /* Set the new acl base */
    if($this->dn == "new") {
      $this->set_acl_base($this->base);
    }

    /* Check if we are allowed to create/move this user 
     */
    
    if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
      $message[]= msgPool::permCreate();
    }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
      $message[]= msgPool::permMove();
    }

    /* UID already used? */
    $ldap= $this->config->get_ldap_link();
    $ldap->cd($this->config->current['BASE']);
    $ldap->search("(uid=$this->uid)", array("uid"));
    $ldap->fetch();
    if ($ldap->count() != 0 && $this->dn == 'new'){
      $message[]= msgPool::duplicated(_("Login"));
    }

    /* In template mode, the uid and givenName are autogenerated... */
    if ($this->sn == ""){
      $message[]= msgPool::required(_("Name"));
    }

    if (!$this->is_template){
      if ($this->givenName == ""){
        $message[]= msgPool::required(_("Given name"));
      }
      if ($this->uid == ""){
        $message[]= msgPool::required(_("Login"));
      }
      if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
        $ldap->cat($this->new_dn);
        if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
          $message[]= msgPool::duplicated(_("Name"));
        }
      }
    }

    /* Check for valid input */
    if ($this->is_modified && !tests::is_uid($this->uid)){

      if (strict_uid_mode()){
        $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
      } else {
        $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
      }
    }
    if (!tests::is_url($this->labeledURI)){
      $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
    }

    /* Check phone numbers */
    if (!tests::is_phone_nr($this->telephoneNumber)){
      $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
    }
    if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
      $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
    }
    if (!tests::is_phone_nr($this->mobile)){
      $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
    }
    if (!tests::is_phone_nr($this->pager)){
      $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
    }

    /* Check for reserved characers */
    if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
      $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
    }
    if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
      $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
    }

    return $message;
  }


  /* Indicate whether a password change is needed or not */
  function password_change_needed()
  {
    if(in_array("pw_storage",$this->multi_boxes)){
      return(TRUE);
    }
    return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
  }


  /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
  function load_picture()
  {
    $ldap = $this->config->get_ldap_link();
    $ldap->cd ($this->dn);
    $data = $ldap->get_attribute($this->dn,"jpegPhoto");

    if((!$data) || ($data == "*removed*")){ 

      /* In case we don't get an entry, load a default picture */
      $this->set_picture ();
      $this->jpegPhoto= "*removed*";
    }else{

      /* Set picture */
      $this->photoData= $data;
      session::set('binary',$this->photoData);
      session::set('binarytype',"image/jpeg");
      $this->jpegPhoto= "";
    }
  }


  /* Load a certificate from LDAP, this is going to be simplified later on */
  function load_cert()
  {
    $ds= ldap_connect($this->config->current['SERVER']);
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
      ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
      ldap_set_rebind_proc($ds, array(&$this, "rebind"));
    }
    if ($this->config->get_cfg_value("ldapTLS") == "true"){
      ldap_start_tls($ds);
    }

    $r= ldap_bind($ds);
    $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));

    if ($sr) {
      $ei= @ldap_first_entry($ds, $sr);
      
      if ($ei) {
        if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
          $this->userCertificate= "";
        } else {
          $this->userCertificate= $info[0];
        }
      }
    } else {
      $this->userCertificate= "";
    }

    ldap_unbind($ds);
  }


  /* Load picture from file to object */
  function set_picture($filename ="")
  {
    if (!is_file($filename) || $filename =="" ){
      $filename= "./plugins/users/images/default.jpg";
      $this->jpegPhoto= "*removed*";
    }

    $fd = fopen ($filename, "rb");
    $this->photoData= fread ($fd, filesize ($filename));
    session::set('binary',$this->photoData);
    session::set('binarytype',"image/jpeg");
    $this->jpegPhoto= "";

    fclose ($fd);
  }


  /* Load certificate from file to object */
  function set_cert($cert, $filename)
  {
    if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
    $fd = fopen ($filename, "rb");
    if (filesize($filename)>0) {
      $this->$cert= fread ($fd, filesize ($filename));
      fclose ($fd);
      $this->is_modified= TRUE;
    } else {
      msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
    }
  }

  /* Adapt from given 'dn' */
  function adapt_from_template($dn, $skip= array())
  {
    plugin::adapt_from_template($dn, $skip);

    /* Get password method from template 
     */
    $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
    if(is_object($tmp)){
      if($tmp->is_configurable()){
        $tmp->adapt_from_template($dn);
        $this->pwObject = &$tmp;
      }
      $this->pw_storage= $tmp->get_hash();
    }

    /* Get base */
    $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);

    if($this->governmentmode){

      /* Walk through govattrs */
      foreach ($this->govattrs as $val){

        if (in_array($val, $skip)){
          continue;
        }

        if (isset($this->attrs["$val"][0])){

          /* If attribute is set, replace dynamic parts: 
             %sn, %givenName and %uid. Fill these in our local variables. */
          $value= $this->attrs["$val"][0];

          foreach (array("sn", "givenName", "uid") as $repl){
            if (preg_match("/%$repl/i", $value)){
              $value= preg_replace ("/%$repl/i",
                  $this->parent->$repl, $value);
            }
          }
          $this->$val= $value;
        }
      }
    }

    /* Get back uid/sn/givenName - only write if nothing's skipped */
    if ($this->parent !== NULL && count($skip) == 0){
      $this->uid= $this->parent->uid;
      $this->sn= $this->parent->sn;
      $this->givenName= $this->parent->givenName;
    }
  }

 
  /* This avoids that users move themselves out of their rights. 
   */
  function allowedBasesToMoveTo()
  {
    /* Get bases */
    $bases  = $this->get_allowed_bases();
    return($bases);
  } 


  function getCopyDialog()
  {
    $str = "";

    session::set('binary',$this->photoData); 
    session::set('binarytype',"image/jpeg");

    /* Get random number for pictures */
    srand((double)microtime()*1000000); 
    $rand = rand(0, 10000);

    $smarty = get_smarty();

    $smarty->assign("passwordTodo","clear");

    if(isset($_POST['passwordTodo'])){
      $smarty->assign("passwordTodo",$_POST['passwordTodo']);
    }

    $smarty->assign("sn",       $this->sn);
    $smarty->assign("givenName",$this->givenName);
    $smarty->assign("uid",      $this->uid);
    $smarty->assign("rand",     $rand);
    $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));


    $ret = array();
    $ret['string'] = $str;
    $ret['status'] = "";  
    return($ret);
  }

  function saveCopyDialog()
  {
    /* Set_acl_base */
    $this->set_acl_base($this->base);

    if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
      $this->set_picture($_FILES['picture_file']['tmp_name']);
    }

    /* Remove picture? */
    if (isset($_POST['picture_remove'])){
      $this->jpegPhoto= "*removed*";
      $this->set_picture ("./plugins/users/images/default.jpg");
      $this->is_modified= TRUE;
    }

    $attrs = array("uid","givenName","sn");
    foreach($attrs as $attr){
      if(isset($_POST[$attr])){
        $this->$attr = $_POST[$attr];
      }
    } 
  }


  function PrepareForCopyPaste($source)
  {
    plugin::PrepareForCopyPaste($source);

    /* Reset certificate information addepted from source user
       to avoid setting the same user certificate for the destination user. */
    $this->userPKCS12= "";
    $this->userSMIMECertificate= "";
    $this->userCertificate= "";
    $this->certificateSerialNumber= "";
    $this->old_certificateSerialNumber= "";
    $this->old_userPKCS12= "";
    $this->old_userSMIMECertificate= "";
    $this->old_userCertificate= "";
  }


  static function plInfo()
  {
  
    $govattrs= array(
        "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
        "houseIdentifier"                           =>  _("House identifier"), 
        "vocation"                                  =>  _("Vocation"),
        "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
        "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
        "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
        "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
        "functionalTitle"                           =>  _("Functional title"),
        "certificateSerialNumber"                   =>  _("Certificate serial number"),
        "publicVisible"                             =>  _("Public visible"),
        "street"                                    =>  _("Street"),
        "role"                                      =>  _("Role"),
        "postalCode"                                =>  _("Postal code"));

    $ret = array(
        "plShortName" => _("Generic"),
        "plDescription" => _("Generic user settings"),
        "plSelfModify"  => TRUE,
        "plDepends"     => array(),
        "plPriority"    => 1,
        "plSection"     => array("personal" => _("My account")),
        "plCategory"    => array("users" => array("description" => _("Users"),
                                                  "objectClass" => "gosaAccount")),

        "plProvidedAcls" => array(

          "sn"                => _("Surname"),
          "givenName"         => _("Given name"),
          "uid"               => _("User identification"),
          "personalTitle"     => _("Personal title"),
          "academicTitle"     => _("Academic title"),

          "dateOfBirth"       => _("Date of birth"),
          "gender"            => _("Gender"),
          "preferredLanguage" => _("Preferred language"),
          "base"              => _("Base"), 

          "userPicture"       => _("User picture"),

          "o"                 => _("Organization"),
          "ou"                => _("Department"),
          "departmentNumber"  => _("Department number"),
          "employeeNumber"    => _("Employee number"),
          "employeeType"      => _("Employee type"),

          "roomNumber"        => _("Room number"),
          "telephoneNumber"   => _("Telefon number"),
          "pager"             => _("Pager number"),
          "mobile"            => _("Mobile number"),
          "facsimileTelephoneNumber"     => _("Fax number"),

          "st"                => _("State"),
          "l"                 => _("Location"),
          "postalAddress"     => _("Postal address"),

          "homePostalAddress" => _("Home postal address"),
          "homePhone"         => _("Home phone number"),
          "labeledURI"        => _("Homepage"),
          "userPassword"      => _("User password method"), 
          "Certificate"       => _("User certificates"))

        );

    /* Append government attributes if required */
    global $config;
    if($config->get_cfg_value("honourIvbbAttributes") == "true"){
      foreach($govattrs as $attr => $desc){
        $ret["plProvidedAcls"][$attr] = $desc;
      }
    }
    return($ret);
  }

  function get_multi_edit_values()
  {
    $ret = plugin::get_multi_edit_values();
    if(in_array("pw_storage",$this->multi_boxes)){
      $ret['pw_storage'] = $this->pw_storage;
    }
    if(in_array("edit_picture",$this->multi_boxes)){
      $ret['jpegPhoto'] = $this->jpegPhoto;
      $ret['photoData'] = $this->photoData;
      $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
      $ret['old_photoData'] = $this->old_photoData;
    }
    if(isset($ret['dateOfBirth'])){
      unset($ret['dateOfBirth']);
    }
    if(isset($ret['cn'])){
      unset($ret['cn']);
    }
    $ret['is_modified'] = $this->is_modified;
    if(in_array("base",$this->multi_boxes)){
      $ret['orig_base']="Changed_by_Multi_Plug";
      $ret['base']=$this->base;
    }
    return($ret); 
  }


  function multiple_save_object()
  {
    plugin::multiple_save_object();

    /* Get pw_storage mode */
    if (isset($_POST['pw_storage'])){
      foreach(array("pw_storage") as $val){
        if(isset($_POST[$val])){
          $data= validate(get_post($val));
          if ($data != $this->$val){
            $this->is_modified= TRUE;
          }
          $this->$val= $data;
        }
      }
    }
    if(isset($_POST['base'])){
      $this->base = get_post('base');
    }

    if(isset($_POST['user_mulitple_edit'])){
      foreach(array("base","pw_storage","edit_picture") as $val){
        if(isset($_POST["use_".$val])){
          $this->multi_boxes[] = $val;
        }
      }
    }
  }

  
  function multiple_check()
  {
    /* Call check() to set new_dn correctly ... */
    $message = plugin::multiple_check();

    /* Set the new acl base */
    if($this->dn == "new") {
      $this->set_acl_base($this->base);
    }
    if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Homepage"));
    }
    if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
    }
    if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
    }
    if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
    }
    if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
    }
    if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
    }
    if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
      $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
    }
    return($message);
  }



  function multiple_execute()
  {
    return($this->execute());
  }


}

// vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
?>
