Code

9f216a9575fa82dec047d274cdf18a5de813796d
[gosa.git] / plugins / personal / generic / class_user.inc
1 <?php
2 /*!
3   \brief   user plugin
4   \author  Cajus Pollmeier <pollmeier@gonicus.de>
5   \version 2.00
6   \date    24.07.2003
8   This class provides the functionality to read and write all attributes
9   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
10   from/to the LDAP. It does syntax checking and displays the formulars required.
11  */
13 class user extends plugin
14 {
15   /* Definitions */
16   var $plHeadline= "Generic";
17   var $plDescription= "This does something";
19   /* CLI vars */
20   var $cli_summary= "Handling of GOsa's user base object";
21   var $cli_description= "Some longer text\nfor help";
22   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
24   /* Plugin specific values */
25   var $base= "";
26   var $cn= "";
27   var $personalTitle= "";
28   var $academicTitle= "";
29   var $homePostalAddress= "";
30   var $homePhone= "";
31   var $labeledURI= "";
32   var $o= "";
33   var $ou= "";
34   var $departmentNumber= "";
35   var $employeeNumber= "";
36   var $employeeType= "";
37   var $roomNumber= "";
38   var $telephoneNumber= "";
39   var $facsimileTelephoneNumber= "";
40   var $mobile= "";
41   var $pager= "";
42   var $l= "";
43   var $st= "";
44   var $postalAddress= "";
45   var $dob= "0";
46   var $use_dob= "0";
47   var $gender= "0";
49   var $jpegPhoto= "*removed*";
50   var $photoData= "";
51   var $old_jpegPhoto= "";
52   var $old_photoData= "";
53   var $cert_dialog= FALSE;
54   var $picture_dialog= FALSE;
56   var $userPKCS12= "";
57   var $userSMIMECertificate= "";
58   var $userCertificate= "";
59   var $certificateSerialNumber= "";
60   var $old_certificateSerialNumber= "";
61   var $old_userPKCS12= "";
62   var $old_userSMIMECertificate= "";
63   var $old_userCertificate= "";
65   var $gouvernmentOrganizationalUnit= "";
66   var $houseIdentifier= "";
67   var $street= "";
68   var $postalCode= "";
69   var $vocation= "";
70   var $ivbbLastDeliveryCollective= "";
71   var $gouvernmentOrganizationalPersonLocality= "";
72   var $gouvernmentOrganizationalUnitDescription= "";
73   var $gouvernmentOrganizationalUnitSubjectArea= "";
74   var $functionalTitle= "";
75   var $role= "";
76   var $publicVisible= "";
78   /* variables to trigger password changes */
79   var $pw_storage= "crypt";
80   var $last_pw_storage= "unset";
81   var $had_userCertificate= FALSE;
83   /* attribute list for save action */
84   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
85       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dob", "gender",
86       "departmentNumber", "employeeNumber", "employeeType", "l", "st",
87       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
88       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
90   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
91       "gosaAccount");
93   /* attributes that are part of the government mode */
94   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
95       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
96       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
97       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
98       "postalCode");
101   /* constructor, if 'dn' is set, the node loads the given
102      'dn' from LDAP */
103   function user ($config, $dn= NULL)
104   {
105     /* Configuration is fine, allways */
106     $this->config= $config;
108     /* Load base attributes */
109     plugin::plugin ($config, $dn);
111     /* Load government mode attributes */
112     if ($this->config->current['GOVERNMENTMODE']){
114       /* Copy all attributs */
115       foreach ($this->govattrs as $val){
116         if (isset($this->attrs["$val"][0])){
117           $this->$val= $this->attrs["$val"][0];
118         }
119       }
121       /* Fix public visible attribute if unset */
122       if (!isset($this->attrs['publicVisible'])){
123         $this->publicVisible == "nein";
124       }
126     }
128     /* Create me for new accounts */
129     if ($dn == "new"){
130       $this->is_account= TRUE;
131     }
133     /* Make hash default to md5 if not set in config */
134     if (!isset($this->config->current['HASH'])){
135       $hash= "md5";
136     } else {
137       $hash= $this->config->current['HASH'];
138     }
140     /* Load data from LDAP? */
141     if ($dn != NULL){
143       /* Do base conversation */
144       if ($this->dn == "new"){
145         $ui= get_userinfo();
146         $this->base= dn2base($ui->dn);
147       } else {
148         $this->base= dn2base($dn);
149       }
151       /* get password storage type */
152       if (isset ($this->attrs['userPassword'][0])){
153         /* Initialize local array */
154         $matches= array();
155         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
156           $this->pw_storage= strtolower($matches[1]);
157         } else {
158           if ($this->attrs['userPassword'][0] != ""){
159             $this->pw_storage= "clear";
160           } else {
161             $this->pw_storage= $hash;
162           }
163         }
164       } else {
165         /* Preset with vaule from configuration */
166         $this->pw_storage= $hash;
167       }
169       /* Load extra attributes: certificate and picture */
170       $this->load_picture();
171       $this->load_cert();
172       if ($this->userCertificate != ""){
173         $this->had_userCertificate= TRUE;
174       }
175     }
177     /* Reset password storage indicator, used by password_change_needed() */
178     if ($dn == "new"){
179       $this->last_pw_storage= "unset";
180     } else {
181       $this->last_pw_storage= $this->pw_storage;
182     }
184     /* Generate dob entry */
185     if (isset ($this->attrs['dateOfBirth'])){
186       /* This entry is ISO 8601 conform */
187       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
188     
189       $this->dob=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
190       $this->use_dob= "1";
191     } else {
192       $this->use_dob= "0";
193     }
195     /* Put gender attribute to upper case */
196     if (isset ($this->attrs['gender'])){
197       $this->gender= strtoupper($this->attrs['gender'][0]);
198     }   
199   }
202   /* execute generates the html output for this node */
203   function execute()
204   {
205     $smarty= get_smarty();
207     /* Fill calendar */
208     if ($this->dob == "0"){
209       $date= getdate();
210     } else {
211       if(is_array($this->dob)){
212         $date = $this->dob;
213       }else{
214         $date = getdate($this->dob);
215       } 
216     }
218     $days= array();
219     for($d= 1; $d<32; $d++){
220       $days[$d]= $d;
221     }
222     $years= array();
224     if(($date['year']-100)<1901){
225       $start = 1901;
226     }else{
227       $start = $date['year']-100;
228     }
230     $end = $start +100;
231     
232     for($y= $start; $y<=$end; $y++){
233       $years[]= $y;
234     }
235     $years['-']= "-&nbsp;";
236     $months= array(_("January"), _("February"), _("March"), _("April"),
237         _("May"), _("June"), _("July"), _("August"), _("September"),
238         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
239     $smarty->assign("day", $date["mday"]);
240     $smarty->assign("days", $days);
241     $smarty->assign("months", $months);
242     $smarty->assign("month", $date["mon"]-1);
243     $smarty->assign("years", $years);
244     $smarty->assign("year", $date["year"]);
246     /* Assign sex */
247     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
248     $smarty->assign("gender_list", $sex);
250     /* Get random number for pictures */
251     srand((double)microtime()*1000000); 
252     $smarty->assign("rand", rand(0, 10000));
254     /* Do we represent a valid gosaAccount? */
255     if (!$this->is_account){
256       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
257         _("This account has no valid GOsa extensions.")."</b>";
258       return;
259     }
261     /* Want picture edit dialog? */
262     if (isset($_POST['edit_picture'])){
263       /* Save values for later recovery, in case some presses
264          the cancel button. */
265       $this->old_jpegPhoto= $this->jpegPhoto;
266       $this->old_photoData= $this->photoData;
267       $this->picture_dialog= TRUE;
268       $this->dialog= TRUE;
269     }
271     /* Remove picture? */
272     if (isset($_POST['picture_remove'])){
273       $this->jpegPhoto= "*removed*";
274       $this->set_picture ("./images/default.jpg");
275       $this->is_modified= TRUE;
277       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
278     }
280     /* Save picture */
281     if (isset($_POST['picture_edit_finish'])){
283       /* Check for clean upload */
284       if ($_FILES['picture_file']['name'] != ""){
285         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
286           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
287           exit;
288         }
290         /* Activate new picture */
291         $this->set_picture($_FILES['picture_file']['tmp_name']);
292       }
293       $this->picture_dialog= FALSE;
294       $this->dialog= FALSE;
295       $this->is_modified= TRUE;
296     }
299     /* Cancel picture */
300     if (isset($_POST['picture_edit_cancel'])){
302       /* Restore values */
303       $this->jpegPhoto= $this->old_jpegPhoto;
304       $this->photoData= $this->old_photoData;
306       /* Update picture */
307       $_SESSION['picture']= $this->photoData;
308       $this->picture_dialog= FALSE;
309       $this->dialog= FALSE;
310     }
312     /* Toggle dob information */
313     if (isset($_POST['set_dob'])){
314       $this->use_dob= ($this->use_dob == "0")?"1":"0";
315     }
318     /* Want certificate= */
319     if (isset($_POST['edit_cert'])){
321       /* Save original values for later reconstruction */
322       foreach (array("certificateSerialNumber", "userCertificate",
323             "userSMIMECertificate", "userPKCS12") as $val){
325         $oval= "old_$val";
326         $this->$oval= $this->$val;
327       }
329       $this->cert_dialog= TRUE;
330       $this->dialog= TRUE;
331     }
334     /* Cancel certificate dialog */
335     if (isset($_POST['cert_edit_cancel'])){
337       /* Restore original values in case of 'cancel' */
338       foreach (array("certificateSerialNumber", "userCertificate",
339             "userSMIMECertificate", "userPKCS12") as $val){
341         $oval= "old_$val";
342         $this->$val= $this->$oval;
343       }
344       $this->cert_dialog= FALSE;
345       $this->dialog= FALSE;
346     }
349     /* Remove certificate? */
350     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
351       if (isset($_POST["remove_$val"])){
353         /* Reset specified cert*/
354         $this->$val= "";
355         $this->is_modified= TRUE;
356       }
357     }
360     /* Upload new cert and close dialog? */     
361     if (isset($_POST['cert_edit_finish'])){
363       /* for all certificates do */
364       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
365           as $val){
367         /* Check for clean upload */
368         if (array_key_exists($val."_file", $_FILES) &&
369             array_key_exists('name', $_FILES[$val."_file"]) &&
370             $_FILES[$val."_file"]['name'] != "" &&
371             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
372           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
373         }
374       }
376       /* Save serial number */
377       if (isset($_POST["certificateSerialNumber"]) &&
378           $_POST["certificateSerialNumber"] != ""){
380         if (!is_id($_POST["certificateSerialNumber"])){
381           print_red (_("Please enter a valid serial number"));
383           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
384             if ($this->$cert != ""){
385               $smarty->assign("$cert"."_state", "true");
386             } else {
387               $smarty->assign("$cert"."_state", "");
388             }
389           }
390           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
391         }
393         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
394         $this->is_modified= TRUE;
395       }
397       $this->cert_dialog= FALSE;
398       $this->dialog= FALSE;
399     }
401     /* Display picture dialog */
402     if ($this->picture_dialog){
403       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
404     }
406     /* Display cert dialog */
407     if ($this->cert_dialog){
408       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
409         if ($this->$cert != ""){
410           /* import certificate */
411           $certificate = new certificate;
412           $certificate->import($this->$cert);
413       
414           /* Read out data*/
415           $timeto   = $certificate->getvalidto_date();
416           $timefrom = $certificate->getvalidfrom_date();
417           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
418                   sprintf(_("Certificate is valid from <b>%s</b> to <b>%s</b> and is currently <b>%s</b>."), date('d M Y',$timefrom),date('d M Y',$timeto), $certificate->isvalid()?"<font style='color:green'>"._("valid")."</font>":"<font style='color:red'>"._("invalid")."</font>");
419           $smarty->assign($cert."info",$str);
420           $smarty->assign($cert."_state","true");
421         } else {
422           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
423           $smarty->assign($cert."_state","");
424         }
425       }
426       $smarty->assign("governmentmode", "false");
427       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
428     }
430     /* Show us the edit screen */
431     $smarty->assign("bases", $this->config->idepartments);
432     $smarty->assign("base_select", $this->base);
433     $smarty->assign("selectmode", chkacl($this->acl, "create"));
434     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
435     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
437     /* Prepare password hashes */
438     if ($this->pw_storage == ""){
439       $this->pw_storage= $this->config->current['HASH'];
440     }
442     $temp   = passwordMethod::get_available_methods();
443     $hashes = $temp['name'];
444     
445     $smarty->assign("pwmode", $hashes);
446     $smarty->assign("pwmode_select", $this->pw_storage);
447     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
449     /* Load attributes and acl's */
450     foreach($this->attributes as $val){
451       $smarty->assign("$val", $this->$val);
452       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
453     }
455     /* Save government mode attributes */
456     if (isset($this->config->current['GOVERNMENTMODE']) &&
457         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
458       $smarty->assign("governmentmode", "true");
459       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
460           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
461       $smarty->assign("ivbbmodes", $ivbbmodes);
462       foreach ($this->govattrs as $val){
463         $smarty->assign("$val", $this->$val);
464         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
465       }
466     } else {
467       $smarty->assign("governmentmode", "false");
468     }
470     /* Special mode for uid */
471     $uidACL= "";
472     if (isset ($this->dn)){
473       if ($this->dn != "new"){
474         $uidACL="readonly";
475       }
476     }  else {
477       $uidACL= "readonly";
478     }
479     $uidACL.= " ".chkacl($this->acl, "uid");
480     
481     $smarty->assign("uidACL", $uidACL);
482     $smarty->assign("is_template", $this->is_template);
483     $smarty->assign("use_dob", $this->use_dob);
485     if (isset($this->parent)){
486       if (isset($this->parent->by_object['phoneAccount']) &&
487           $this->parent->by_object['phoneAccount']->is_account){
488         $smarty->assign("has_phoneaccount", "true");
489       } else {
490         $smarty->assign("has_phoneaccount", "false");
491       }
492     } else {
493         $smarty->assign("has_phoneaccount", "false");
494     }
496     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
497   }
500   /* remove object from parent */
501   function remove_from_parent()
502   {
503     $ldap= $this->config->get_ldap_link();
504     $ldap->rmdir ($this->dn);
506     /* Delete references to groups */
507     $ldap->cd ($this->config->current['BASE']);
508     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
509     while ($ldap->fetch()){
510       $g= new group($this->config, $ldap->getDN());
511       $g->removeUser($this->uid);
512       $g->save ();
513     }
515     /* Delete references to object groups */
516     $ldap->cd ($this->config->current['BASE']);
517     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
518     while ($ldap->fetch()){
519       $og= new ogroup($this->config, $ldap->getDN());
520       unset($og->member[$this->dn]);
521       $og->save ();
522     }
524     /* Optionally execute a command after we're done */
525     $this->handle_post_events("remove");
526   }
529   /* Save data to object */
530   function save_object()
531   {
532     if (isset($_POST['generic'])){
534       /* Parents save function */
535       plugin::save_object ();
537       /* Save government mode attributes */
538       if ($this->config->current['GOVERNMENTMODE']){
539         foreach ($this->govattrs as $val){
540           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
541             $data= stripcslashes($_POST["$val"]);
542             if ($data != $this->$val){
543               $this->is_modified= TRUE;
544             }
545             $this->$val= $data;
546           }
547         }
548       }
550       /* In template mode, the uid is autogenerated... */
551       if ($this->is_template){
552         $this->uid= strtolower($this->sn);
553         $this->givenName= $this->sn;
554       }
556       /* Save base and pw_storage, since these are no LDAP attributes */
557       if (isset($_POST['base'])){
558         foreach(array("base", "pw_storage") as $val){
559           $data= validate($_POST[$val]);
560           if ($data != $this->$val){
561             $this->is_modified= TRUE;
562           }
563           $this->$val= $data;
564         }
565       }
566     }
567   }
569   function rebind($ldap, $referral)
570   {
571     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
572     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
573       $this->error = "Success";
574       $this->hascon=true;
575       $this->reconnect= true;
576       return (0);
577     } else {
578       $this->error = "Could not bind to " . $credentials['ADMIN'];
579       return NULL;
580     }
581   }
583   /* Save data to LDAP, depending on is_account we save or delete */
584   function save()
585   {
586     /* First use parents methods to do some basic fillup in $this->attrs */
587     plugin::save ();
589     /* Remove additional objectClasses */
590     $tmp= array();
591     foreach ($this->attrs['objectClass'] as $key => $set){
592       $found= false;
593       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
594         if (preg_match ("/^$set$/i", $val)){
595           $found= true;
596           break;
597         }
598       }
599       if (!$found){
600         $tmp[]= $set;
601       }
602     }
604     /* Replace the objectClass array. This is done because of the
605        separation into government and normal mode. */
606     $this->attrs['objectClass']= $tmp;
608     /* Add objectClasss for template mode? */
609     if ($this->is_template){
610       $this->attrs['objectClass'][]= "gosaUserTemplate";
611     }
613     /* Hard coded government mode? */
614     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
615       $this->attrs['objectClass'][]= "ivbbEntry";
617       /* Copy standard attributes */
618       foreach ($this->govattrs as $val){
619         if ($this->$val != ""){
620           $this->attrs["$val"]= $this->$val;
621         } elseif (!$this->new) {
622           $this->attrs["$val"]= array();
623         }
624       }
626       /* Remove attribute if set to "nein" */
627       if ($this->publicVisible == "nein"){
628         $this->attrs['publicVisible']= array();
629         if($this->new){
630           unset($this->attrs['publicVisible']);
631         }else{
632           $this->attrs['publicVisible']=array();
633         }
635       }
637     }
639     /* Special handling for attribute userCertificate needed */
640     if ($this->userCertificate != ""){
641       $this->attrs["userCertificate;binary"]= $this->userCertificate;
642       $remove_userCertificate= false;
643     } else {
644       $remove_userCertificate= true;
645     }
647     /* Special handling for dob value */
648     if ($this->use_dob == "1"){
649       $this->attrs["dob"]= date("Y-m-d", $this->dob);
650     } else {
651       if ($this->new) {
652         unset($this->attrs["dob"]);
653       } else {
654         $this->attrs["dob"]= array();
655       }
656     }
657     if ($this->gender == "0"){
658       if ($this->new) {
659         unset($this->attrs["gender"]);
660       } else {
661         $this->attrs["gender"]= array();
662       }
663     }
665     /* Special handling for attribute jpegPhote needed, scale image via
666        image magick to 147x200 pixels and inject resulting data. */
667     if ($this->jpegPhoto != "*removed*"){
669       /* Fallback if there's no image magick inside PHP */
670       if (!function_exists("imagick_blob2image")){
671         /* Get temporary file name for conversation */
672         $fname = tempnam ("/tmp", "GOsa");
674         /* Open file and write out photoData */
675         $fp = fopen ($fname, "w");
676         fwrite ($fp, $this->photoData);
677         fclose ($fp);
679         /* Build conversation query. Filename is generated automatically, so
680            we do not need any special security checks. Exec command and save
681            output. For PHP safe mode, you'll need a configuration which respects
682            image magick as executable... */
683         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
684         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
685             $query, "Execute");
687         /* Read data written by convert */
688         $output= "";
689         $sh= popen($query, 'r');
690         while (!feof($sh)){
691           $output.= fread($sh, 4096);
692         }
693         pclose($sh);
695         unlink($fname);
697         /* Save attribute */
698         $this->attrs["jpegPhoto"] = $output;
700       } else {
702         /* Load the new uploaded Photo */
703         if(!$handle  =  imagick_blob2image($this->photoData))  {
704           gosa_log("Can't Load image");
705         }
707         /* Resizing image to 147x200 and blur */
708         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
709           gosa_log("imagick_resize failed");
710         }
712         /* Converting image to JPEG */
713         if(!imagick_convert($handle,"JPEG")) {
714           gosa_log("Can't Convert to JPEG");
715         }
717         /* Creating binary Code for the Image */
718         if(!$dump = imagick_image2blob($handle)){
719           gosa_log("Can't create blob for image");
720         }
722         /* Sending Image */
723         $output=  $dump;
725         /* Save attribute */
726         $this->attrs["jpegPhoto"] = $output;
727       }
729     } elseif(!$this->new) {
730       $this->attrs["jpegPhoto"] = array();
731     }
733     /* Build new dn */
734     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
735       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
736     } else {
737       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
738     }
740     /* This only gets called when user is renaming himself */
741     $ldap= $this->config->get_ldap_link();
742     if ($this->dn != $new_dn){
744       /* Write entry on new 'dn' */
745       $this->move($this->dn, $new_dn);
747       /* Happen to use the new one */
748       change_ui_dn($this->dn, $new_dn);
749       $this->dn= $new_dn;
750     }
753     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
754        new entries. So do a check first... */
755     $ldap->cat ($this->dn);
756     if ($ldap->fetch()){
757       $mode= "modify";
758     } else {
759       $mode= "add";
760       $ldap->cd($this->config->current['BASE']);
761       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
762     }
764     /* Set password to some junk stuff in case of templates */
765     if ($this->is_template){
766       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
767     }
769     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
770         $this->attributes, "Save via $mode");
772     /* Finally write data with selected 'mode' */
773     $ldap->cd ($this->dn);
774     $ldap->$mode ($this->attrs);
775     if (show_ldap_error($ldap->get_error())){
776       return (1);
777     }
779     /* Remove cert? 
780        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
781        to work around myself. */
782     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
784       /* Reset array, assemble new, this should be reworked */
785       $this->attrs= array();
786       $this->attrs['userCertificate;binary']= array();
788       /* Prepare connection */
789       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
790         die ("Could not connect to LDAP server");
791       }
792       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
793       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
794         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
795         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
796       }
797       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
798         ldap_start_tls($ds);
799       }
800       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
801               $this->config->current['PASSWORD']))) {
802         die ("Could not bind to LDAP");
803       }
805       /* Modify using attrs */
806       ldap_mod_del($ds,$this->dn,$this->attrs);
807       ldap_close($ds);
808     }
810     /* Kerberos server defined? */
811     if (isset($this->config->data['SERVERS']['KERBEROS'])){
812       $cfg= $this->config->data['SERVERS']['KERBEROS'];
813     }
814     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
816       /* Connect to the admin interface */
817       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
818           $cfg['ADMIN'], $cfg['PASSWORD']);
820       /* Errors? */             
821       if ($handle === FALSE){
822         print_red (_("Kerberos database communication failed"));
823         return (2);
824       }
826       /* Build user principal, get list of existsing principals */
827       $principal= $this->uid."@".$cfg['REALM'];
828       $principals = kadm5_get_principals($handle);
830       /* User exists in database? */
831       if (in_array($principal, $principals)){
833         /* Ok. User exists. Remove him/her when pw_storage has
834            changed to be NOT kerberos. */
835         if ($this->pw_storage != "kerberos"){
836           $ret= kadm5_delete_principal ( $handle, $principal);
838           if ($ret === FALSE){
839             print_red (_("Can't remove user from kerberos database."));
840           }
841         }
843       } else {
845         /* User doesn't exists, create it when pw_storage is kerberos. */
846         if ($this->pw_storage == "kerberos"){
847           $ret= kadm5_create_principal ( $handle, $principal);
849           if ($ret === FALSE){
850             print_red (_("Can't add user to kerberos database."));
851           }
852         }
854       }
856       /* Free kerberos admin handle */
857       kadm5_destroy($handle);
858     }
860     /* Optionally execute a command after we're done */
861     if ($mode == "add"){
862       $this->handle_post_events("add");
863     } elseif ($this->is_modified){
864       $this->handle_post_events("modify");
865     }
867     return (0);
868   }
871   /* Check formular input */
872   function check()
873   {
874     $message= array();
876     /* Assemble cn */
877     $this->cn= $this->givenName." ".$this->sn;
879     /* Permissions for that base? */
880     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
881       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
882     } else {
883       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
884     }
886     $ui= get_userinfo();
887     $acl= get_permissions ($new_dn, $ui->subtreeACL);
888     $acl= get_module_permission($acl, "user", $new_dn);
889     if ($this->dn == "new" && chkacl($acl, "create") != ""){
890       $message[]= _("You have no permissions to create a user on this 'Base'.");
891     } elseif ($this->dn != $new_dn && $this->dn != "new"){
892       $acl= get_permissions ($this->dn, $ui->subtreeACL);
893       $acl= get_module_permission($acl, "user", $this->dn);
894       if (chkacl($acl, "create") != ""){
895         $message[]= _("You have no permissions to move a user from the original 'Base'.");
896       }
897     }
899     /* must: sn, givenName, uid */
900     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
901       $message[]= _("The required field 'Name' is not set.");
902     }
904     /* UID already used? */
905     $ldap= $this->config->get_ldap_link();
906     $ldap->cd($this->config->current['BASE']);
907     $ldap->search("(uid=$this->uid)", array("uid"));
908     $ldap->fetch();
909     if ($ldap->count() != 0 && $this->dn == 'new'){
910       $message[]= _("There's already a person with this 'Login' in the database.");
911     }
913     /* In template mode, the uid and givenName are autogenerated... */
914     if (!$this->is_template){
915       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
916         $message[]= _("The required field 'Given name' is not set.");
917       }
918       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
919         $message[]= _("The required field 'Login' is not set.");
920       }
921       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
922         $ldap->cd($this->config->current['BASE']);
923         $ldap->search("(cn=".$this->cn.")", array("uid"));
924         $ldap->fetch();
925         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
926           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
927         }
928       }
929     }
931     /* Check for valid input */
932     if ($this->is_modified && !is_uid($this->uid)){
933       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
934     }
935     if (!is_url($this->labeledURI)){
936       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
937     }
938     if (preg_match ("/[\\\\]/", $this->sn)){
939       $message[]= _("The field 'Name' contains invalid characters.");
940     }
941     if (preg_match ("/[\\\\]/", $this->givenName)){
942       $message[]= _("The field 'Given name' contains invalid characters.");
943     }
945     /* Check phone numbers */
946     if (!is_phone_nr($this->homePhone)){
947       $message[]= _("The field 'Phone' contains an invalid phone number.");
948     }
949     if (!is_phone_nr($this->telephoneNumber)){
950       $message[]= _("The field 'Phone' contains an invalid phone number.");
951     }
952     if (!is_phone_nr($this->facsimileTelephoneNumber)){
953       $message[]= _("The field 'Fax' contains an invalid phone number.");
954     }
955     if (!is_phone_nr($this->mobile)){
956       $message[]= _("The field 'Mobile' contains an invalid phone number.");
957     }
958     if (!is_phone_nr($this->pager)){
959       $message[]= _("The field 'Pager' contains an invalid phone number.");
960     }
962     /* Check for reserved characers */
963     if (preg_match ('/[,+"?\'()-=<>;]/', $this->givenName)){
964       $message[]= _("The field 'Given name' contains invalid characters.");
965   }
966   if (preg_match ('/[,+"?\'()-=<>;]/', $this->sn)){
967     $message[]= _("The field 'Name' contains invalid characters.");
968   }
970   return $message;
971   }
974   /* Indicate whether a password change is needed or not */
975   function password_change_needed()
976   {
977     return ($this->pw_storage != $this->last_pw_storage);
978   }
981   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
982   function load_picture()
983   {
984     /* make connection and read jpegPhoto */
985     $ds= ldap_connect($this->config->current['SERVER']);
986     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
987     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
988       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
989       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
990     }
992     if(isset($this->config->current['TLS']) &&
993         $this->config->current['TLS'] == "true"){
995       ldap_start_tls($ds);
996     }
998     $r= ldap_bind($ds);
999     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1001     /* in case we don't get an entry, load a default picture */
1002     $this->set_picture ("./images/default.jpg");
1003     $this->jpegPhoto= "*removed*";
1005     /* fill data from LDAP */
1006     if ($sr) {
1007       $ei=ldap_first_entry($ds, $sr);
1008       if ($ei) {
1009         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1010           $this->photoData= $info[0];
1011           $_SESSION['picture']= $this->photoData;
1012           $this->jpegPhoto= "";
1013         }
1014       }
1015     }
1017     /* close conncetion */
1018     ldap_unbind($ds);
1019   }
1022   /* Load a certificate from LDAP, this is going to be simplified later on */
1023   function load_cert()
1024   {
1025     $ds= ldap_connect($this->config->current['SERVER']);
1026     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1027     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1028       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1029       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1030     }
1031     if(isset($this->config->current['TLS']) &&
1032         $this->config->current['TLS'] == "true"){
1034       ldap_start_tls($ds);
1035     }
1037     $r= ldap_bind($ds);
1038     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1040     if ($sr) {
1041       $ei= @ldap_first_entry($ds, $sr);
1042       
1043       if ($ei) {
1044         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1045           $this->userCertificate= "";
1046         } else {
1047           $this->userCertificate= $info[0];
1048         }
1049       }
1050     } else {
1051       $this->userCertificate= "";
1052     }
1054     ldap_unbind($ds);
1055   }
1058   /* Load picture from file to object */
1059   function set_picture($filename)
1060   {
1061     if (!is_file($filename)){
1062       $filename= "./images/default.jpg";
1063       $this->jpegPhoto= "*removed*";
1064     }
1066     $fd = fopen ($filename, "rb");
1067     $this->photoData= fread ($fd, filesize ($filename));
1068     $_SESSION['picture']= $this->photoData;
1069     $this->jpegPhoto= "";
1071     fclose ($fd);
1072   }
1075   /* Load certificate from file to object */
1076   function set_cert($cert, $filename)
1077   {
1078     $fd = fopen ($filename, "rb");
1079     if (filesize($filename)>0) {
1080       $this->$cert= fread ($fd, filesize ($filename));
1081       fclose ($fd);
1082       $this->is_modified= TRUE;
1083     } else {
1084       print_red(_("Could not open specified certificate!"));
1085     }
1086   }
1088   /* Adapt from given 'dn' */
1089   function adapt_from_template($dn)
1090   {
1091     plugin::adapt_from_template($dn);
1093     /* Get base */
1094     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1096     if ($this->config->current['GOVERNMENTMODE']){
1098       /* Walk through govattrs */
1099       foreach ($this->govattrs as $val){
1101         if (isset($this->attrs["$val"][0])){
1103           /* If attribute is set, replace dynamic parts: 
1104              %sn, %givenName and %uid. Fill these in our local variables. */
1105           $value= $this->attrs["$val"][0];
1107           foreach (array("sn", "givenName", "uid") as $repl){
1108             if (preg_match("/%$repl/i", $value)){
1109               $value= preg_replace ("/%$repl/i",
1110                   $this->parent->$repl, $value);
1111             }
1112           }
1113           $this->$val= $value;
1114         }
1115       }
1116     }
1118     /* Get back uid/sn/givenName */
1119     if ($this->parent != NULL){
1120       $this->uid= $this->parent->uid;
1121       $this->sn= $this->parent->sn;
1122       $this->givenName= $this->parent->givenName;
1123     }
1124   }
1128 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1129 ?>