Code

Updated user plugin to release manager assignment
[gosa.git] / gosa-core / plugins / personal / generic / class_user.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*!
24   \brief   user plugin
25   \author  Cajus Pollmeier <pollmeier@gonicus.de>
26   \version 2.00
27   \date    24.07.2003
29   This class provides the functionality to read and write all attributes
30   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
31   from/to the LDAP. It does syntax checking and displays the formulars required.
32  */
34 class user extends plugin
35 {
36   /* Definitions */
37   var $plHeadline= "Generic";
38   var $plDescription= "Edit organizational user settings";
40   /* Plugin specific values */
41   var $base= "";
42   var $orig_base= "";
43   var $cn= "";
44   var $new_dn= "";
45   var $personalTitle= "";
46   var $academicTitle= "";
47   var $homePostalAddress= "";
48   var $homePhone= "";
49   var $labeledURI= "";
50   var $o= "";
51   var $ou= "";
52   var $departmentNumber= "";
53   var $gosaLoginRestriction= array();
54   var $gosaLoginRestrictionWidget;
55   var $employeeNumber= "";
56   var $employeeType= "";
57   var $roomNumber= "";
58   var $telephoneNumber= "";
59   var $facsimileTelephoneNumber= "";
60   var $mobile= "";
61   var $pager= "";
62   var $l= "";
63   var $st= "";
64   var $postalAddress= "";
65   var $dateOfBirth;
66   var $use_dob= "0";
67   var $gender="0";
68   var $preferredLanguage="0";
69   var $baseSelector;
71   var $jpegPhoto= "*removed*";
72   var $photoData= "";
73   var $old_jpegPhoto= "";
74   var $old_photoData= "";
75   var $cert_dialog= FALSE;
76   var $picture_dialog= FALSE;
77   var $pwObject= NULL;
79   var $userPKCS12= "";
80   var $userSMIMECertificate= "";
81   var $userCertificate= "";
82   var $certificateSerialNumber= "";
83   var $old_certificateSerialNumber= "";
84   var $old_userPKCS12= "";
85   var $old_userSMIMECertificate= "";
86   var $old_userCertificate= "";
88   var $gouvernmentOrganizationalUnit= "";
89   var $houseIdentifier= "";
90   var $street= "";
91   var $postalCode= "";
92   var $vocation= "";
93   var $ivbbLastDeliveryCollective= "";
94   var $gouvernmentOrganizationalPersonLocality= "";
95   var $gouvernmentOrganizationalUnitDescription= "";
96   var $gouvernmentOrganizationalUnitSubjectArea= "";
97   var $functionalTitle= "";
98   var $role= "";
99   var $publicVisible= "";
101   var $orig_dn;
102   var $dialog;
104   /* variables to trigger password changes */
105   var $pw_storage= "md5";
106   var $last_pw_storage= "unset";
107   var $had_userCertificate= FALSE;
109   var $view_logged = FALSE;
111   var $manager = "";
112   var $manager_name = "";
115   /* attribute list for save action */
116   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
117       "homePostalAddress", "homePhone", "labeledURI", "ou", "o", "dateOfBirth", "gender","preferredLanguage",
118       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
119       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
120       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate", "gosaLoginRestriction", "manager");
122   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
123       "gosaAccount");
125   /* attributes that are part of the government mode */
126   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
127       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
128       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
129       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
130       "postalCode");
132   var $multiple_support = TRUE;
134   var $governmentmode = FALSE;
136   /* constructor, if 'dn' is set, the node loads the given
137      'dn' from LDAP */
138   function user (&$config, $dn= NULL)
139   {
140     global $lang;
142     $this->config= $config;
143     /* Configuration is fine, allways */
144     if($this->config->get_cfg_value("honourIvbbAttributes") == "true"){
145       $this->governmentmode = TRUE;
146       $this->attributes=array_merge($this->attributes,$this->govattrs);
147     }
149     /* Load base attributes */
150     plugin::plugin ($config, $dn);
152     $this->orig_dn  = $this->dn;
153     $this->new_dn   = $dn;
155     if ($this->governmentmode){
156       /* Fix public visible attribute if unset */
157       if (!isset($this->attrs['publicVisible'])){
158         $this->publicVisible == "nein";
159       }
160     }
162     /* Load government mode attributes */
163     if ($this->governmentmode){
164       /* Copy all attributs */
165       foreach ($this->govattrs as $val){
166         if (isset($this->attrs["$val"][0])){
167           $this->$val= $this->attrs["$val"][0];
168         }
169       }
170     }
172     /* Create me for new accounts */
173     if ($dn == "new"){
174       $this->is_account= TRUE;
175     }
177     /* Make hash default to md5 if not set in config */
178     $hash= $this->config->get_cfg_value("passwordDefaultHash", "crypt/md5");
180     /* Load data from LDAP? */
181     if ($dn !== NULL){
183       /* Do base conversation */
184       if ($this->dn == "new"){
185         $ui= get_userinfo();
186         $this->base= dn2base(session::global_is_set("CurrentMainBase")?"cn=dummy,".session::global_get("CurrentMainBase"):$ui->dn);
187       } else {
188         $this->base= dn2base($dn);
189       }
191       /* get password storage type */
192       if (isset ($this->attrs['userPassword'][0])){
193         /* Initialize local array */
194         $matches= array();
195         if (preg_match ("/^{[^}]+}/", $this->attrs['userPassword'][0])){
196           $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
197           if(is_object($tmp)){
198             $this->pw_storage= $tmp->get_hash(); 
199           }
201         } else {
202           if ($this->attrs['userPassword'][0] != ""){
203             $this->pw_storage= "clear";
204           } else {
205             $this->pw_storage= $hash;
206           }
207         }
208       } else {
209         /* Preset with vaule from configuration */
210         $this->pw_storage= $hash;
211       }
213       /* Load extra attributes: certificate and picture */
214       $this->load_cert();
215       $this->load_picture();
216       if ($this->userCertificate != ""){
217         $this->had_userCertificate= TRUE;
218       }
219     }
221     /* Reset password storage indicator, used by password_change_needed() */
222     if ($dn == "new"){
223       $this->last_pw_storage= "unset";
224     } else {
225       $this->last_pw_storage= $this->pw_storage;
226     }
228     /* Generate dateOfBirth entry */
229     if (isset ($this->attrs['dateOfBirth'])){
230       /* This entry is ISO 8601 conform */
231       list($year, $month, $day)= explode("-", $this->attrs['dateOfBirth'][0], 3);
232     
233       #TODO: use $lang to convert date
234       $this->dateOfBirth= "$day.$month.$year";
235     } else {
236       $this->dateOfBirth= "";
237     }
239     /* Put gender attribute to upper case */
240     if (isset ($this->attrs['gender'])){
241       $this->gender= strtoupper($this->attrs['gender'][0]);
242     }
244     // Get login restrictions
245     if(isset($this->attrs['gosaLoginRestriction'])){
246       $this->gosaLoginRestriction  =array();
247       for($i =0;$i < $this->attrs['gosaLoginRestriction']['count']; $i++){
248         $this->gosaLoginRestriction[] = $this->attrs['gosaLoginRestriction'][$i];
249       }
250     }
251     $this->gosaLoginRestrictionWidget= new sortableListing($this->gosaLoginRestriction);
252     $this->gosaLoginRestrictionWidget->setDeleteable(true);
253     $this->gosaLoginRestrictionWidget->setColspecs(array('*'));
254     $this->gosaLoginRestrictionWidget->setWidth("100%");
255     $this->gosaLoginRestrictionWidget->setHeight("70px");
256  
257     $this->orig_base = $this->base;
258     $this->baseSelector= new baseSelector($this->allowedBasesToMoveTo(), $this->base);
259     $this->baseSelector->setSubmitButton(false);
260     $this->baseSelector->setHeight(300);
261     $this->baseSelector->update(true);
264     // Detect the managers name
265     $this->manager_name = "";
266     $ldap = $this->config->get_ldap_link();
267     if(!empty($this->manager)){
268       $ldap->cat($this->manager, array('cn'));
269       if($ldap->count()){
270         $attrs = $ldap->fetch();
271         $this->manager_name = $attrs['cn'][0];
272       }else{
273         $this->manager_name = "("._("Unknown")."!): ".$this->manager;
274       }
275     }
276   }
279   /* execute generates the html output for this node */
280   function execute()
281   {
282     /* Call parent execute */
283     plugin::execute();
285     /* Set list ACL */
286     $this->gosaLoginRestrictionWidget->setAcl($this->getacl('gosaLoginRestriction', (!is_object($this->parent) && !session::is_set('edit'))));
287     $this->gosaLoginRestrictionWidget->update();
289     /* Handle add/delete for restriction mode */
290     if (isset($_POST['add_res']) && isset($_POST['res'])) {
291       $val= validate($_POST['res']);
292       if (preg_match('/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/', $val) ||
293           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+)$/', $val) ||
294           preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $val)) {
295         $this->gosaLoginRestrictionWidget->addEntry($val);
296       } else {
297         msg_dialog::display(_("Error"), _("Please add a single IP address or a network/netmask combination!"), ERROR_DIALOG);
298       }
299     }
301     /* Log view */
302     if($this->is_account && !$this->view_logged){
303       $this->view_logged = TRUE;
304       new log("view","users/".get_class($this),$this->dn);
305     }
307     // Clear manager attribute if requested
308     if(preg_match("/ removeManager/i", " ".implode(array_keys($_POST),' ')." ")){
309       $this->manager = "";
310       $this->manager_name = "";
311     }
313     // Allow to select a new inetOrgPersion:manager 
314     if(preg_match("/ editManager/i", " ".implode(array_keys($_POST),' ')." ")){
315       $this->dialog = new singleUserSelect($this->config, get_userinfo());
316     }
317     if($this->dialog && count($this->dialog->detectPostActions())){
318       $users = $this->dialog->detectPostActions();
319       if(isset($users['targets']) && count($users['targets'])){
321         $headpage = $this->dialog->getHeadpage();
322         $dn = $users['targets'][0];
323         $attrs = $headpage->getEntry($dn);
324         $this->manager = $dn;
325         $this->manager_name = $attrs['cn'][0];
326         $this->dialog = NULL;
327       }
328     }
329     if(isset($_POST['add_users_cancel'])){
330       $this->dialog = NULL;
331     }
332     if($this->dialog) return($this->dialog->execute()); 
335     $smarty= get_smarty();
336     $smarty->assign("usePrototype", "true");
337     $smarty->assign("gosaLoginRestrictionWidget", $this->gosaLoginRestrictionWidget->render());
339     /* Assign sex */
340     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
341     $smarty->assign("gender_list", $sex);
342     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
343     $smarty->assign("preferredLanguage_list", $language);
345     /* Get random number for pictures */
346     srand((double)microtime()*1000000); 
347     $smarty->assign("rand", rand(0, 10000));
350     /* Do we represent a valid gosaAccount? */
351     if (!$this->is_account){
352       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
353         msgPool::noValidExtension("GOsa")."</b>";
354       return($str);
355     }
357     /* Password configure dialog handling */
358     if(is_object($this->pwObject) && $this->pwObject->display){
359       $output= $this->pwObject->configure();
360       if ($output != ""){
361         $this->dialog= TRUE;
362         return $output;
363       }
364       $this->dialog= false;
365     }
367     /* Dialog handling */
368     if(is_object($this->dialog)){
369       /* Must be called before save_object */
370       $this->dialog->save_object();
371    
372       if($this->dialog->isClosed()){
373         $this->dialog = false;
374       }elseif($this->dialog->isSelected()){
376         /* check if selected base is allowed to move to / create a new object */
377         $tmp = $this->get_allowed_bases();
378         if(isset($tmp[$this->dialog->isSelected()])){
379           $this->base = $this->dialog->isSelected();
380         }
381         $this->dialog= false;
382       }else{
383         return($this->dialog->execute());
384       }
385     }
387     /* Want password method editing? */
388     if ($this->acl_is_writeable("userPassword")){
389       if (isset($_POST['edit_pw_method'])){
390         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
391           $temp= passwordMethod::get_available_methods();
392           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
393         }
394         $this->pwObject->display = TRUE;
395         $this->dialog= TRUE;
396         return ($this->pwObject->configure());
397       }
398     }
400     /* Want picture edit dialog? */
401     if($this->acl_is_writeable("userPicture")) {
402       if (isset($_POST['edit_picture'])){
403         /* Save values for later recovery, in case some presses
404            the cancel button. */
405         $this->old_jpegPhoto= $this->jpegPhoto;
406         $this->old_photoData= $this->photoData;
407         $this->picture_dialog= TRUE;
408         $this->dialog= TRUE;
409       }
410     }
412     /* Remove picture? */
413     if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
414       if (isset($_POST['picture_remove'])){
415         $this->set_picture ();
416         $this->jpegPhoto= "*removed*";
417         $this->is_modified= TRUE;
418         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
419       }
420     }
422     /* Save picture */
423     if (isset($_POST['picture_edit_finish'])){
425       /* Check for clean upload */
426       if ($_FILES['picture_file']['name'] != ""){
427         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
428           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
429         }else{
430           /* Activate new picture */
431           $this->set_picture($_FILES['picture_file']['tmp_name']);
432         }
433       }
434       $this->picture_dialog= FALSE;
435       $this->dialog= FALSE;
436       $this->is_modified= TRUE;
437     }
440     /* Cancel picture */
441     if (isset($_POST['picture_edit_cancel'])){
443       /* Restore values */
444       $this->jpegPhoto= $this->old_jpegPhoto;
445       $this->photoData= $this->old_photoData;
447       /* Update picture */
448       session::set('binary',$this->photoData);
449       session::set('binarytype',"image/jpeg");
450       $this->picture_dialog= FALSE;
451       $this->dialog= FALSE;
452     }
454     /* Want certificate= */
455     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
457       /* Save original values for later reconstruction */
458       foreach (array("certificateSerialNumber", "userCertificate",
459             "userSMIMECertificate", "userPKCS12") as $val){
461         $oval= "old_$val";
462         $this->$oval= $this->$val;
463       }
465       $this->cert_dialog= TRUE;
466       $this->dialog= TRUE;
467     }
470     /* Cancel certificate dialog */
471     if (isset($_POST['cert_edit_cancel'])){
473       /* Restore original values in case of 'cancel' */
474       foreach (array("certificateSerialNumber", "userCertificate",
475             "userSMIMECertificate", "userPKCS12") as $val){
477         $oval= "old_$val";
478         $this->$val= $this->$oval;
479       }
480       $this->cert_dialog= FALSE;
481       $this->dialog= FALSE;
482     }
485     /* Remove certificate? */
486     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
487       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
488         if (isset($_POST["remove_$val"])){
490           /* Reset specified cert*/
491           $this->$val= "";
492           $this->is_modified= TRUE;
493         }
494       }
495     }
497     /* Upload new cert and close dialog? */     
498     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
500       $fail =false;
502       if (isset($_POST['cert_edit_finish'])){
504         /* for all certificates do */
505         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
506             as $val){
508           /* Check for clean upload */
509           if (array_key_exists($val."_file", $_FILES) &&
510               array_key_exists('name', $_FILES[$val."_file"]) &&
511               $_FILES[$val."_file"]['name'] != "" &&
512               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
513             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
514           }
515         }
517         /* Save serial number */
518         if (isset($_POST["certificateSerialNumber"]) &&
519             $_POST["certificateSerialNumber"] != ""){
521           if (!tests::is_id($_POST["certificateSerialNumber"])){
522             $fail = true;
523             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
525             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
526               if ($this->$cert != ""){
527                 $smarty->assign("$cert"."_state", "true");
528               } else {
529                 $smarty->assign("$cert"."_state", "");
530               }
531             }
532           }
534           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
535           $this->is_modified= TRUE;
536         }
537         if(!$fail){
538           $this->cert_dialog= FALSE;
539           $this->dialog= FALSE;
540         }
541       }
542     }
543     /* Display picture dialog */
544     if ($this->picture_dialog){
545       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
546     }
548     /* Display cert dialog */
549     if ($this->cert_dialog){
550       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
551       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
552       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
554       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
555         if ($this->$cert != ""){
556           /* import certificate */
557           $certificate = new certificate;
558           $certificate->import($this->$cert);
559       
560           /* Read out data*/
561           $timeto   = $certificate->getvalidto_date();
562           $timefrom = $certificate->getvalidfrom_date();
563          
564           
565           /* Additional info if start end time is '0' */
566           $add_str_info = "";
567           if($timeto == 0 && $timefrom == 0){
568             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
569           }
571           $str = "<table summary=\"\" border=0>
572                     <tr>
573                       <td style='vertical-align:top'>CN</td>
574                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
575                     </tr>
576                   </table><br>".
578                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
579                         "<b>".date('d M Y',$timefrom)."</b>",
580                         "<b>".date('d M Y',$timeto)."</b>",
581                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
582                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
584           $smarty->assign($cert."info",$str);
585           $smarty->assign($cert."_state","true");
586         } else {
587           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
588           $smarty->assign($cert."_state","");
589         }
590       }
591   
592       if($this->governmentmode){
593         $smarty->assign("honourIvbbAttributes", "true");
594       }else{
595         $smarty->assign("honourIvbbAttributes", "false");
596       }
597       $smarty->assign("governmentmode", $this->governmentmode);
598       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
599     }
601     /* Prepare password hashes */
602     if ($this->pw_storage == ""){
603       $this->pw_storage= $this->config->get_cfg_value("hash");
604     }
606     $temp= passwordMethod::get_available_methods();
607     $is_configurable= FALSE;
608     $hashes = $temp['name'];
609     if(isset($temp[$this->pw_storage])){
610       $test= new $temp[$this->pw_storage]($this->config);
611       $is_configurable= $test->is_configurable();
612     }else{
613       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
614     }
617     /* Create password methods array */
618     $pwd_methods = array();
619     foreach($hashes as $id => $name){
620       if(!empty($temp['desc'][$id])){
621         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
622       }else{
623         $pwd_methods[$name] = $name;
624       }
625     }
626  
627     /* Load attributes and acl's */
628     $ui =get_userinfo();
629     foreach($this->attributes as $val){
630       $smarty->assign("$val", $this->$val);
631       if(in_array($val,$this->multi_boxes)){
632         $smarty->assign("use_".$val,TRUE);
633       }else{
634         $smarty->assign("use_".$val,FALSE);
635       }
636     }
637     foreach(array("base","pw_storage","edit_picture") as $val){
638       if(in_array($val,$this->multi_boxes)){
639         $smarty->assign("use_".$val,TRUE);
640       }else{
641         $smarty->assign("use_".$val,FALSE);
642       }
643     }
645     /* Set acls */
646     $tmp = $this->plinfo();
647     foreach($tmp['plProvidedAcls'] as $val => $translation){
648       $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
649     }
651     // Special ACL for gosaLoginRestrictions - 
652     // In case of multiple edit, we need a readonly ACL for the list. 
653     $smarty->assign('gosaLoginRestriction_ONLY_R_ACL', 
654       preg_replace("/[^r]/i","", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit')))));
656     $smarty->assign("pwmode", $pwd_methods);
657     $smarty->assign("pwmode_select", $this->pw_storage);
658     $smarty->assign("pw_configurable", $is_configurable);
659     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
661     if(!session::is_set('edit')){
662       $smarty->assign("CertificatesACL","");
663     }else{
664       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
665     }
666     
667     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
668     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
670     /* Create base acls */
671     $smarty->assign("base", $this->baseSelector->render());
673     /* Save government mode attributes */
674     if($this->governmentmode){
675       $smarty->assign("governmentmode", "true");
676       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
677           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
678       $smarty->assign("ivbbmodes", $ivbbmodes);
679       foreach ($this->govattrs as $val){
680         $smarty->assign("$val", $this->$val);
681         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
682       }
683     } else {
684       $smarty->assign("governmentmode", "false");
685     }
687     /* Special mode for uid */
688     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
689     if (isset ($this->dn)){
690       if ($this->dn != "new"){
691         $uidACL= preg_replace("/w/","",$uidACL);
692       }
693     }  else {
694       $uidACL= preg_replace("/w/","",$uidACL);
695     }
696     
697     $smarty->assign("uidACL", $uidACL);
698     $smarty->assign("is_template", $this->is_template);
699     $smarty->assign("use_dob", $this->use_dob);
701     if (isset($this->parent)){
702       if (isset($this->parent->by_object['phoneAccount']) &&
703           $this->parent->by_object['phoneAccount']->is_account){
704         $smarty->assign("has_phoneaccount", "true");
705       } else {
706         $smarty->assign("has_phoneaccount", "false");
707       }
708     } else {
709       $smarty->assign("has_phoneaccount", "false");
710     }
711     $smarty->assign("multiple_support" , $this->multiple_support_active);
712     $smarty->assign("manager_name",$this->manager_name);
713     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
714   }
717   /* remove object from parent */
718   function remove_from_parent()
719   {
720     /* Only remove valid accounts */
721     if(!$this->initially_was_account) return;
723     /* Remove password extension */
724     $temp= passwordMethod::get_available_methods();
726     /* Remove password method from user account */
727     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
728       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
729       $this->pwObject->remove_from_parent();
730     }
732     /* Remove user */
733     $ldap= $this->config->get_ldap_link();
734     $ldap->rmdir ($this->dn);
735     if (!$ldap->success()){
736       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
737     }
738   
739     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
740   
741     /* Delete references to groups */
742     $ldap->cd ($this->config->current['BASE']);
743     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
744     while ($ldap->fetch()){
745       $g= new group($this->config, $ldap->getDN());
746       $g->removeUser($this->uid);
747       $g->save ();
748     }
750     /* Delete references to object groups */
751     $ldap->cd ($this->config->current['BASE']);
752     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
753     while ($ldap->fetch()){
754       $og= new ogroup($this->config, $ldap->getDN());
755       unset($og->member[$this->dn]);
756       $og->member= array_values($og->member);
757       $og->save ();
758     }
760     // Update 'manager' attributes from gosaDepartment and inetOrgPerson
761     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter($this->dn)."))";
762     $ocs = $ldap->get_objectclasses();
763     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
764       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter($this->dn).")))";
765     }
766     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'],
767         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
768     foreach($leaf_deps as $entry){
769       $update = array('manager' => array());
770       $ldap->cd($entry['dn']);
771       $ldap->modify($update);
772       if(!$ldap->success()){
773         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
774       }
775     }
777     /* Delete references to roles */
778     $ldap->cd ($this->config->current['BASE']);
779     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
780     while ($ldap->fetch()){
781       $role= new roleGeneric($this->config, $ldap->getDN());
782       $key = array_search($this->dn,$role->roleOccupant);
783       if($key !== FALSE){
784         unset($role->roleOccupant[$key]);
785         $role->roleOccupant= array_values($role->roleOccupant);
786         $role->save ();
787       }
788     }
790     /* If needed, let the password method do some cleanup */
791     $tmp = new passwordMethod($this->config);
792     $available = $tmp->get_available_methods();
793     if (in_array_ics($this->pw_storage, $available['name'])){
794       $test= new $available[$this->pw_storage]($this->config);
795       $test->attrs= $this->attrs;
796       $test->dn= $this->dn;
797       $test->remove_from_parent();
798     }
800     /* Remove ACL dependencies too */
801     acl::remove_acl_for($this->dn);
803     /* Optionally execute a command after we're done */
804     $this->handle_post_events("remove",array("uid" => $this->uid));
805   }
808   /* Save data to object */
809   function save_object()
810   {
811     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
813       /* Make a backup of the current selected base */
814       $base_tmp = $this->base;
816       /* Parents save function */
817       plugin::save_object ();
819       /* Refresh base */
820       if ($this->acl_is_moveable($this->base)){
821         if (!$this->baseSelector->update()) {
822           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
823         }
824         if ($this->base != $this->baseSelector->getBase()) {
825           $this->base= $this->baseSelector->getBase();
826           $this->is_modified= TRUE;
827         }
828       }
829       
830       /* Sync lists */
831       $this->gosaLoginRestrictionWidget->save_object();
832       if ($this->gosaLoginRestrictionWidget->isModified()) {
833         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
834       }
836       /* Save government mode attributes */
837       if ($this->governmentmode){
838         foreach ($this->govattrs as $val){
839           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
840             $data= stripcslashes($_POST["$val"]);
841             if ($data != $this->$val){
842               $this->is_modified= TRUE;
843             }
844             $this->$val= $data;
845           }
846         }
847       }
849       /* In template mode, the uid is autogenerated... */
850       if ($this->is_template){
851         $this->uid= strtolower($this->sn);
852         $this->givenName= $this->sn;
853       }
855       /* Get pw_storage mode */
856       if (isset($_POST['pw_storage'])){
857         foreach(array("pw_storage") as $val){
858           if(isset($_POST[$val])){
859             $data= validate($_POST[$val]);
860             if ($data != $this->$val){
861               $this->is_modified= TRUE;
862             }
863             $this->$val= $data;
864           }
865         }
866       }
868       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
869         if ($this->acl_is_writeable("userPassword")){
870           $temp= passwordMethod::get_available_methods();
871           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
872             foreach($temp as $id => $data){
873               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
874                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
875                 break;
876               }
877             }
878           }
879         }
880       }
882       /* Save current cn
883        */
884       $this->cn = $this->givenName." ".$this->sn;
885     }
886   }
888   function rebind($ldap, $referral)
889   {
890     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
891     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
892       $this->error = "Success";
893       $this->hascon=true;
894       $this->reconnect= true;
895       return (0);
896     } else {
897       $this->error = "Could not bind to " . $credentials['ADMIN'];
898       return NULL;
899     }
900   }
902   
903   /* Save data to LDAP, depending on is_account we save or delete */
904   function save()
905   {
906     global $lang;
908     /* Only force save of changes .... 
909        If this attributes aren't changed, avoid saving.
910      */
911   
912     if($this->gender=="0") $this->gender ="";
913     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
915     /* First use parents methods to do some basic fillup in $this->attrs */
916     plugin::save ();
918     if ($this->dateOfBirth != ""){
919       if(!is_array($this->attrs['dateOfBirth'])) {
920         #TODO: use $lang to convert date
921         list($day, $month, $year)= explode(".", $this->dateOfBirth);
922         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
923       }
924     }
926     /* Remove additional objectClasses */
927     $tmp= array();
928     foreach ($this->attrs['objectClass'] as $key => $set){
929       $found= false;
930       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
931         if (preg_match ("/^$set$/i", $val)){
932           $found= true;
933           break;
934         }
935       }
936       if (!$found){
937         $tmp[]= $set;
938       }
939     }
941     /* Replace the objectClass array. This is done because of the
942        separation into government and normal mode. */
943     $this->attrs['objectClass']= $tmp;
945     /* Add objectClasss for template mode? */
946     if ($this->is_template){
947       $this->attrs['objectClass'][]= "gosaUserTemplate";
948     }
950     /* Hard coded government mode? */
951     if ($this->governmentmode){
952       $this->attrs['objectClass'][]= "ivbbentry";
954       /* Copy standard attributes */
955       foreach ($this->govattrs as $val){
956         if ($this->$val != ""){
957           $this->attrs["$val"]= $this->$val;
958         } elseif (!$this->is_new) {
959           $this->attrs["$val"]= array();
960         }
961       }
963       /* Remove attribute if set to "nein" */
964       if ($this->publicVisible == "nein"){
965         $this->attrs['publicVisible']= array();
966         if($this->is_new){
967           unset($this->attrs['publicVisible']);
968         }else{
969           $this->attrs['publicVisible']=array();
970         }
972       }
974     }
976     /* Special handling for attribute userCertificate needed */
977     if ($this->userCertificate != ""){
978       $this->attrs["userCertificate;binary"]= $this->userCertificate;
979       $remove_userCertificate= false;
980     } else {
981       $remove_userCertificate= true;
982     }
984     /* Special handling for dateOfBirth value */
985     if ($this->dateOfBirth == ""){
986       if ($this->is_new) {
987         unset($this->attrs["dateOfBirth"]);
988       } else {
989         $this->attrs["dateOfBirth"]= array();
990       }
991     }
992     if (!$this->gender){
993       if ($this->is_new) {
994         unset($this->attrs["gender"]);
995       } else {
996         $this->attrs["gender"]= array();
997       }
998     }
999     if (!$this->preferredLanguage){
1000       if ($this->is_new) {
1001         unset($this->attrs["preferredLanguage"]);
1002       } else {
1003         $this->attrs["preferredLanguage"]= array();
1004       }
1005     }
1007     /* Special handling for attribute jpegPhote needed, scale image via
1008        image magick to 147x200 pixels and inject resulting data. */
1009     if ($this->jpegPhoto == "*removed*"){
1010     
1011       /* Reset attribute to avoid writing *removed* as value */    
1012       $this->attrs["jpegPhoto"] = array();
1014     } else {
1016       /* Fallback if there's no image magick inside PHP */
1017       if (!function_exists("imagick_blob2image")){
1018         /* Get temporary file name for conversation */
1019         $fname = tempnam (TEMP_DIR, "GOsa");
1020   
1021         /* Open file and write out photoData */
1022         $fp = fopen ($fname, "w");
1023         fwrite ($fp, $this->photoData);
1024         fclose ($fp);
1026         /* Build conversation query. Filename is generated automatically, so
1027            we do not need any special security checks. Exec command and save
1028            output. For PHP safe mode, you'll need a configuration which respects
1029            image magick as executable... */
1030         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1031         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1032             $query, "Execute");
1033   
1034         /* Read data written by convert */
1035         $output= "";
1036         $sh= popen($query, 'r');
1037         while (!feof($sh)){
1038           $output.= fread($sh, 4096);
1039         }
1040         pclose($sh);
1042         unlink($fname);
1044         /* Save attribute */
1045         $this->attrs["jpegPhoto"] = $output;
1047       } else {
1049         /* Load the new uploaded Photo */
1050         if(!$handle  =  imagick_blob2image($this->photoData))  {
1051           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
1052         }
1054         /* Resizing image to 147x200 and blur */
1055         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
1056           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
1057         }
1059         /* Converting image to JPEG */
1060         if(!imagick_convert($handle,"JPEG")) {
1061           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1062         }
1064         /* Creating binary Code for the Image */
1065         if(!$dump = imagick_image2blob($handle)){
1066           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1067         }
1069         /* Sending Image */
1070         $output=  $dump;
1072         /* Save attribute */
1073         $this->attrs["jpegPhoto"] = $output;
1074       }
1076     }
1078     /* This only gets called when user is renaming himself */
1079     $ldap= $this->config->get_ldap_link();
1080     if ($this->dn != $this->new_dn){
1082       /* Write entry on new 'dn' */
1083       $this->update_acls($this->dn,$this->new_dn);
1084       $this->move($this->dn, $this->new_dn);
1086       /* Happen to use the new one */
1087       change_ui_dn($this->dn, $this->new_dn);
1088       $this->dn= $this->new_dn;
1089     }
1092     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1093        new entries. So do a check first... */
1094     $ldap->cat ($this->dn, array('dn'));
1095     if ($ldap->fetch()){
1096       $mode= "modify";
1097     } else {
1098       $mode= "add";
1099       $ldap->cd($this->config->current['BASE']);
1100       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1101     }
1103     /* Set password to some junk stuff in case of templates */
1104     if ($this->is_template){
1105       $temp= passwordMethod::get_available_methods();
1106       foreach($temp as $id => $data){
1107         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1108           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1109           $tmp->set_hash($this->pw_storage);
1110           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1111           break;
1112         }
1113       }
1114     }
1116     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1117         $this->attributes, "Save via $mode");
1119     /* Finally write data with selected 'mode' */
1120     $this->cleanup();
1122     /* Update current locale settings, if we have edited ourselves */
1123     $ui = session::get('ui');
1124     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1125       $ui->language = $this->preferredLanguage;
1126       session::set('ui',$ui);
1127       session::set('Last_init_lang',"update");
1128     }
1130     $ldap->cd ($this->dn);
1131     $ldap->$mode ($this->attrs);
1132     if (!$ldap->success()){
1133       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1134       return (1);
1135     }
1137     /* Remove ACL dependencies too */
1138     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1139       $tmp = new acl($this->config,$this->parent,$this->dn);
1140       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1141     }
1143     if($mode == "modify"){
1144       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1145     }else{
1146       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1147     }
1149     /* Remove cert? 
1150        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1151        to work around myself. */
1152     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1154       /* Reset array, assemble new, this should be reworked */
1155       $this->attrs= array();
1156       $this->attrs['userCertificate;binary']= array();
1158       /* Prepare connection */
1159       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1160         die ("Could not connect to LDAP server");
1161       }
1162       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1163       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1164         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1165         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1166       }
1167       if($this->config->get_cfg_value("ldapTLS") == "true"){
1168         ldap_start_tls($ds);
1169       }
1170       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1171               $this->config->current['PASSWORD']))) {
1172         die ("Could not bind to LDAP");
1173       }
1175       /* Modify using attrs */
1176       ldap_mod_del($ds,$this->dn,$this->attrs);
1177       ldap_close($ds);
1178     }
1180     /* If needed, let the password method do some cleanup */
1181     if ($this->pw_storage != $this->last_pw_storage){
1182       $tmp = new passwordMethod($this->config);
1183       $available = $tmp->get_available_methods();
1184       if (in_array_ics($this->last_pw_storage, $available['name'])){
1185         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1186         $test->attrs= $this->attrs;
1187         $test->remove_from_parent();
1188       }
1189     }
1191     /* Maybe the current password method want's to do some changes... */
1192     if (is_object($this->pwObject)){
1193       $this->pwObject->save($this->dn);
1194     }
1196     /* Optionally execute a command after we're done */
1197     if ($mode == "add"){
1198       $this->handle_post_events("add", array("uid" => $this->uid));
1199     } elseif ($this->is_modified){
1200       $this->handle_post_events("modify", array("uid" => $this->uid));
1201     }
1203     return (0);
1204   }
1207   function create_initial_rdn($pattern)
1208   {
1209     // Only generate single RDNs
1210     if (preg_match('/\+/', $pattern)){
1211       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1212       return "";
1213     }
1215     // Extract attribute
1216     $attribute= preg_replace('/=.*$/', '', $pattern);
1217     if (!in_array_ics($attribute, $this->attributes)) {
1218       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1219       return "";
1220     }
1222     // Sort attributes for length
1223     $attrl= array();
1224     foreach ($this->attributes as $attr) {
1225       $attrl[$attr]= strlen($attr);
1226     }
1227     arsort($attrl);
1228     
1229     // Walk thru sorted attributes and replace them in pattern
1230     foreach ($attrl as $attr => $dummy) {
1231       if (!is_array($this->$attr)){
1232         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1233       } else {
1234         // Array elements cannot be used for ID generation
1235         if (preg_match("/%$attr/", $pattern)) {
1236           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1237           break;
1238         }
1239       }
1240     }
1242     // Internally assign value
1243     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1245     return $pattern;
1246   }
1248   
1249   function update_new_dn()
1250   {
1251     // Alternative way to handle DN
1252     $pattern= $this->config->get_cfg_value("accountRDN");
1253     if ($pattern != "") {
1254       $rdn= $this->create_initial_rdn($pattern);
1255       $attribute= preg_replace('/=.*$/', '', $rdn);
1256       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1258       /* Don't touch dn, if $attribute hasn't changed */
1259       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1260             $this->orig_base == $this->base ){
1261         $this->new_dn= $this->dn;
1262       } else {
1263         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1264       }
1266     // Original way to handle DN
1267     } else {
1269       $pt= "";
1270       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1271         if(!empty($this->personalTitle)){
1272           $pt = $this->personalTitle." ";
1273         }
1274       }
1276       $this->cn= $pt.$this->givenName." ".$this->sn;
1278       /* Permissions for that base? */
1279       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1280         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1281       } else {
1282         /* Don't touch dn, if cn hasn't changed */
1283         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1284             $this->orig_base == $this->base ){
1285           $this->new_dn= $this->dn;
1286         } else {
1287           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1288         }
1289       }
1290     }
1291   }
1292   
1294   /* Check formular input */
1295   function check()
1296   {
1297     /* Call common method to give check the hook */
1298     $message= plugin::check();
1300     /* Configurable password methods should be configured initially. 
1301      */ 
1302     if($this->last_pw_storage != $this->pw_storage){
1303       $temp= passwordMethod::get_available_methods();
1304       foreach($temp['name'] as $id => $name){
1305         if($name == $this->pw_storage){
1306           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1307             $message[] = _("The selected password method requires initial configuration!");
1308           }
1309           break;
1310         }
1311       }
1312     }
1314     $this->update_new_dn();
1316     /* Set the new acl base */
1317     if($this->dn == "new") {
1318       $this->set_acl_base($this->base);
1319     }
1321     /* Check if we are allowed to create/move this user */
1322     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1323       $message[]= msgPool::permCreate();
1324     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1325       $message[]= msgPool::permMove();
1326     }
1328     /* UID already used? */
1329     $ldap= $this->config->get_ldap_link();
1330     $ldap->cd($this->config->current['BASE']);
1331     $ldap->search("(uid=$this->uid)", array("uid"));
1332     $ldap->fetch();
1333     if ($ldap->count() != 0 && $this->dn == 'new'){
1334       $message[]= msgPool::duplicated(_("Login"));
1335     }
1337     /* In template mode, the uid and givenName are autogenerated... */
1338     if ($this->sn == ""){
1339       $message[]= msgPool::required(_("Name"));
1340     }
1342     // Check if a wrong base was supplied
1343     if(!$this->baseSelector->checkLastBaseUpdate()){
1344       $message[]= msgPool::check_base();;
1345     }
1347     if (!$this->is_template){
1348       if ($this->givenName == ""){
1349         $message[]= msgPool::required(_("Given name"));
1350       }
1351       if ($this->uid == ""){
1352         $message[]= msgPool::required(_("Login"));
1353       }
1354       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1355         $ldap->cat($this->new_dn);
1356         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1357           $message[]= msgPool::duplicated(_("Name"));
1358         }
1359       }
1360     }
1362     /* Check for valid input */
1363     if ($this->is_modified && !tests::is_uid($this->uid)){
1365       if (strict_uid_mode()){
1366         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1367       } else {
1368         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1369       }
1370     }
1371     if (!tests::is_url($this->labeledURI)){
1372       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1373     }
1375     /* Check phone numbers */
1376     if (!tests::is_phone_nr($this->telephoneNumber)){
1377       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1378     }
1379     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1380       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1381     }
1382     if (!tests::is_phone_nr($this->mobile)){
1383       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1384     }
1385     if (!tests::is_phone_nr($this->pager)){
1386       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1387     }
1389     /* Check dates */
1390     if (!tests::is_date($this->dateOfBirth)){
1391       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1392     }
1394     /* Check for reserved characers */
1395     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1396       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1397     }
1398     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1399       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1400     }
1402     return $message;
1403   }
1406   /* Indicate whether a password change is needed or not */
1407   function password_change_needed()
1408   {
1409     if($this->multiple_support_active){
1410       return(FALSE);
1411     }else{
1413       if(in_array("pw_storage",$this->multi_boxes)){
1414         return(TRUE);
1415       }
1416       return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1417     }
1418   }
1421   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1422   function load_picture()
1423   {
1424     $ldap = $this->config->get_ldap_link();
1425     $ldap->cd ($this->dn);
1426     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1428     if((!$data) || ($data == "*removed*")){ 
1430       /* In case we don't get an entry, load a default picture */
1431       $this->set_picture ();
1432       $this->jpegPhoto= "*removed*";
1433     }else{
1435       /* Set picture */
1436       $this->photoData= $data;
1437       session::set('binary',$this->photoData);
1438       session::set('binarytype',"image/jpeg");
1439       $this->jpegPhoto= "";
1440     }
1441   }
1444   /* Load a certificate from LDAP, this is going to be simplified later on */
1445   function load_cert()
1446   {
1447     $ds= ldap_connect($this->config->current['SERVER']);
1448     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1449     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1450       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1451       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1452     }
1453     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1454       ldap_start_tls($ds);
1455     }
1457     $r= ldap_bind($ds);
1458     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1460     if ($sr) {
1461       $ei= @ldap_first_entry($ds, $sr);
1462       
1463       if ($ei) {
1464         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1465           $this->userCertificate= "";
1466         } else {
1467           $this->userCertificate= $info[0];
1468         }
1469       }
1470     } else {
1471       $this->userCertificate= "";
1472     }
1474     ldap_unbind($ds);
1475   }
1478   /* Load picture from file to object */
1479   function set_picture($filename ="")
1480   {
1481     if (!is_file($filename) || $filename =="" ){
1482       $filename= "./plugins/users/images/default.jpg";
1483       $this->jpegPhoto= "*removed*";
1484     }
1486     $fd = fopen ($filename, "rb");
1487     $this->photoData= fread ($fd, filesize ($filename));
1488     session::set('binary',$this->photoData);
1489     session::set('binarytype',"image/jpeg");
1490     $this->jpegPhoto= "";
1492     fclose ($fd);
1493   }
1496   /* Load certificate from file to object */
1497   function set_cert($cert, $filename)
1498   {
1499     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1500     $fd = fopen ($filename, "rb");
1501     if (filesize($filename)>0) {
1502       $this->$cert= fread ($fd, filesize ($filename));
1503       fclose ($fd);
1504       $this->is_modified= TRUE;
1505     } else {
1506       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1507     }
1508   }
1510   /* Adapt from given 'dn' */
1511   function adapt_from_template($dn, $skip= array())
1512   {
1513     plugin::adapt_from_template($dn, $skip);
1515     /* Get password method from template 
1516      */
1517     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1518     if(is_object($tmp)){
1519       if($tmp->is_configurable()){
1520         $tmp->adapt_from_template($dn);
1521         $this->pwObject = &$tmp;
1522       }
1523       $this->pw_storage= $tmp->get_hash();
1524     }
1526     /* Get base */
1527     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1529     if($this->governmentmode){
1531       /* Walk through govattrs */
1532       foreach ($this->govattrs as $val){
1534         if (in_array($val, $skip)){
1535           continue;
1536         }
1538         if (isset($this->attrs["$val"][0])){
1540           /* If attribute is set, replace dynamic parts: 
1541              %sn, %givenName and %uid. Fill these in our local variables. */
1542           $value= $this->attrs["$val"][0];
1544           foreach (array("sn", "givenName", "uid") as $repl){
1545             if (preg_match("/%$repl/i", $value)){
1546               $value= preg_replace ("/%$repl/i",
1547                   $this->parent->$repl, $value);
1548             }
1549           }
1550           $this->$val= $value;
1551         }
1552       }
1553     }
1555     /* Get back uid/sn/givenName - only write if nothing's skipped */
1556     if ($this->parent !== NULL && count($skip) == 0){
1557       $this->uid= $this->parent->uid;
1558       $this->sn= $this->parent->sn;
1559       $this->givenName= $this->parent->givenName;
1560     }
1562     if ($this->dateOfBirth) {
1563       /* This entry is ISO 8601 conform */
1564       list($year, $month, $day)= explode("-", $this->dateOfBirth, 3);
1565     
1566       #TODO: use $lang to convert date
1567       $this->dateOfBirth= "$day.$month.$year";
1568     }
1569   }
1571  
1572   /* This avoids that users move themselves out of their rights. 
1573    */
1574   function allowedBasesToMoveTo()
1575   {
1576     /* Get bases */
1577     $bases  = $this->get_allowed_bases();
1578     return($bases);
1579   } 
1582   function getCopyDialog()
1583   {
1584     $str = "";
1586     session::set('binary',$this->photoData); 
1587     session::set('binarytype',"image/jpeg");
1589     /* Get random number for pictures */
1590     srand((double)microtime()*1000000); 
1591     $rand = rand(0, 10000);
1593     $smarty = get_smarty();
1595     $smarty->assign("passwordTodo","clear");
1597     if(isset($_POST['passwordTodo'])){
1598       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1599     }
1601     $smarty->assign("sn",       $this->sn);
1602     $smarty->assign("givenName",$this->givenName);
1603     $smarty->assign("uid",      $this->uid);
1604     $smarty->assign("rand",     $rand);
1605     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1608     $ret = array();
1609     $ret['string'] = $str;
1610     $ret['status'] = "";  
1611     return($ret);
1612   }
1614   function saveCopyDialog()
1615   {
1616     /* Set_acl_base */
1617     $this->set_acl_base($this->base);
1619     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1620       $this->set_picture($_FILES['picture_file']['tmp_name']);
1621     }
1623     /* Remove picture? */
1624     if (isset($_POST['picture_remove'])){
1625       $this->jpegPhoto= "*removed*";
1626       $this->set_picture ("./plugins/users/images/default.jpg");
1627       $this->is_modified= TRUE;
1628     }
1630     $attrs = array("uid","givenName","sn");
1631     foreach($attrs as $attr){
1632       if(isset($_POST[$attr])){
1633         $this->$attr = $_POST[$attr];
1634       }
1635     } 
1636   }
1639   function PrepareForCopyPaste($source)
1640   {
1641     plugin::PrepareForCopyPaste($source);
1643     /* Reset certificate information addepted from source user
1644        to avoid setting the same user certificate for the destination user. */
1645     $this->userPKCS12= "";
1646     $this->userSMIMECertificate= "";
1647     $this->userCertificate= "";
1648     $this->certificateSerialNumber= "";
1649     $this->old_certificateSerialNumber= "";
1650     $this->old_userPKCS12= "";
1651     $this->old_userSMIMECertificate= "";
1652     $this->old_userCertificate= "";
1653   }
1656   static function plInfo()
1657   {
1658   
1659     $govattrs= array(
1660         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1661         "houseIdentifier"                           =>  _("House identifier"), 
1662         "vocation"                                  =>  _("Vocation"),
1663         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1664         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1665         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1666         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1667         "functionalTitle"                           =>  _("Functional title"),
1668         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1669         "publicVisible"                             =>  _("Public visible"),
1670         "street"                                    =>  _("Street"),
1671         "role"                                      =>  _("Role"),
1672         "postalCode"                                =>  _("Postal code"));
1674     $ret = array(
1675         "plShortName" => _("Generic"),
1676         "plDescription" => _("Generic user settings"),
1677         "plSelfModify"  => TRUE,
1678         "plDepends"     => array(),
1679         "plPriority"    => 1,
1680         "plSection"     => array("personal" => _("My account")),
1681         "plCategory"    => array("users" => array("description" => _("Users"),
1682                                                   "objectClass" => "gosaAccount")),
1684         "plProvidedAcls" => array(
1686           "sn"                => _("Surname"),
1687           "givenName"         => _("Given name"),
1688           "uid"               => _("User identification"),
1689           "personalTitle"     => _("Personal title"),
1690           "academicTitle"     => _("Academic title"),
1692           "dateOfBirth"       => _("Date of birth"),
1693           "gender"            => _("Sex"),
1694           "preferredLanguage" => _("Preferred language"),
1695           "base"              => _("Base"), 
1697           "userPicture"       => _("User picture"),
1699           "gosaLoginRestriction" => _("Login restrictions"),         
1701           "o"                 => _("Organization"),
1702           "ou"                => _("Department"),
1703           "departmentNumber"  => _("Department number"),
1704           "manager"           => _("Manager"),
1705           "employeeNumber"    => _("Employee number"),
1706           "employeeType"      => _("Employee type"),
1708           "roomNumber"        => _("Room number"),
1709           "telephoneNumber"   => _("Telefon number"),
1710           "pager"             => _("Pager number"),
1711           "mobile"            => _("Mobile number"),
1712           "facsimileTelephoneNumber"     => _("Fax number"),
1714           "st"                => _("State"),
1715           "l"                 => _("Location"),
1716           "postalAddress"     => _("Postal address"),
1718           "homePostalAddress" => _("Home postal address"),
1719           "homePhone"         => _("Home phone number"),
1720           "labeledURI"        => _("Homepage"),
1721           "userPassword"      => _("User password method"), 
1722           "Certificate"       => _("User certificates"))
1724         );
1726     /* Append government attributes if required */
1727     global $config;
1728     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1729       foreach($govattrs as $attr => $desc){
1730         $ret["plProvidedAcls"][$attr] = $desc;
1731       }
1732     }
1733     return($ret);
1734   }
1736   function get_multi_edit_values()
1737   {
1738     $ret = plugin::get_multi_edit_values();
1739     if(in_array("pw_storage",$this->multi_boxes)){
1740       $ret['pw_storage'] = $this->pw_storage;
1741     }
1742     if(in_array("edit_picture",$this->multi_boxes)){
1743       $ret['jpegPhoto'] = $this->jpegPhoto;
1744       $ret['photoData'] = $this->photoData;
1745       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1746       $ret['old_photoData'] = $this->old_photoData;
1747     }
1748     if(isset($ret['dateOfBirth'])){
1749       unset($ret['dateOfBirth']);
1750     }
1751     if(isset($ret['cn'])){
1752       unset($ret['cn']);
1753     }
1754     $ret['is_modified'] = $this->is_modified;
1755     if(in_array("base",$this->multi_boxes)){
1756       $ret['orig_base']="Changed_by_Multi_Plug";
1757       $ret['base']=$this->base;
1758     }
1760     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1761     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1763     return($ret); 
1764   }
1767   function multiple_save_object()
1768   {
1770     if(!isset($_POST['user_mulitple_edit'])) return;
1772     plugin::multiple_save_object();
1774     /* Get pw_storage mode */
1775     if (isset($_POST['pw_storage'])){
1776       foreach(array("pw_storage") as $val){
1777         if(isset($_POST[$val])){
1778           $data= validate(get_post($val));
1779           if ($data != $this->$val){
1780             $this->is_modified= TRUE;
1781           }
1782           $this->$val= $data;
1783         }
1784       }
1785     }
1786   
1787     /* Refresh base */
1788     if ($this->acl_is_moveable($this->base)){
1789       if (!$this->baseSelector->update()) {
1790         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1791       }
1792       if ($this->base != $this->baseSelector->getBase()) {
1793         $this->base= $this->baseSelector->getBase();
1794       }
1795     }
1797     if(isset($_POST['user_mulitple_edit'])){
1798       foreach(array("base","pw_storage","edit_picture") as $val){
1799         if(isset($_POST["use_".$val])){
1800           $this->multi_boxes[] = $val;
1801         }
1802       }
1803     }
1805     /* Sync lists */
1806     $this->gosaLoginRestrictionWidget->save_object();
1807     if ($this->gosaLoginRestrictionWidget->isModified()) {
1808       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1809     }
1810   }
1812   
1813   function multiple_check()
1814   {
1815     /* Call check() to set new_dn correctly ... */
1816     $message = plugin::multiple_check();
1818     /* Set the new acl base */
1819     if($this->dn == "new") {
1820       $this->set_acl_base($this->base);
1821     }
1822     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1823       $message[]= msgPool::invalid(_("Homepage"));
1824     }
1825     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1826       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1827     }
1828     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1829       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1830     }
1831     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1832       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1833     }
1834     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1835       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1836     }
1837     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1838       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1839     }
1840     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1841       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1842     }
1843     return($message);
1844   }
1848   function multiple_execute()
1849   {
1850     return($this->execute());
1851   }
1854   /*! \brief  Prepares the plugin to be used for multiple edit
1855    *          Update plugin attributes with given array of attribtues.
1856    *  \param  array   Array with attributes that must be updated.
1857    */
1858   function init_multiple_support($attrs,$all)
1859   {
1860     plugin::init_multiple_support($attrs,$all);
1862     // Get login restrictions
1863     if(isset($attrs['gosaLoginRestriction'])){
1864       $this->gosaLoginRestriction  =array();
1865       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1866         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1867       }
1868     }
1870     // Detect the managers name
1871     $this->manager_name = "";
1872     $ldap = $this->config->get_ldap_link();
1873     if(!empty($this->manager)){
1874       $ldap->cat($this->manager, array('cn'));
1875       if($ldap->count()){
1876         $attrs = $ldap->fetch();
1877         $this->manager_name = $attrs['cn'][0];
1878       }else{
1879         $this->manager_name = "("._("Unknown")."!): ".$this->manager;
1880       }
1881     }
1883     // Detect login restriction not used in all user objects.
1884     $this->gosaLoginRestriction_some = array();
1885     if(isset($all['gosaLoginRestriction'])){
1886       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1887         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1888       }
1889     }
1892     // Reinit the login restriction list.
1893     $data = $this->convertLoginRestriction();
1894     if(count($data)){
1895       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1896     }
1897   }
1900   function set_multi_edit_values($attrs)
1901   {
1902     $lR = array();
1904     // Update loginRestrictions, keep my settings while ip is optional
1905     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1906       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1907         $lR[] = $ip;
1908       }
1909     }
1911     // Add enforced loginRestrictions 
1912     foreach($attrs['gosaLoginRestriction'] as $ip){
1913       $lR[] = $ip;
1914     }
1916     $lR = array_values(array_unique($lR));
1917     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1918     plugin::set_multi_edit_values($attrs);
1919     $this->gosaLoginRestriction = $lR;
1920   }
1923   function convertLoginRestriction()
1924   {
1925     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1926     $data = array();
1927     foreach($all as $ip){
1928       $data['data'][] = $ip;
1929       if(!in_array($ip, $this->gosaLoginRestriction)){
1930         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1931       }else{
1932         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1933       }
1934     }   
1935     return($data);
1936   }
1939 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1940 ?>