Code

Updated manager attribute handling
[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     }
312     // Allow to select a new inetOrgPersion:manager 
313     if(preg_match("/ editManager/i", " ".implode(array_keys($_POST),' ')." ")){
314       $this->dialog = new singleUserSelect($this->config, get_userinfo());
315     }
316     if($this->dialog && count($this->dialog->detectPostActions())){
317       $users = $this->dialog->detectPostActions();
318       if(isset($users['targets']) && count($users['targets'])){
320         $headpage = $this->dialog->getHeadpage();
321         $dn = $users['targets'][0];
322         $attrs = $headpage->getEntry($dn);
323         $this->manager = $dn;
324         $this->manager_name = $attrs['cn'][0];
325         $this->dialog = NULL;
326       }
327     }
328     if(isset($_POST['add_users_cancel'])){
329       $this->dialog = NULL;
330     }
331     if($this->dialog) return($this->dialog->execute()); 
334     $smarty= get_smarty();
335     $smarty->assign("usePrototype", "true");
336     $smarty->assign("gosaLoginRestrictionWidget", $this->gosaLoginRestrictionWidget->render());
338     /* Assign sex */
339     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
340     $smarty->assign("gender_list", $sex);
341     $language= array_merge(array(0 => "&nbsp;") ,get_languages(TRUE));
342     $smarty->assign("preferredLanguage_list", $language);
344     /* Get random number for pictures */
345     srand((double)microtime()*1000000); 
346     $smarty->assign("rand", rand(0, 10000));
349     /* Do we represent a valid gosaAccount? */
350     if (!$this->is_account){
351       $str = "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
352         msgPool::noValidExtension("GOsa")."</b>";
353       return($str);
354     }
356     /* Password configure dialog handling */
357     if(is_object($this->pwObject) && $this->pwObject->display){
358       $output= $this->pwObject->configure();
359       if ($output != ""){
360         $this->dialog= TRUE;
361         return $output;
362       }
363       $this->dialog= false;
364     }
366     /* Dialog handling */
367     if(is_object($this->dialog)){
368       /* Must be called before save_object */
369       $this->dialog->save_object();
370    
371       if($this->dialog->isClosed()){
372         $this->dialog = false;
373       }elseif($this->dialog->isSelected()){
375         /* check if selected base is allowed to move to / create a new object */
376         $tmp = $this->get_allowed_bases();
377         if(isset($tmp[$this->dialog->isSelected()])){
378           $this->base = $this->dialog->isSelected();
379         }
380         $this->dialog= false;
381       }else{
382         return($this->dialog->execute());
383       }
384     }
386     /* Want password method editing? */
387     if ($this->acl_is_writeable("userPassword")){
388       if (isset($_POST['edit_pw_method'])){
389         if (!is_object($this->pwObject) || $this->pw_storage != $this->pwObject->get_hash_name()){
390           $temp= passwordMethod::get_available_methods();
391           $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
392         }
393         $this->pwObject->display = TRUE;
394         $this->dialog= TRUE;
395         return ($this->pwObject->configure());
396       }
397     }
399     /* Want picture edit dialog? */
400     if($this->acl_is_writeable("userPicture")) {
401       if (isset($_POST['edit_picture'])){
402         /* Save values for later recovery, in case some presses
403            the cancel button. */
404         $this->old_jpegPhoto= $this->jpegPhoto;
405         $this->old_photoData= $this->photoData;
406         $this->picture_dialog= TRUE;
407         $this->dialog= TRUE;
408       }
409     }
411     /* Remove picture? */
412     if($this->acl_is_writeable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))) ){
413       if (isset($_POST['picture_remove'])){
414         $this->set_picture ();
415         $this->jpegPhoto= "*removed*";
416         $this->is_modified= TRUE;
417         return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
418       }
419     }
421     /* Save picture */
422     if (isset($_POST['picture_edit_finish'])){
424       /* Check for clean upload */
425       if ($_FILES['picture_file']['name'] != ""){
426         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
427           msg_dialog::display(_("Error"), _("Cannot upload file!"), ERROR_DIALOG);
428         }else{
429           /* Activate new picture */
430           $this->set_picture($_FILES['picture_file']['tmp_name']);
431         }
432       }
433       $this->picture_dialog= FALSE;
434       $this->dialog= FALSE;
435       $this->is_modified= TRUE;
436     }
439     /* Cancel picture */
440     if (isset($_POST['picture_edit_cancel'])){
442       /* Restore values */
443       $this->jpegPhoto= $this->old_jpegPhoto;
444       $this->photoData= $this->old_photoData;
446       /* Update picture */
447       session::set('binary',$this->photoData);
448       session::set('binarytype',"image/jpeg");
449       $this->picture_dialog= FALSE;
450       $this->dialog= FALSE;
451     }
453     /* Want certificate= */
454     if ((isset($_POST['edit_cert'])) && $this->acl_is_readable("Certificate")){
456       /* Save original values for later reconstruction */
457       foreach (array("certificateSerialNumber", "userCertificate",
458             "userSMIMECertificate", "userPKCS12") as $val){
460         $oval= "old_$val";
461         $this->$oval= $this->$val;
462       }
464       $this->cert_dialog= TRUE;
465       $this->dialog= TRUE;
466     }
469     /* Cancel certificate dialog */
470     if (isset($_POST['cert_edit_cancel'])){
472       /* Restore original values in case of 'cancel' */
473       foreach (array("certificateSerialNumber", "userCertificate",
474             "userSMIMECertificate", "userPKCS12") as $val){
476         $oval= "old_$val";
477         $this->$val= $this->$oval;
478       }
479       $this->cert_dialog= FALSE;
480       $this->dialog= FALSE;
481     }
484     /* Remove certificate? */
485     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
486       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
487         if (isset($_POST["remove_$val"])){
489           /* Reset specified cert*/
490           $this->$val= "";
491           $this->is_modified= TRUE;
492         }
493       }
494     }
496     /* Upload new cert and close dialog? */     
497     if($this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))){ 
499       $fail =false;
501       if (isset($_POST['cert_edit_finish'])){
503         /* for all certificates do */
504         foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
505             as $val){
507           /* Check for clean upload */
508           if (array_key_exists($val."_file", $_FILES) &&
509               array_key_exists('name', $_FILES[$val."_file"]) &&
510               $_FILES[$val."_file"]['name'] != "" &&
511               is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
512             $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
513           }
514         }
516         /* Save serial number */
517         if (isset($_POST["certificateSerialNumber"]) &&
518             $_POST["certificateSerialNumber"] != ""){
520           if (!tests::is_id($_POST["certificateSerialNumber"])){
521             $fail = true;
522             msg_dialog::display(_("Error"), msgPool::invalid(_("Serial number"),$_POST["certificateSerialNumber"],"/[0-9]/"),ERROR_DIALOG);
524             foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
525               if ($this->$cert != ""){
526                 $smarty->assign("$cert"."_state", "true");
527               } else {
528                 $smarty->assign("$cert"."_state", "");
529               }
530             }
531           }
533           $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
534           $this->is_modified= TRUE;
535         }
536         if(!$fail){
537           $this->cert_dialog= FALSE;
538           $this->dialog= FALSE;
539         }
540       }
541     }
542     /* Display picture dialog */
543     if ($this->picture_dialog){
544       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
545     }
547     /* Display cert dialog */
548     if ($this->cert_dialog){
549       $smarty->assign("CertificateACL",$this->getacl("Certificate",(!is_object($this->parent) && !session::is_set('edit'))));
550       $smarty->assign("Certificate_readable",$this->acl_is_readable("Certificate"));
551       $smarty->assign("certificateSerialNumber",$this->certificateSerialNumber);
553       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
554         if ($this->$cert != ""){
555           /* import certificate */
556           $certificate = new certificate;
557           $certificate->import($this->$cert);
558       
559           /* Read out data*/
560           $timeto   = $certificate->getvalidto_date();
561           $timefrom = $certificate->getvalidfrom_date();
562          
563           
564           /* Additional info if start end time is '0' */
565           $add_str_info = "";
566           if($timeto == 0 && $timefrom == 0){
567             $add_str_info = "<br><i>"._("(Some types of certificates are currently not supported and may be displayed as 'invalid'.)")."</i>";
568           }
570           $str = "<table summary=\"\" border=0>
571                     <tr>
572                       <td style='vertical-align:top'>CN</td>
573                       <td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td>
574                     </tr>
575                   </table><br>".
577                   sprintf(_("Certificate is valid from %s to %s and is currently %s."),
578                         "<b>".date('d M Y',$timefrom)."</b>",
579                         "<b>".date('d M Y',$timeto)."</b>",
580                         $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":
581                                                 "<b><font style='color:red'>"._("invalid")."</font></b>").$add_str_info;
583           $smarty->assign($cert."info",$str);
584           $smarty->assign($cert."_state","true");
585         } else {
586           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
587           $smarty->assign($cert."_state","");
588         }
589       }
590   
591       if($this->governmentmode){
592         $smarty->assign("honourIvbbAttributes", "true");
593       }else{
594         $smarty->assign("honourIvbbAttributes", "false");
595       }
596       $smarty->assign("governmentmode", $this->governmentmode);
597       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
598     }
600     /* Prepare password hashes */
601     if ($this->pw_storage == ""){
602       $this->pw_storage= $this->config->get_cfg_value("hash");
603     }
605     $temp= passwordMethod::get_available_methods();
606     $is_configurable= FALSE;
607     $hashes = $temp['name'];
608     if(isset($temp[$this->pw_storage])){
609       $test= new $temp[$this->pw_storage]($this->config);
610       $is_configurable= $test->is_configurable();
611     }else{
612       new msg_dialog(_("Password method"),_("The selected password method is no longer available."),WARNING_DIALOG);
613     }
616     /* Create password methods array */
617     $pwd_methods = array();
618     foreach($hashes as $id => $name){
619       if(!empty($temp['desc'][$id])){
620         $pwd_methods[$name] = $name." (".$temp['desc'][$id].")";
621       }else{
622         $pwd_methods[$name] = $name;
623       }
624     }
625  
626     /* Load attributes and acl's */
627     $ui =get_userinfo();
628     foreach($this->attributes as $val){
629       $smarty->assign("$val", $this->$val);
630       if(in_array($val,$this->multi_boxes)){
631         $smarty->assign("use_".$val,TRUE);
632       }else{
633         $smarty->assign("use_".$val,FALSE);
634       }
635     }
636     foreach(array("base","pw_storage","edit_picture") as $val){
637       if(in_array($val,$this->multi_boxes)){
638         $smarty->assign("use_".$val,TRUE);
639       }else{
640         $smarty->assign("use_".$val,FALSE);
641       }
642     }
644     /* Set acls */
645     $tmp = $this->plinfo();
646     foreach($tmp['plProvidedAcls'] as $val => $translation){
647       $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
648     }
650     // Special ACL for gosaLoginRestrictions - 
651     // In case of multiple edit, we need a readonly ACL for the list. 
652     $smarty->assign('gosaLoginRestriction_ONLY_R_ACL', 
653       preg_replace("/[^r]/i","", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit')))));
655     $smarty->assign("pwmode", $pwd_methods);
656     $smarty->assign("pwmode_select", $this->pw_storage);
657     $smarty->assign("pw_configurable", $is_configurable);
658     $smarty->assign("passwordStorageACL", $this->getacl("userPassword",(!is_object($this->parent) && !session::is_set('edit'))));
660     if(!session::is_set('edit')){
661       $smarty->assign("CertificatesACL","");
662     }else{
663       $smarty->assign("CertificatesACL",  $this->getacl("Certificate"));
664     }
665     
666     $smarty->assign("userPictureACL",   $this->getacl("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
667     $smarty->assign("userPicture_is_readable",   $this->acl_is_readable("userPicture",(!is_object($this->parent) && !session::is_set('edit'))));
669     /* Create base acls */
670     $smarty->assign("base", $this->baseSelector->render());
672     /* Save government mode attributes */
673     if($this->governmentmode){
674       $smarty->assign("governmentmode", "true");
675       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
676           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
677       $smarty->assign("ivbbmodes", $ivbbmodes);
678       foreach ($this->govattrs as $val){
679         $smarty->assign("$val", $this->$val);
680         $smarty->assign("$val"."ACL", $this->getacl($val,(!is_object($this->parent) && !session::is_set('edit'))));
681       }
682     } else {
683       $smarty->assign("governmentmode", "false");
684     }
686     /* Special mode for uid */
687     $uidACL= $this->getacl("uid",(!is_object($this->parent) && !session::is_set('edit')));
688     if (isset ($this->dn)){
689       if ($this->dn != "new"){
690         $uidACL= preg_replace("/w/","",$uidACL);
691       }
692     }  else {
693       $uidACL= preg_replace("/w/","",$uidACL);
694     }
695     
696     $smarty->assign("uidACL", $uidACL);
697     $smarty->assign("is_template", $this->is_template);
698     $smarty->assign("use_dob", $this->use_dob);
700     if (isset($this->parent)){
701       if (isset($this->parent->by_object['phoneAccount']) &&
702           $this->parent->by_object['phoneAccount']->is_account){
703         $smarty->assign("has_phoneaccount", "true");
704       } else {
705         $smarty->assign("has_phoneaccount", "false");
706       }
707     } else {
708       $smarty->assign("has_phoneaccount", "false");
709     }
710     $smarty->assign("multiple_support" , $this->multiple_support_active);
711     $smarty->assign("manager_name",$this->manager_name);
712     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
713   }
716   /* remove object from parent */
717   function remove_from_parent()
718   {
719     /* Only remove valid accounts */
720     if(!$this->initially_was_account) return;
722     /* Remove password extension */
723     $temp= passwordMethod::get_available_methods();
725     /* Remove password method from user account */
726     if(isset($temp[$this->pw_storage]) && class_available($temp[$this->pw_storage])){
727       $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
728       $this->pwObject->remove_from_parent();
729     }
731     /* Remove user */
732     $ldap= $this->config->get_ldap_link();
733     $ldap->rmdir ($this->dn);
734     if (!$ldap->success()){
735       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
736     }
737   
738     new log("remove","users/".get_class($this),$this->dn,$this->attributes,$ldap->get_error());
739   
740     /* Delete references to groups */
741     $ldap->cd ($this->config->current['BASE']);
742     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
743     while ($ldap->fetch()){
744       $g= new group($this->config, $ldap->getDN());
745       $g->removeUser($this->uid);
746       $g->save ();
747     }
749     /* Delete references to object groups */
750     $ldap->cd ($this->config->current['BASE']);
751     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
752     while ($ldap->fetch()){
753       $og= new ogroup($this->config, $ldap->getDN());
754       unset($og->member[$this->dn]);
755       $og->member= array_values($og->member);
756       $og->save ();
757     }
759     /* Delete references to roles */
760     $ldap->cd ($this->config->current['BASE']);
761     $ldap->search ("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter($this->dn)."))", array("cn"));
762     while ($ldap->fetch()){
763       $role= new roleGeneric($this->config, $ldap->getDN());
764       $key = array_search($this->dn,$role->roleOccupant);
765       if($key !== FALSE){
766         unset($role->roleOccupant[$key]);
767         $role->roleOccupant= array_values($role->roleOccupant);
768         $role->save ();
769       }
770     }
772     /* If needed, let the password method do some cleanup */
773     $tmp = new passwordMethod($this->config);
774     $available = $tmp->get_available_methods();
775     if (in_array_ics($this->pw_storage, $available['name'])){
776       $test= new $available[$this->pw_storage]($this->config);
777       $test->attrs= $this->attrs;
778       $test->dn= $this->dn;
779       $test->remove_from_parent();
780     }
782     /* Remove ACL dependencies too */
783     acl::remove_acl_for($this->dn);
785     /* Optionally execute a command after we're done */
786     $this->handle_post_events("remove",array("uid" => $this->uid));
787   }
790   /* Save data to object */
791   function save_object()
792   {
793     if(isset($_POST['generic']) || isset($_POST['multiple_user_posted'])){
795       /* Make a backup of the current selected base */
796       $base_tmp = $this->base;
798       /* Parents save function */
799       plugin::save_object ();
801       /* Refresh base */
802       if ($this->acl_is_moveable($this->base)){
803         if (!$this->baseSelector->update()) {
804           msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
805         }
806         if ($this->base != $this->baseSelector->getBase()) {
807           $this->base= $this->baseSelector->getBase();
808           $this->is_modified= TRUE;
809         }
810       }
811       
812       /* Sync lists */
813       $this->gosaLoginRestrictionWidget->save_object();
814       if ($this->gosaLoginRestrictionWidget->isModified()) {
815         $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
816       }
818       /* Save government mode attributes */
819       if ($this->governmentmode){
820         foreach ($this->govattrs as $val){
821           if ($this->acl_is_writeable($val,(!is_object($this->parent) && !session::is_set('edit'))) && isset($_POST["$val"])){
822             $data= stripcslashes($_POST["$val"]);
823             if ($data != $this->$val){
824               $this->is_modified= TRUE;
825             }
826             $this->$val= $data;
827           }
828         }
829       }
831       /* In template mode, the uid is autogenerated... */
832       if ($this->is_template){
833         $this->uid= strtolower($this->sn);
834         $this->givenName= $this->sn;
835       }
837       /* Get pw_storage mode */
838       if (isset($_POST['pw_storage'])){
839         foreach(array("pw_storage") as $val){
840           if(isset($_POST[$val])){
841             $data= validate($_POST[$val]);
842             if ($data != $this->$val){
843               $this->is_modified= TRUE;
844             }
845             $this->$val= $data;
846           }
847         }
848       }
850       if($this->pw_storage != $this->last_pw_storage && isset($_POST['pw_storage'])){
851         if ($this->acl_is_writeable("userPassword")){
852           $temp= passwordMethod::get_available_methods();
853           if (!is_object($this->pwObject) || !($this->pwObject instanceOf $temp[$this->pw_storage])){
854             foreach($temp as $id => $data){
855               if(isset($data['name']) && $data['name'] == $this->pw_storage && $data['is_configurable']){
856                 $this->pwObject= new $temp[$this->pw_storage]($this->config,$this->dn);
857                 break;
858               }
859             }
860           }
861         }
862       }
864       /* Save current cn
865        */
866       $this->cn = $this->givenName." ".$this->sn;
867     }
868   }
870   function rebind($ldap, $referral)
871   {
872     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
873     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
874       $this->error = "Success";
875       $this->hascon=true;
876       $this->reconnect= true;
877       return (0);
878     } else {
879       $this->error = "Could not bind to " . $credentials['ADMIN'];
880       return NULL;
881     }
882   }
884   
885   /* Save data to LDAP, depending on is_account we save or delete */
886   function save()
887   {
888     global $lang;
890     /* Only force save of changes .... 
891        If this attributes aren't changed, avoid saving.
892      */
893   
894     if($this->gender=="0") $this->gender ="";
895     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
897     /* First use parents methods to do some basic fillup in $this->attrs */
898     plugin::save ();
900     if ($this->dateOfBirth != ""){
901       if(!is_array($this->attrs['dateOfBirth'])) {
902         #TODO: use $lang to convert date
903         list($day, $month, $year)= explode(".", $this->dateOfBirth);
904         $this->attrs['dateOfBirth'] = sprintf("%04d-%02d-%02d", $year, $month, $day);
905       }
906     }
908     /* Remove additional objectClasses */
909     $tmp= array();
910     foreach ($this->attrs['objectClass'] as $key => $set){
911       $found= false;
912       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
913         if (preg_match ("/^$set$/i", $val)){
914           $found= true;
915           break;
916         }
917       }
918       if (!$found){
919         $tmp[]= $set;
920       }
921     }
923     /* Replace the objectClass array. This is done because of the
924        separation into government and normal mode. */
925     $this->attrs['objectClass']= $tmp;
927     /* Add objectClasss for template mode? */
928     if ($this->is_template){
929       $this->attrs['objectClass'][]= "gosaUserTemplate";
930     }
932     /* Hard coded government mode? */
933     if ($this->governmentmode){
934       $this->attrs['objectClass'][]= "ivbbentry";
936       /* Copy standard attributes */
937       foreach ($this->govattrs as $val){
938         if ($this->$val != ""){
939           $this->attrs["$val"]= $this->$val;
940         } elseif (!$this->is_new) {
941           $this->attrs["$val"]= array();
942         }
943       }
945       /* Remove attribute if set to "nein" */
946       if ($this->publicVisible == "nein"){
947         $this->attrs['publicVisible']= array();
948         if($this->is_new){
949           unset($this->attrs['publicVisible']);
950         }else{
951           $this->attrs['publicVisible']=array();
952         }
954       }
956     }
958     /* Special handling for attribute userCertificate needed */
959     if ($this->userCertificate != ""){
960       $this->attrs["userCertificate;binary"]= $this->userCertificate;
961       $remove_userCertificate= false;
962     } else {
963       $remove_userCertificate= true;
964     }
966     /* Special handling for dateOfBirth value */
967     if ($this->dateOfBirth == ""){
968       if ($this->is_new) {
969         unset($this->attrs["dateOfBirth"]);
970       } else {
971         $this->attrs["dateOfBirth"]= array();
972       }
973     }
974     if (!$this->gender){
975       if ($this->is_new) {
976         unset($this->attrs["gender"]);
977       } else {
978         $this->attrs["gender"]= array();
979       }
980     }
981     if (!$this->preferredLanguage){
982       if ($this->is_new) {
983         unset($this->attrs["preferredLanguage"]);
984       } else {
985         $this->attrs["preferredLanguage"]= array();
986       }
987     }
989     /* Special handling for attribute jpegPhote needed, scale image via
990        image magick to 147x200 pixels and inject resulting data. */
991     if ($this->jpegPhoto == "*removed*"){
992     
993       /* Reset attribute to avoid writing *removed* as value */    
994       $this->attrs["jpegPhoto"] = array();
996     } else {
998       /* Fallback if there's no image magick inside PHP */
999       if (!function_exists("imagick_blob2image")){
1000         /* Get temporary file name for conversation */
1001         $fname = tempnam (TEMP_DIR, "GOsa");
1002   
1003         /* Open file and write out photoData */
1004         $fp = fopen ($fname, "w");
1005         fwrite ($fp, $this->photoData);
1006         fclose ($fp);
1008         /* Build conversation query. Filename is generated automatically, so
1009            we do not need any special security checks. Exec command and save
1010            output. For PHP safe mode, you'll need a configuration which respects
1011            image magick as executable... */
1012         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
1013         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
1014             $query, "Execute");
1015   
1016         /* Read data written by convert */
1017         $output= "";
1018         $sh= popen($query, 'r');
1019         while (!feof($sh)){
1020           $output.= fread($sh, 4096);
1021         }
1022         pclose($sh);
1024         unlink($fname);
1026         /* Save attribute */
1027         $this->attrs["jpegPhoto"] = $output;
1029       } else {
1031         /* Load the new uploaded Photo */
1032         if(!$handle  =  imagick_blob2image($this->photoData))  {
1033           new log("debug","users/".get_class($this),$this->dn,array(),"Could not access uploaded image");
1034         }
1036         /* Resizing image to 147x200 and blur */
1037         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
1038           new log("debug","users/".get_class($this),$this->dn,array(),"Could not resize uploaded image");
1039         }
1041         /* Converting image to JPEG */
1042         if(!imagick_convert($handle,"JPEG")) {
1043           new log("debug","users/".get_class($this),$this->dn,array(),"Could not convert uploaded image to jepg");
1044         }
1046         /* Creating binary Code for the Image */
1047         if(!$dump = imagick_image2blob($handle)){
1048           new log("debug","users/".get_class($this),$this->dn,array(),"Could not create new user image");
1049         }
1051         /* Sending Image */
1052         $output=  $dump;
1054         /* Save attribute */
1055         $this->attrs["jpegPhoto"] = $output;
1056       }
1058     }
1060     /* This only gets called when user is renaming himself */
1061     $ldap= $this->config->get_ldap_link();
1062     if ($this->dn != $this->new_dn){
1064       /* Write entry on new 'dn' */
1065       $this->update_acls($this->dn,$this->new_dn);
1066       $this->move($this->dn, $this->new_dn);
1068       /* Happen to use the new one */
1069       change_ui_dn($this->dn, $this->new_dn);
1070       $this->dn= $this->new_dn;
1071     }
1074     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
1075        new entries. So do a check first... */
1076     $ldap->cat ($this->dn, array('dn'));
1077     if ($ldap->fetch()){
1078       $mode= "modify";
1079     } else {
1080       $mode= "add";
1081       $ldap->cd($this->config->current['BASE']);
1082       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
1083     }
1085     /* Set password to some junk stuff in case of templates */
1086     if ($this->is_template){
1087       $temp= passwordMethod::get_available_methods();
1088       foreach($temp as $id => $data){
1089         if(isset($data['name']) && $data['name'] == $this->pw_storage){
1090           $tmp = new  $temp[$this->pw_storage]($this->config,$this->dn);
1091           $tmp->set_hash($this->pw_storage);
1092           $this->attrs['userPassword'] = $tmp->create_template_hash($this->attrs);
1093           break;
1094         }
1095       }
1096     }
1098     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
1099         $this->attributes, "Save via $mode");
1101     /* Finally write data with selected 'mode' */
1102     $this->cleanup();
1104     /* Update current locale settings, if we have edited ourselves */
1105     $ui = session::get('ui');
1106     if(isset($this->attrs['preferredLanguage']) && $this->dn == $ui->dn){
1107       $ui->language = $this->preferredLanguage;
1108       session::set('ui',$ui);
1109       session::set('Last_init_lang',"update");
1110     }
1112     $ldap->cd ($this->dn);
1113     $ldap->$mode ($this->attrs);
1114     if (!$ldap->success()){
1115       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
1116       return (1);
1117     }
1119     /* Remove ACL dependencies too */
1120     if($this->dn != $this->orig_dn && $this->orig_dn != "new"){
1121       $tmp = new acl($this->config,$this->parent,$this->dn);
1122       $tmp->update_acl_membership($this->orig_dn,$this->dn);
1123     }
1125     if($mode == "modify"){
1126       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1127     }else{
1128       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1129     }
1131     /* Remove cert? 
1132        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
1133        to work around myself. */
1134     if ($remove_userCertificate == true && !$this->is_new && $this->had_userCertificate){
1136       /* Reset array, assemble new, this should be reworked */
1137       $this->attrs= array();
1138       $this->attrs['userCertificate;binary']= array();
1140       /* Prepare connection */
1141       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
1142         die ("Could not connect to LDAP server");
1143       }
1144       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1145       if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true") {
1146         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1147         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1148       }
1149       if($this->config->get_cfg_value("ldapTLS") == "true"){
1150         ldap_start_tls($ds);
1151       }
1152       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
1153               $this->config->current['PASSWORD']))) {
1154         die ("Could not bind to LDAP");
1155       }
1157       /* Modify using attrs */
1158       ldap_mod_del($ds,$this->dn,$this->attrs);
1159       ldap_close($ds);
1160     }
1162     /* If needed, let the password method do some cleanup */
1163     if ($this->pw_storage != $this->last_pw_storage){
1164       $tmp = new passwordMethod($this->config);
1165       $available = $tmp->get_available_methods();
1166       if (in_array_ics($this->last_pw_storage, $available['name'])){
1167         $test= new $available[$this->last_pw_storage]($this->config,$this->dn);
1168         $test->attrs= $this->attrs;
1169         $test->remove_from_parent();
1170       }
1171     }
1173     /* Maybe the current password method want's to do some changes... */
1174     if (is_object($this->pwObject)){
1175       $this->pwObject->save($this->dn);
1176     }
1178     /* Optionally execute a command after we're done */
1179     if ($mode == "add"){
1180       $this->handle_post_events("add", array("uid" => $this->uid));
1181     } elseif ($this->is_modified){
1182       $this->handle_post_events("modify", array("uid" => $this->uid));
1183     }
1185     return (0);
1186   }
1189   function create_initial_rdn($pattern)
1190   {
1191     // Only generate single RDNs
1192     if (preg_match('/\+/', $pattern)){
1193       msg_dialog::display(_("Error"), _("Cannot build RDN: no + allowed to build sub RDN!"), ERROR_DIALOG);
1194       return "";
1195     }
1197     // Extract attribute
1198     $attribute= preg_replace('/=.*$/', '', $pattern);
1199     if (!in_array_ics($attribute, $this->attributes)) {
1200       msg_dialog::display(_("Error"), _("Cannot build RDN: attribute is not defined!"), ERROR_DIALOG);
1201       return "";
1202     }
1204     // Sort attributes for length
1205     $attrl= array();
1206     foreach ($this->attributes as $attr) {
1207       $attrl[$attr]= strlen($attr);
1208     }
1209     arsort($attrl);
1210     
1211     // Walk thru sorted attributes and replace them in pattern
1212     foreach ($attrl as $attr => $dummy) {
1213       if (!is_array($this->$attr)){
1214         $pattern= preg_replace("/%$attr/", $this->$attr, $pattern);
1215       } else {
1216         // Array elements cannot be used for ID generation
1217         if (preg_match("/%$attr/", $pattern)) {
1218           msg_dialog::display(_("Error"), _("Cannot build RDN: invalid attribute parameters!"), ERROR_DIALOG);
1219           break;
1220         }
1221       }
1222     }
1224     // Internally assign value
1225     $this->$attribute= preg_replace('/^[^=]+=/', '', $pattern);
1227     return $pattern;
1228   }
1230   
1231   function update_new_dn()
1232   {
1233     // Alternative way to handle DN
1234     $pattern= $this->config->get_cfg_value("accountRDN");
1235     if ($pattern != "") {
1236       $rdn= $this->create_initial_rdn($pattern);
1237       $attribute= preg_replace('/=.*$/', '', $rdn);
1238       $value= preg_replace('/^[^=]+=$/', '', $rdn);
1240       /* Don't touch dn, if $attribute hasn't changed */
1241       if (isset($this->saved_attributes[$attribute]) && $this->saved_attributes[$attribute] == $this->$attribute &&
1242             $this->orig_base == $this->base ){
1243         $this->new_dn= $this->dn;
1244       } else {
1245         $this->new_dn= $this->create_unique_dn2($rdn, get_people_ou().$this->base);
1246       }
1248     // Original way to handle DN
1249     } else {
1251       $pt= "";
1252       if($this->config->get_cfg_value("personalTitleInDN") == "true"){
1253         if(!empty($this->personalTitle)){
1254           $pt = $this->personalTitle." ";
1255         }
1256       }
1258       $this->cn= $pt.$this->givenName." ".$this->sn;
1260       /* Permissions for that base? */
1261       if ($this->config->get_cfg_value("accountPrimaryAttribute") == "uid"){
1262         $this->new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
1263       } else {
1264         /* Don't touch dn, if cn hasn't changed */
1265         if (isset($this->saved_attributes['cn']) && $this->saved_attributes['cn'] == $this->cn &&
1266             $this->orig_base == $this->base ){
1267           $this->new_dn= $this->dn;
1268         } else {
1269           $this->new_dn= $this->create_unique_dn('cn', get_people_ou().$this->base);
1270         }
1271       }
1272     }
1273   }
1274   
1276   /* Check formular input */
1277   function check()
1278   {
1279     /* Call common method to give check the hook */
1280     $message= plugin::check();
1282     /* Configurable password methods should be configured initially. 
1283      */ 
1284     if($this->last_pw_storage != $this->pw_storage){
1285       $temp= passwordMethod::get_available_methods();
1286       foreach($temp['name'] as $id => $name){
1287         if($name == $this->pw_storage){
1288           if($temp['is_configurable'][$id] && !$this->pwObject instanceof $temp[$name] ){
1289             $message[] = _("The selected password method requires initial configuration!");
1290           }
1291           break;
1292         }
1293       }
1294     }
1296     $this->update_new_dn();
1298     /* Set the new acl base */
1299     if($this->dn == "new") {
1300       $this->set_acl_base($this->base);
1301     }
1303     /* Check if we are allowed to create/move this user */
1304     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
1305       $message[]= msgPool::permCreate();
1306     }elseif($this->orig_dn != "new" && $this->new_dn != $this->orig_dn && !$this->acl_is_moveable($this->base)){
1307       $message[]= msgPool::permMove();
1308     }
1310     /* UID already used? */
1311     $ldap= $this->config->get_ldap_link();
1312     $ldap->cd($this->config->current['BASE']);
1313     $ldap->search("(uid=$this->uid)", array("uid"));
1314     $ldap->fetch();
1315     if ($ldap->count() != 0 && $this->dn == 'new'){
1316       $message[]= msgPool::duplicated(_("Login"));
1317     }
1319     /* In template mode, the uid and givenName are autogenerated... */
1320     if ($this->sn == ""){
1321       $message[]= msgPool::required(_("Name"));
1322     }
1324     // Check if a wrong base was supplied
1325     if(!$this->baseSelector->checkLastBaseUpdate()){
1326       $message[]= msgPool::check_base();;
1327     }
1329     if (!$this->is_template){
1330       if ($this->givenName == ""){
1331         $message[]= msgPool::required(_("Given name"));
1332       }
1333       if ($this->uid == ""){
1334         $message[]= msgPool::required(_("Login"));
1335       }
1336       if ($this->config->get_cfg_value("accountPrimaryAttribute") != "uid"){
1337         $ldap->cat($this->new_dn);
1338         if ($ldap->count() != 0 && $this->dn != $this->new_dn && $this->dn == 'new'){
1339           $message[]= msgPool::duplicated(_("Name"));
1340         }
1341       }
1342     }
1344     /* Check for valid input */
1345     if ($this->is_modified && !tests::is_uid($this->uid)){
1347       if (strict_uid_mode()){
1348         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/");
1349       } else {
1350         $message[]= msgPool::invalid(_("Login"), $this->uid, "/[a-z0-9_-]/i");
1351       }
1352     }
1353     if (!tests::is_url($this->labeledURI)){
1354       $message[]= msgPool::invalid(_("Homepage"), "", "", "http://www.your-domain.com/yourname");
1355     }
1357     /* Check phone numbers */
1358     if (!tests::is_phone_nr($this->telephoneNumber)){
1359       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1360     }
1361     if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
1362       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1363     }
1364     if (!tests::is_phone_nr($this->mobile)){
1365       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1366     }
1367     if (!tests::is_phone_nr($this->pager)){
1368       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1369     }
1371     /* Check dates */
1372     if (!tests::is_date($this->dateOfBirth)){
1373       $message[]= msgPool::invalid(_("Date of birth"), $this->dateOfBirth,"" ,"23.02.2009");
1374     }
1376     /* Check for reserved characers */
1377     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName)){
1378       $message[]= msgPool::invalid(_("Given name"), $this->givenName, '/[^,+"?\'()=<>;\\\\]/');
1379     }
1380     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn)){
1381       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1382     }
1384     return $message;
1385   }
1388   /* Indicate whether a password change is needed or not */
1389   function password_change_needed()
1390   {
1391     if(in_array("pw_storage",$this->multi_boxes)){
1392       return(TRUE);
1393     }
1394     return($this->pw_storage != $this->last_pw_storage && !$this->is_template);
1395   }
1398   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1399   function load_picture()
1400   {
1401     $ldap = $this->config->get_ldap_link();
1402     $ldap->cd ($this->dn);
1403     $data = $ldap->get_attribute($this->dn,"jpegPhoto");
1405     if((!$data) || ($data == "*removed*")){ 
1407       /* In case we don't get an entry, load a default picture */
1408       $this->set_picture ();
1409       $this->jpegPhoto= "*removed*";
1410     }else{
1412       /* Set picture */
1413       $this->photoData= $data;
1414       session::set('binary',$this->photoData);
1415       session::set('binarytype',"image/jpeg");
1416       $this->jpegPhoto= "";
1417     }
1418   }
1421   /* Load a certificate from LDAP, this is going to be simplified later on */
1422   function load_cert()
1423   {
1424     $ds= ldap_connect($this->config->current['SERVER']);
1425     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1426     if (function_exists("ldap_set_rebind_proc") && $this->config->get_cfg_value("ldapFollowReferrals") == "true"){
1427       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1428       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1429     }
1430     if ($this->config->get_cfg_value("ldapTLS") == "true"){
1431       ldap_start_tls($ds);
1432     }
1434     $r= ldap_bind($ds);
1435     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1437     if ($sr) {
1438       $ei= @ldap_first_entry($ds, $sr);
1439       
1440       if ($ei) {
1441         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1442           $this->userCertificate= "";
1443         } else {
1444           $this->userCertificate= $info[0];
1445         }
1446       }
1447     } else {
1448       $this->userCertificate= "";
1449     }
1451     ldap_unbind($ds);
1452   }
1455   /* Load picture from file to object */
1456   function set_picture($filename ="")
1457   {
1458     if (!is_file($filename) || $filename =="" ){
1459       $filename= "./plugins/users/images/default.jpg";
1460       $this->jpegPhoto= "*removed*";
1461     }
1463     $fd = fopen ($filename, "rb");
1464     $this->photoData= fread ($fd, filesize ($filename));
1465     session::set('binary',$this->photoData);
1466     session::set('binarytype',"image/jpeg");
1467     $this->jpegPhoto= "";
1469     fclose ($fd);
1470   }
1473   /* Load certificate from file to object */
1474   function set_cert($cert, $filename)
1475   {
1476     if(!$this->acl_is_writeable("Certificate",(!is_object($this->parent) && !session::is_set('edit')))) return;
1477     $fd = fopen ($filename, "rb");
1478     if (filesize($filename)>0) {
1479       $this->$cert= fread ($fd, filesize ($filename));
1480       fclose ($fd);
1481       $this->is_modified= TRUE;
1482     } else {
1483       msg_dialog::display(_("Error"), _("Cannot open certificate!"), ERROR_DIALOG);
1484     }
1485   }
1487   /* Adapt from given 'dn' */
1488   function adapt_from_template($dn, $skip= array())
1489   {
1490     plugin::adapt_from_template($dn, $skip);
1492     /* Get password method from template 
1493      */
1494     $tmp= passwordMethod::get_method($this->attrs['userPassword'][0]);
1495     if(is_object($tmp)){
1496       if($tmp->is_configurable()){
1497         $tmp->adapt_from_template($dn);
1498         $this->pwObject = &$tmp;
1499       }
1500       $this->pw_storage= $tmp->get_hash();
1501     }
1503     /* Get base */
1504     $this->base= preg_replace('/^[^,]+,'.preg_quote(get_people_ou(), '/').'/i', '', $dn);
1506     if($this->governmentmode){
1508       /* Walk through govattrs */
1509       foreach ($this->govattrs as $val){
1511         if (in_array($val, $skip)){
1512           continue;
1513         }
1515         if (isset($this->attrs["$val"][0])){
1517           /* If attribute is set, replace dynamic parts: 
1518              %sn, %givenName and %uid. Fill these in our local variables. */
1519           $value= $this->attrs["$val"][0];
1521           foreach (array("sn", "givenName", "uid") as $repl){
1522             if (preg_match("/%$repl/i", $value)){
1523               $value= preg_replace ("/%$repl/i",
1524                   $this->parent->$repl, $value);
1525             }
1526           }
1527           $this->$val= $value;
1528         }
1529       }
1530     }
1532     /* Get back uid/sn/givenName - only write if nothing's skipped */
1533     if ($this->parent !== NULL && count($skip) == 0){
1534       $this->uid= $this->parent->uid;
1535       $this->sn= $this->parent->sn;
1536       $this->givenName= $this->parent->givenName;
1537     }
1539     if ($this->dateOfBirth) {
1540       /* This entry is ISO 8601 conform */
1541       list($year, $month, $day)= explode("-", $this->dateOfBirth, 3);
1542     
1543       #TODO: use $lang to convert date
1544       $this->dateOfBirth= "$day.$month.$year";
1545     }
1546   }
1548  
1549   /* This avoids that users move themselves out of their rights. 
1550    */
1551   function allowedBasesToMoveTo()
1552   {
1553     /* Get bases */
1554     $bases  = $this->get_allowed_bases();
1555     return($bases);
1556   } 
1559   function getCopyDialog()
1560   {
1561     $str = "";
1563     session::set('binary',$this->photoData); 
1564     session::set('binarytype',"image/jpeg");
1566     /* Get random number for pictures */
1567     srand((double)microtime()*1000000); 
1568     $rand = rand(0, 10000);
1570     $smarty = get_smarty();
1572     $smarty->assign("passwordTodo","clear");
1574     if(isset($_POST['passwordTodo'])){
1575       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1576     }
1578     $smarty->assign("sn",       $this->sn);
1579     $smarty->assign("givenName",$this->givenName);
1580     $smarty->assign("uid",      $this->uid);
1581     $smarty->assign("rand",     $rand);
1582     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1585     $ret = array();
1586     $ret['string'] = $str;
1587     $ret['status'] = "";  
1588     return($ret);
1589   }
1591   function saveCopyDialog()
1592   {
1593     /* Set_acl_base */
1594     $this->set_acl_base($this->base);
1596     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1597       $this->set_picture($_FILES['picture_file']['tmp_name']);
1598     }
1600     /* Remove picture? */
1601     if (isset($_POST['picture_remove'])){
1602       $this->jpegPhoto= "*removed*";
1603       $this->set_picture ("./plugins/users/images/default.jpg");
1604       $this->is_modified= TRUE;
1605     }
1607     $attrs = array("uid","givenName","sn");
1608     foreach($attrs as $attr){
1609       if(isset($_POST[$attr])){
1610         $this->$attr = $_POST[$attr];
1611       }
1612     } 
1613   }
1616   function PrepareForCopyPaste($source)
1617   {
1618     plugin::PrepareForCopyPaste($source);
1620     /* Reset certificate information addepted from source user
1621        to avoid setting the same user certificate for the destination user. */
1622     $this->userPKCS12= "";
1623     $this->userSMIMECertificate= "";
1624     $this->userCertificate= "";
1625     $this->certificateSerialNumber= "";
1626     $this->old_certificateSerialNumber= "";
1627     $this->old_userPKCS12= "";
1628     $this->old_userSMIMECertificate= "";
1629     $this->old_userCertificate= "";
1630   }
1633   static function plInfo()
1634   {
1635   
1636     $govattrs= array(
1637         "gouvernmentOrganizationalUnit"             =>  _("Unit"), 
1638         "houseIdentifier"                           =>  _("House identifier"), 
1639         "vocation"                                  =>  _("Vocation"),
1640         "ivbbLastDeliveryCollective"                =>  _("Last delivery"), 
1641         "gouvernmentOrganizationalPersonLocality"   =>  _("Person locality"),
1642         "gouvernmentOrganizationalUnitDescription"  =>  _("Unit description"),
1643         "gouvernmentOrganizationalUnitSubjectArea"  =>  _("Subject area"),
1644         "functionalTitle"                           =>  _("Functional title"),
1645         "certificateSerialNumber"                   =>  _("Certificate serial number"),
1646         "publicVisible"                             =>  _("Public visible"),
1647         "street"                                    =>  _("Street"),
1648         "role"                                      =>  _("Role"),
1649         "postalCode"                                =>  _("Postal code"));
1651     $ret = array(
1652         "plShortName" => _("Generic"),
1653         "plDescription" => _("Generic user settings"),
1654         "plSelfModify"  => TRUE,
1655         "plDepends"     => array(),
1656         "plPriority"    => 1,
1657         "plSection"     => array("personal" => _("My account")),
1658         "plCategory"    => array("users" => array("description" => _("Users"),
1659                                                   "objectClass" => "gosaAccount")),
1661         "plProvidedAcls" => array(
1663           "sn"                => _("Surname"),
1664           "givenName"         => _("Given name"),
1665           "uid"               => _("User identification"),
1666           "personalTitle"     => _("Personal title"),
1667           "academicTitle"     => _("Academic title"),
1669           "dateOfBirth"       => _("Date of birth"),
1670           "gender"            => _("Sex"),
1671           "preferredLanguage" => _("Preferred language"),
1672           "base"              => _("Base"), 
1674           "userPicture"       => _("User picture"),
1676           "gosaLoginRestriction" => _("Login restrictions"),         
1678           "o"                 => _("Organization"),
1679           "ou"                => _("Department"),
1680           "departmentNumber"  => _("Department number"),
1681           "manager"           => _("Manager"),
1682           "employeeNumber"    => _("Employee number"),
1683           "employeeType"      => _("Employee type"),
1685           "roomNumber"        => _("Room number"),
1686           "telephoneNumber"   => _("Telefon number"),
1687           "pager"             => _("Pager number"),
1688           "mobile"            => _("Mobile number"),
1689           "facsimileTelephoneNumber"     => _("Fax number"),
1691           "st"                => _("State"),
1692           "l"                 => _("Location"),
1693           "postalAddress"     => _("Postal address"),
1695           "homePostalAddress" => _("Home postal address"),
1696           "homePhone"         => _("Home phone number"),
1697           "labeledURI"        => _("Homepage"),
1698           "userPassword"      => _("User password method"), 
1699           "Certificate"       => _("User certificates"))
1701         );
1703     /* Append government attributes if required */
1704     global $config;
1705     if($config->get_cfg_value("honourIvbbAttributes") == "true"){
1706       foreach($govattrs as $attr => $desc){
1707         $ret["plProvidedAcls"][$attr] = $desc;
1708       }
1709     }
1710     return($ret);
1711   }
1713   function get_multi_edit_values()
1714   {
1715     $ret = plugin::get_multi_edit_values();
1716     if(in_array("pw_storage",$this->multi_boxes)){
1717       $ret['pw_storage'] = $this->pw_storage;
1718     }
1719     if(in_array("edit_picture",$this->multi_boxes)){
1720       $ret['jpegPhoto'] = $this->jpegPhoto;
1721       $ret['photoData'] = $this->photoData;
1722       $ret['old_jpegPhoto'] = $this->old_jpegPhoto;
1723       $ret['old_photoData'] = $this->old_photoData;
1724     }
1725     if(isset($ret['dateOfBirth'])){
1726       unset($ret['dateOfBirth']);
1727     }
1728     if(isset($ret['cn'])){
1729       unset($ret['cn']);
1730     }
1731     $ret['is_modified'] = $this->is_modified;
1732     if(in_array("base",$this->multi_boxes)){
1733       $ret['orig_base']="Changed_by_Multi_Plug";
1734       $ret['base']=$this->base;
1735     }
1737     $ret['gosaLoginRestriction'] = $this->gosaLoginRestriction;
1738     $ret['gosaLoginRestriction_some'] = $this->gosaLoginRestriction_some;
1740     return($ret); 
1741   }
1744   function multiple_save_object()
1745   {
1746     plugin::multiple_save_object();
1748     /* Get pw_storage mode */
1749     if (isset($_POST['pw_storage'])){
1750       foreach(array("pw_storage") as $val){
1751         if(isset($_POST[$val])){
1752           $data= validate(get_post($val));
1753           if ($data != $this->$val){
1754             $this->is_modified= TRUE;
1755           }
1756           $this->$val= $data;
1757         }
1758       }
1759     }
1760   
1761     /* Refresh base */
1762     if ($this->acl_is_moveable($this->base)){
1763       if (!$this->baseSelector->update()) {
1764         msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
1765       }
1766       if ($this->base != $this->baseSelector->getBase()) {
1767         $this->base= $this->baseSelector->getBase();
1768       }
1769     }
1771     if(isset($_POST['user_mulitple_edit'])){
1772       foreach(array("base","pw_storage","edit_picture") as $val){
1773         if(isset($_POST["use_".$val])){
1774           $this->multi_boxes[] = $val;
1775         }
1776       }
1777     }
1779     /* Sync lists */
1780     $this->gosaLoginRestrictionWidget->save_object();
1781     if ($this->gosaLoginRestrictionWidget->isModified()) {
1782       $this->gosaLoginRestriction= array_values($this->gosaLoginRestrictionWidget->getMaintainedData());
1783     }
1784   }
1786   
1787   function multiple_check()
1788   {
1789     /* Call check() to set new_dn correctly ... */
1790     $message = plugin::multiple_check();
1792     /* Set the new acl base */
1793     if($this->dn == "new") {
1794       $this->set_acl_base($this->base);
1795     }
1796     if (!tests::is_url($this->labeledURI) && in_array("labeledURI",$this->multi_boxes)){
1797       $message[]= msgPool::invalid(_("Homepage"));
1798     }
1799     if (!tests::is_phone_nr($this->telephoneNumber) && in_array("telephoneNumber",$this->multi_boxes)){
1800       $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
1801     }
1802     if (!tests::is_phone_nr($this->facsimileTelephoneNumber) &&  in_array("facsimileTelephoneNumber",$this->multi_boxes)){
1803       $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
1804     }
1805     if (!tests::is_phone_nr($this->mobile) && in_array("mobile",$this->multi_boxes)){
1806       $message[]= msgPool::invalid(_("Mobile"), $this->mobile, "/[\/0-9 ()+*-]/");
1807     }
1808     if (!tests::is_phone_nr($this->pager) && in_array("pager",$this->multi_boxes)){
1809       $message[]= msgPool::invalid(_("Pager"), $this->pager, "/[\/0-9 ()+*-]/");
1810     }
1811     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->givenName) && in_array("givenName",$this->multi_boxes)){
1812       $message[]= msgPool::invalid(_("Given name"), $this->giveName, '/[^,+"?\'()=<>;\\\\]/');
1813     }
1814     if (preg_match ('/[,+"?\'()=<>;\\\\]/', $this->sn) && in_array("sn",$this->multi_boxes)){
1815       $message[]= msgPool::invalid(_("Name"), $this->sn, '/[^,+"?\'()=<>;\\\\]/');
1816     }
1817     return($message);
1818   }
1822   function multiple_execute()
1823   {
1824     return($this->execute());
1825   }
1828   /*! \brief  Prepares the plugin to be used for multiple edit
1829    *          Update plugin attributes with given array of attribtues.
1830    *  \param  array   Array with attributes that must be updated.
1831    */
1832   function init_multiple_support($attrs,$all)
1833   {
1834     plugin::init_multiple_support($attrs,$all);
1836     // Get login restrictions
1837     if(isset($attrs['gosaLoginRestriction'])){
1838       $this->gosaLoginRestriction  =array();
1839       for($i =0;$i < $attrs['gosaLoginRestriction']['count']; $i++){
1840         $this->gosaLoginRestriction[] = $attrs['gosaLoginRestriction'][$i];
1841       }
1842     }
1844     // Detect login restriction not used in all user objects.
1845     $this->gosaLoginRestriction_some = array();
1846     if(isset($all['gosaLoginRestriction'])){
1847       for($i=0;$i<$all['gosaLoginRestriction']['count'];$i++){
1848         $this->gosaLoginRestriction_some[] = $all['gosaLoginRestriction'][$i];
1849       }
1850     }
1853     // Reinit the login restriction list.
1854     $data = $this->convertLoginRestriction();
1855     if(count($data)){
1856       $this->gosaLoginRestrictionWidget->setListData($data['data'], $data['displayData']);
1857     }
1858   }
1861   function set_multi_edit_values($attrs)
1862   {
1863     $lR = array();
1865     // Update loginRestrictions, keep my settings while ip is optional
1866     foreach($attrs['gosaLoginRestriction_some'] as $ip){
1867       if(in_array($ip, $this->gosaLoginRestriction) && in_array($ip, $attrs['gosaLoginRestriction'])){
1868         $lR[] = $ip;
1869       }
1870     }
1872     // Add enforced loginRestrictions 
1873     foreach($attrs['gosaLoginRestriction'] as $ip){
1874       $lR[] = $ip;
1875     }
1877     $lR = array_values(array_unique($lR));
1878     $this->is_modified |=  array_differs($this->gosaLoginRestriction, $lR);
1879     plugin::set_multi_edit_values($attrs);
1880     $this->gosaLoginRestriction = $lR;
1881   }
1884   function convertLoginRestriction()
1885   {
1886     $all = array_unique(array_merge($this->gosaLoginRestriction,$this->gosaLoginRestriction_some));
1887     $data = array();
1888     foreach($all as $ip){
1889       $data['data'][] = $ip;
1890       if(!in_array($ip, $this->gosaLoginRestriction)){
1891         $data['displayData'][] = array('mode' => LIST_MARKED , 'data' => array($ip.' ('._("Entries differ").')'));
1892       }else{
1893         $data['displayData'][] = array('mode' => 0 , 'data' => array($ip));
1894       }
1895     }   
1896     return($data);
1897   }
1900 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1901 ?>