Code

Only check uid if it was modified.
[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       $this->dob= mktime ( 0, 0, 0, $month, $day, $year);
189       $this->use_dob= "1";
190     } else {
191       $this->use_dob= "0";
192     }
194     /* Put gender attribute to upper case */
195     if (isset ($this->attrs['gender'])){
196       $this->gender= strtoupper($this->attrs['gender'][0]);
197     }   
198   }
201   /* execute generates the html output for this node */
202   function execute()
203   {
204     $smarty= get_smarty();
206     /* Fill calendar */
207     if ($this->dob == "0"){
208       $date= getdate();
209     } else {
210       $date= getdate($this->dob);
211     }
213     $days= array();
214     for($d= 1; $d<32; $d++){
215       $days[$d]= $d;
216     }
217     $years= array();
218     for($y= $date['year']-100; $y<=$date['year']+100; $y++){
219       $years[]= $y;
220     }
221     $years['-']= "-&nbsp;";
222     $months= array(_("January"), _("February"), _("March"), _("April"),
223         _("May"), _("June"), _("July"), _("August"), _("September"),
224         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
225     $smarty->assign("day", $date["mday"]);
226     $smarty->assign("days", $days);
227     $smarty->assign("months", $months);
228     $smarty->assign("month", $date["mon"]-1);
229     $smarty->assign("years", $years);
230     $smarty->assign("year", $date["year"]);
232     /* Assign sex */
233     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
234     $smarty->assign("gender_list", $sex);
236     /* Get random number for pictures */
237     srand((double)microtime()*1000000); 
238     $smarty->assign("rand", rand(0, 10000));
240     /* Do we represent a valid gosaAccount? */
241     if (!$this->is_account){
242       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
243         _("This account has no valid GOsa extensions.")."</b>";
244       return;
245     }
247     /* Want picture edit dialog? */
248     if (isset($_POST['edit_picture'])){
249       /* Save values for later recovery, in case some presses
250          the cancel button. */
251       $this->old_jpegPhoto= $this->jpegPhoto;
252       $this->old_photoData= $this->photoData;
253       $this->picture_dialog= TRUE;
254       $this->dialog= TRUE;
255     }
257     /* Remove picture? */
258     if (isset($_POST['picture_remove'])){
259       $this->jpegPhoto= "*removed*";
260       $this->set_picture ("./images/default.jpg");
261       $this->is_modified= TRUE;
263       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
264     }
266     /* Save picture */
267     if (isset($_POST['picture_edit_finish'])){
269       /* Check for clean upload */
270       if ($_FILES['picture_file']['name'] != ""){
271         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
272           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
273           exit;
274         }
276         /* Activate new picture */
277         $this->set_picture($_FILES['picture_file']['tmp_name']);
278       }
279       $this->picture_dialog= FALSE;
280       $this->dialog= FALSE;
281       $this->is_modified= TRUE;
282     }
285     /* Cancel picture */
286     if (isset($_POST['picture_edit_cancel'])){
288       /* Restore values */
289       $this->jpegPhoto= $this->old_jpegPhoto;
290       $this->photoData= $this->old_photoData;
292       /* Update picture */
293       $_SESSION['picture']= $this->photoData;
294       $this->picture_dialog= FALSE;
295       $this->dialog= FALSE;
296     }
298     /* Toggle dob information */
299     if (isset($_POST['set_dob'])){
300       $this->use_dob= ($this->use_dob == "0")?"1":"0";
301     }
304     /* Want certificate= */
305     if (isset($_POST['edit_cert'])){
307       /* Save original values for later reconstruction */
308       foreach (array("certificateSerialNumber", "userCertificate",
309             "userSMIMECertificate", "userPKCS12") as $val){
311         $oval= "old_$val";
312         $this->$oval= $this->$val;
313       }
315       $this->cert_dialog= TRUE;
316       $this->dialog= TRUE;
317     }
320     /* Cancel certificate dialog */
321     if (isset($_POST['cert_edit_cancel'])){
323       /* Restore original values in case of 'cancel' */
324       foreach (array("certificateSerialNumber", "userCertificate",
325             "userSMIMECertificate", "userPKCS12") as $val){
327         $oval= "old_$val";
328         $this->$val= $this->$oval;
329       }
330       $this->cert_dialog= FALSE;
331       $this->dialog= FALSE;
332     }
335     /* Remove certificate? */
336     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
337       if (isset($_POST["remove_$val"])){
339         /* Reset specified cert*/
340         $this->$val= "";
341         $this->is_modified= TRUE;
342       }
343     }
346     /* Upload new cert and close dialog? */     
347     if (isset($_POST['cert_edit_finish'])){
349       /* for all certificates do */
350       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
351           as $val){
353         /* Check for clean upload */
354         if (array_key_exists($val."_file", $_FILES) &&
355             array_key_exists('name', $_FILES[$val."_file"]) &&
356             $_FILES[$val."_file"]['name'] != "" &&
357             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
358           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
359         }
360       }
362       /* Save serial number */
363       if (isset($_POST["certificateSerialNumber"]) &&
364           $_POST["certificateSerialNumber"] != ""){
366         if (!is_id($_POST["certificateSerialNumber"])){
367           print_red (_("Please enter a valid serial number"));
369           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
370             if ($this->$cert != ""){
371               $smarty->assign("$cert"."_state", "true");
372             } else {
373               $smarty->assign("$cert"."_state", "");
374             }
375           }
376           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
377         }
379         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
380         $this->is_modified= TRUE;
381       }
383       $this->cert_dialog= FALSE;
384       $this->dialog= FALSE;
385     }
387     /* Display picture dialog */
388     if ($this->picture_dialog){
389       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
390     }
392     /* Display cert dialog */
393     if ($this->cert_dialog){
394       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
395         if ($this->$cert != ""){
396           /* import certificate */
397           $certificate = new certificate;
398           $certificate->import($this->$cert);
399       
400           /* Read out data*/
401           $timeto   = $certificate->getvalidto_date();
402           $timefrom = $certificate->getvalidfrom_date();
403           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
404                   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>");
405           $smarty->assign($cert."info",$str);
406           $smarty->assign($cert."_state","true");
407         } else {
408           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
409           $smarty->assign($cert."_state","");
410         }
411       }
412       $smarty->assign("governmentmode", "false");
413       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
414     }
416     /* Show us the edit screen */
417     $smarty->assign("bases", $this->config->idepartments);
418     $smarty->assign("base_select", $this->base);
419     $smarty->assign("selectmode", chkacl($this->acl, "create"));
420     $smarty->assign("certificatesACL", chkacl($this->acl, "certificates"));
421     $smarty->assign("jpegPhotoACL", chkacl($this->acl, "jpegPhoto"));
423     /* Prepare password hashes */
424     if ($this->pw_storage == ""){
425       $this->pw_storage= $this->config->current['HASH'];
426     }
428     $temp   = passwordMethod::get_available_methods();
429     $hashes = $temp['name'];
430     
431     $smarty->assign("pwmode", $hashes);
432     $smarty->assign("pwmode_select", $this->pw_storage);
433     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
435     /* Load attributes and acl's */
436     foreach($this->attributes as $val){
437       $smarty->assign("$val", $this->$val);
438       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
439     }
441     /* Save government mode attributes */
442     if (isset($this->config->current['GOVERNMENTMODE']) &&
443         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
444       $smarty->assign("governmentmode", "true");
445       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
446           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
447       $smarty->assign("ivbbmodes", $ivbbmodes);
448       foreach ($this->govattrs as $val){
449         $smarty->assign("$val", $this->$val);
450         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
451       }
452     } else {
453       $smarty->assign("governmentmode", "false");
454     }
456     /* Special mode for uid */
457     $uidACL= "";
458     if (isset ($this->dn)){
459       if ($this->dn != "new"){
460         $uidACL="readonly";
461       }
462     }  else {
463       $uidACL= "readonly";
464     }
465     $uidACL.= " ".chkacl($this->acl, "uid");
466     
467     $smarty->assign("uidACL", $uidACL);
468     $smarty->assign("is_template", $this->is_template);
469     $smarty->assign("use_dob", $this->use_dob);
471     if (isset($this->parent)){
472       if (isset($this->parent->by_object['phoneAccount']) &&
473           $this->parent->by_object['phoneAccount']->is_account){
474         $smarty->assign("has_phoneaccount", "true");
475       } else {
476         $smarty->assign("has_phoneaccount", "false");
477       }
478     } else {
479         $smarty->assign("has_phoneaccount", "false");
480     }
482     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
483   }
486   /* remove object from parent */
487   function remove_from_parent()
488   {
489     $ldap= $this->config->get_ldap_link();
490     $ldap->rmdir ($this->dn);
492     /* Delete references to groups */
493     $ldap->cd ($this->config->current['BASE']);
494     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
495     while ($ldap->fetch()){
496       $g= new group($this->config, $ldap->getDN());
497       $g->removeUser($this->uid);
498       $g->save ();
499     }
501     /* Delete references to object groups */
502     $ldap->cd ($this->config->current['BASE']);
503     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
504     while ($ldap->fetch()){
505       $og= new ogroup($this->config, $ldap->getDN());
506       unset($og->member[$this->dn]);
507       $og->save ();
508     }
510     /* Optionally execute a command after we're done */
511     $this->handle_post_events("remove");
512   }
515   /* Save data to object */
516   function save_object()
517   {
518     if (isset($_POST['generic'])){
520       /* Parents save function */
521       plugin::save_object ();
523       /* Save government mode attributes */
524       if ($this->config->current['GOVERNMENTMODE']){
525         foreach ($this->govattrs as $val){
526           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
527             $data= stripcslashes($_POST["$val"]);
528             if ($data != $this->$val){
529               $this->is_modified= TRUE;
530             }
531             $this->$val= $data;
532           }
533         }
534       }
536       /* In template mode, the uid is autogenerated... */
537       if ($this->is_template){
538         $this->uid= strtolower($this->sn);
539         $this->givenName= $this->sn;
540       }
542       /* Save base and pw_storage, since these are no LDAP attributes */
543       if (isset($_POST['base'])){
544         foreach(array("base", "pw_storage") as $val){
545           $data= validate($_POST[$val]);
546           if ($data != $this->$val){
547             $this->is_modified= TRUE;
548           }
549           $this->$val= $data;
550         }
551       }
552     }
553   }
555   function rebind($ldap, $referral)
556   {
557     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
558     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
559       $this->error = "Success";
560       $this->hascon=true;
561       $this->reconnect= true;
562       return (0);
563     } else {
564       $this->error = "Could not bind to " . $credentials['ADMIN'];
565       return NULL;
566     }
567   }
569   /* Save data to LDAP, depending on is_account we save or delete */
570   function save()
571   {
572     /* First use parents methods to do some basic fillup in $this->attrs */
573     plugin::save ();
575     /* Remove additional objectClasses */
576     $tmp= array();
577     foreach ($this->attrs['objectClass'] as $key => $set){
578       $found= false;
579       foreach (array("ivbbEntry", "gosaUserTemplate") as $val){
580         if (preg_match ("/^$set$/i", $val)){
581           $found= true;
582           break;
583         }
584       }
585       if (!$found){
586         $tmp[]= $set;
587       }
588     }
590     /* Replace the objectClass array. This is done because of the
591        separation into government and normal mode. */
592     $this->attrs['objectClass']= $tmp;
594     /* Add objectClasss for template mode? */
595     if ($this->is_template){
596       $this->attrs['objectClass'][]= "gosaUserTemplate";
597     }
599     /* Hard coded government mode? */
600     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
601       $this->attrs['objectClass'][]= "ivbbEntry";
603       /* Copy standard attributes */
604       foreach ($this->govattrs as $val){
605         if ($this->$val != ""){
606           $this->attrs["$val"]= $this->$val;
607         } elseif (!$this->new) {
608           $this->attrs["$val"]= array();
609         }
610       }
612       /* Remove attribute if set to "nein" */
613       if ($this->publicVisible == "nein"){
614         $this->attrs['publicVisible']= array();
615         if($this->new){
616           unset($this->attrs['publicVisible']);
617         }else{
618           $this->attrs['publicVisible']=array();
619         }
621       }
623     }
625     /* Special handling for attribute userCertificate needed */
626     if ($this->userCertificate != ""){
627       $this->attrs["userCertificate;binary"]= $this->userCertificate;
628       $remove_userCertificate= false;
629     } else {
630       $remove_userCertificate= true;
631     }
633     /* Special handling for dob value */
634     if ($this->use_dob == "1"){
635       $this->attrs["dob"]= date("Y-m-d", $this->dob);
636     } else {
637       if ($this->new) {
638         unset($this->attrs["dob"]);
639       } else {
640         $this->attrs["dob"]= array();
641       }
642     }
643     if ($this->gender == "0"){
644       if ($this->new) {
645         unset($this->attrs["gender"]);
646       } else {
647         $this->attrs["gender"]= array();
648       }
649     }
651     /* Special handling for attribute jpegPhote needed, scale image via
652        image magick to 147x200 pixels and inject resulting data. */
653     if ($this->jpegPhoto != "*removed*"){
655       /* Fallback if there's no image magick inside PHP */
656       if (!function_exists("imagick_blob2image")){
657         /* Get temporary file name for conversation */
658         $fname = tempnam ("/tmp", "GOsa");
660         /* Open file and write out photoData */
661         $fp = fopen ($fname, "w");
662         fwrite ($fp, $this->photoData);
663         fclose ($fp);
665         /* Build conversation query. Filename is generated automatically, so
666            we do not need any special security checks. Exec command and save
667            output. For PHP safe mode, you'll need a configuration which respects
668            image magick as executable... */
669         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
670         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
671             $query, "Execute");
673         /* Read data written by convert */
674         $output= "";
675         $sh= popen($query, 'r');
676         while (!feof($sh)){
677           $output.= fread($sh, 4096);
678         }
679         pclose($sh);
681         unlink($fname);
683         /* Save attribute */
684         $this->attrs["jpegPhoto"] = $output;
686       } else {
688         /* Load the new uploaded Photo */
689         if(!$handle  =  imagick_blob2image($this->photoData))  {
690           gosa_log("Can't Load image");
691         }
693         /* Resizing image to 147x200 and blur */
694         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
695           gosa_log("imagick_resize failed");
696         }
698         /* Converting image to JPEG */
699         if(!imagick_convert($handle,"JPEG")) {
700           gosa_log("Can't Convert to JPEG");
701         }
703         /* Creating binary Code for the Image */
704         if(!$dump = imagick_image2blob($handle)){
705           gosa_log("Can't create blob for image");
706         }
708         /* Sending Image */
709         $output=  $dump;
711         /* Save attribute */
712         $this->attrs["jpegPhoto"] = $output;
713       }
715     } elseif(!$this->new) {
716       $this->attrs["jpegPhoto"] = array();
717     }
719     /* Build new dn */
720     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
721       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
722     } else {
723       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
724     }
726     /* This only gets called when user is renaming himself */
727     $ldap= $this->config->get_ldap_link();
728     if ($this->dn != $new_dn){
730       /* Write entry on new 'dn' */
731       $this->move($this->dn, $new_dn);
733       /* Happen to use the new one */
734       change_ui_dn($this->dn, $new_dn);
735       $this->dn= $new_dn;
736     }
739     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
740        new entries. So do a check first... */
741     $ldap->cat ($this->dn);
742     if ($ldap->fetch()){
743       $mode= "modify";
744     } else {
745       $mode= "add";
746       $ldap->cd($this->config->current['BASE']);
747       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
748     }
750     /* Set password to some junk stuff in case of templates */
751     if ($this->is_template){
752       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
753     }
755     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
756         $this->attributes, "Save via $mode");
758     /* Finally write data with selected 'mode' */
759     $ldap->cd ($this->dn);
760     $ldap->$mode ($this->attrs);
761     if (show_ldap_error($ldap->get_error())){
762       return (1);
763     }
765     /* Remove cert? 
766        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
767        to work around myself. */
768     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
770       /* Reset array, assemble new, this should be reworked */
771       $this->attrs= array();
772       $this->attrs['userCertificate;binary']= array();
774       /* Prepare connection */
775       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
776         die ("Could not connect to LDAP server");
777       }
778       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
779       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
780         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
781         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
782       }
783       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
784         ldap_start_tls($ds);
785       }
786       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
787               $this->config->current['PASSWORD']))) {
788         die ("Could not bind to LDAP");
789       }
791       /* Modify using attrs */
792       ldap_mod_del($ds,$this->dn,$this->attrs);
793       ldap_close($ds);
794     }
796     /* Kerberos server defined? */
797     if (isset($this->config->data['SERVERS']['KERBEROS'])){
798       $cfg= $this->config->data['SERVERS']['KERBEROS'];
799     }
800     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
802       /* Connect to the admin interface */
803       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
804           $cfg['ADMIN'], $cfg['PASSWORD']);
806       /* Errors? */             
807       if ($handle === FALSE){
808         print_red (_("Kerberos database communication failed"));
809         return (2);
810       }
812       /* Build user principal, get list of existsing principals */
813       $principal= $this->uid."@".$cfg['REALM'];
814       $principals = kadm5_get_principals($handle);
816       /* User exists in database? */
817       if (in_array($principal, $principals)){
819         /* Ok. User exists. Remove him/her when pw_storage has
820            changed to be NOT kerberos. */
821         if ($this->pw_storage != "kerberos"){
822           $ret= kadm5_delete_principal ( $handle, $principal);
824           if ($ret === FALSE){
825             print_red (_("Can't remove user from kerberos database."));
826           }
827         }
829       } else {
831         /* User doesn't exists, create it when pw_storage is kerberos. */
832         if ($this->pw_storage == "kerberos"){
833           $ret= kadm5_create_principal ( $handle, $principal);
835           if ($ret === FALSE){
836             print_red (_("Can't add user to kerberos database."));
837           }
838         }
840       }
842       /* Free kerberos admin handle */
843       kadm5_destroy($handle);
844     }
846     /* Optionally execute a command after we're done */
847     if ($mode == "add"){
848       $this->handle_post_events("add");
849     } elseif ($this->is_modified){
850       $this->handle_post_events("modify");
851     }
853     return (0);
854   }
857   /* Check formular input */
858   function check()
859   {
860     $message= array();
862     /* Assemble cn */
863     $this->cn= $this->givenName." ".$this->sn;
865     /* Permissions for that base? */
866     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
867       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
868     } else {
869       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
870     }
872     $ui= get_userinfo();
873     $acl= get_permissions ($new_dn, $ui->subtreeACL);
874     $acl= get_module_permission($acl, "user", $new_dn);
875     if ($this->dn == "new" && chkacl($acl, "create") != ""){
876       $message[]= _("You have no permissions to create a user on this 'Base'.");
877     } elseif ($this->dn != $new_dn && $this->dn != "new"){
878       $acl= get_permissions ($this->dn, $ui->subtreeACL);
879       $acl= get_module_permission($acl, "user", $this->dn);
880       if (chkacl($acl, "create") != ""){
881         $message[]= _("You have no permissions to move a user from the original 'Base'.");
882       }
883     }
885     /* must: sn, givenName, uid */
886     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
887       $message[]= _("The required field 'Name' is not set.");
888     }
890     /* UID already used? */
891     $ldap= $this->config->get_ldap_link();
892     $ldap->cd($this->config->current['BASE']);
893     $ldap->search("(uid=$this->uid)", array("uid"));
894     $ldap->fetch();
895     if ($ldap->count() != 0 && $this->dn == 'new'){
896       $message[]= _("There's already a person with this 'Login' in the database.");
897     }
899     /* In template mode, the uid and givenName are autogenerated... */
900     if (!$this->is_template){
901       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
902         $message[]= _("The required field 'Given name' is not set.");
903       }
904       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
905         $message[]= _("The required field 'Login' is not set.");
906       }
907       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
908         $ldap->cd($this->config->current['BASE']);
909         $ldap->search("(cn=".$this->cn.")", array("uid"));
910         $ldap->fetch();
911         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
912           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
913         }
914       }
915     }
917     /* Check for valid input */
918     if ($this->is_modified && !is_uid($this->uid)){
919       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
920     }
921     if (!is_url($this->labeledURI)){
922       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
923     }
924     if (preg_match ("/[\\\\]/", $this->sn)){
925       $message[]= _("The field 'Name' contains invalid characters.");
926     }
927     if (preg_match ("/[\\\\]/", $this->givenName)){
928       $message[]= _("The field 'Given name' contains invalid characters.");
929     }
931     /* Check phone numbers */
932     if (!is_phone_nr($this->homePhone)){
933       $message[]= _("The field 'Phone' contains an invalid phone number.");
934     }
935     if (!is_phone_nr($this->telephoneNumber)){
936       $message[]= _("The field 'Phone' contains an invalid phone number.");
937     }
938     if (!is_phone_nr($this->facsimileTelephoneNumber)){
939       $message[]= _("The field 'Fax' contains an invalid phone number.");
940     }
941     if (!is_phone_nr($this->mobile)){
942       $message[]= _("The field 'Mobile' contains an invalid phone number.");
943     }
944     if (!is_phone_nr($this->pager)){
945       $message[]= _("The field 'Pager' contains an invalid phone number.");
946     }
948     /* Check for reserved characers */
949     if (preg_match ('/[,+"<>;]/', $this->givenName)){
950       $message[]= _("The field 'Given name' contains invalid characters.");
951   }
952   if (preg_match ('/[,+"<>;]/', $this->sn)){
953     $message[]= _("The field 'Name' contains invalid characters.");
954   }
956   return $message;
957   }
960   /* Indicate whether a password change is needed or not */
961   function password_change_needed()
962   {
963     return ($this->pw_storage != $this->last_pw_storage);
964   }
967   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
968   function load_picture()
969   {
970     /* make connection and read jpegPhoto */
971     $ds= ldap_connect($this->config->current['SERVER']);
972     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
973     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
974       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
975       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
976     }
978     if(isset($this->config->current['TLS']) &&
979         $this->config->current['TLS'] == "true"){
981       ldap_start_tls($ds);
982     }
984     $r= ldap_bind($ds);
985     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
987     /* in case we don't get an entry, load a default picture */
988     $this->set_picture ("./images/default.jpg");
989     $this->jpegPhoto= "*removed*";
991     /* fill data from LDAP */
992     if ($sr) {
993       $ei=ldap_first_entry($ds, $sr);
994       if ($ei) {
995         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
996           $this->photoData= $info[0];
997           $_SESSION['picture']= $this->photoData;
998           $this->jpegPhoto= "";
999         }
1000       }
1001     }
1003     /* close conncetion */
1004     ldap_unbind($ds);
1005   }
1008   /* Load a certificate from LDAP, this is going to be simplified later on */
1009   function load_cert()
1010   {
1011     $ds= ldap_connect($this->config->current['SERVER']);
1012     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1013     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1014       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1015       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1016     }
1017     if(isset($this->config->current['TLS']) &&
1018         $this->config->current['TLS'] == "true"){
1020       ldap_start_tls($ds);
1021     }
1023     $r= ldap_bind($ds);
1024     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1026     if ($sr) {
1027       $ei= @ldap_first_entry($ds, $sr);
1028       
1029       if ($ei) {
1030         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1031           $this->userCertificate= "";
1032         } else {
1033           $this->userCertificate= $info[0];
1034         }
1035       }
1036     } else {
1037       $this->userCertificate= "";
1038     }
1040     ldap_unbind($ds);
1041   }
1044   /* Load picture from file to object */
1045   function set_picture($filename)
1046   {
1047     if (!is_file($filename)){
1048       $filename= "./images/default.jpg";
1049       $this->jpegPhoto= "*removed*";
1050     }
1052     $fd = fopen ($filename, "rb");
1053     $this->photoData= fread ($fd, filesize ($filename));
1054     $_SESSION['picture']= $this->photoData;
1055     $this->jpegPhoto= "";
1057     fclose ($fd);
1058   }
1061   /* Load certificate from file to object */
1062   function set_cert($cert, $filename)
1063   {
1064     $fd = fopen ($filename, "rb");
1065     if (filesize($filename)>0) {
1066       $this->$cert= fread ($fd, filesize ($filename));
1067       fclose ($fd);
1068       $this->is_modified= TRUE;
1069     } else {
1070       print_red(_("Could not open specified certificate!"));
1071     }
1072   }
1074   /* Adapt from given 'dn' */
1075   function adapt_from_template($dn)
1076   {
1077     plugin::adapt_from_template($dn);
1079     /* Get base */
1080     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1082     if ($this->config->current['GOVERNMENTMODE']){
1084       /* Walk through govattrs */
1085       foreach ($this->govattrs as $val){
1087         if (isset($this->attrs["$val"][0])){
1089           /* If attribute is set, replace dynamic parts: 
1090              %sn, %givenName and %uid. Fill these in our local variables. */
1091           $value= $this->attrs["$val"][0];
1093           foreach (array("sn", "givenName", "uid") as $repl){
1094             if (preg_match("/%$repl/i", $value)){
1095               $value= preg_replace ("/%$repl/i",
1096                   $this->parent->$repl, $value);
1097             }
1098           }
1099           $this->$val= $value;
1100         }
1101       }
1102     }
1104     /* Get back uid/sn/givenName */
1105     if ($this->parent != NULL){
1106       $this->uid= $this->parent->uid;
1107       $this->sn= $this->parent->sn;
1108       $this->givenName= $this->parent->givenName;
1109     }
1110   }
1114 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1115 ?>